# -*- coding: utf-8 -*-
# Copyright 2018 JDG <www.yunside.com>
# Created by YGJ <guojian.ye@yunside.com> at 2018/9/6
# ========系统参数========
# jadedragon.notify.channel.sys.url:业务系统域名
# =======================
import logging
import urllib
from odoo.exceptions import MissingError
from odoo import models, api
from odoo import tools
import logging
import urllib
import urllib2

_logger = logging.getLogger(__name__)


class JDGNotifyChannelHaidQYWX(models.AbstractModel):
    _name = 'jd.notify.channel.hd.qywx'
    _description = u'玉龙科技海大企业微信发送通道'

    @api.multi
    def push_text(self, receiver, body, **kwargs):
        """
        文本信息推送。
        :param receiver:工号数组。
        :param body: 纯文本，不能含有转义字符。
        :return:
        """
        try:
            sys_url = self.env['ir.config_parameter'].sudo().get_param("jadedragon.notify.channel.sys.url")
            if not sys_url or sys_url == 'False':
                _logger.warning(u'未配置系统域名，请联系技术人员进行配置！')
                raise Exception(u'未配置系统域名，请联系技术人员进行配置！')
            if receiver and len(receiver) > 0:
                users = ""
                for inx, number in enumerate(receiver):
                    users_str = number
                    if inx != len(receiver) - 1:
                        users_str += "|"
                    users += users_str
                pushcontent = {"userid": str(users), "toparty": "", "totag": "", "msgtype": "text",
                               "text": {"content": "to_replace"}, "safe": 0}
                values = {"pushtype": sys_url, "pushcontent": pushcontent}
                data = urllib.urlencode(values)
                data = data.replace('to_replace', str(body))
                url = "http://wxsk.harriet.com.cn/ModAdpas/push"
                request = urllib2.Request(url, data)
                response = urllib2.urlopen(request)
                result_text = response.read()
                if str(result_text) == '{"errcode":0,"errmsg":"ok","invaliduser":""}':
                    _logger.error('hd qywx push success')
                    return {'result': True, 'result_text': '企业微信推送成功！'}
                else:
                    _logger.error('hd qywx push error:', str(result_text))
                    return {'result': False, 'result_text': '企业微信推送失败，错误信息为：%s' % str(result_text)}
            else:
                raise Exception(u'未指定推送信息接受人！')
        except Exception as e:
            _logger.error('hd qywx push error: %s', e.message)
            return {'result': False, 'result_text': '企业微信推送失败，错误信息为：%s' % e.message}
