# -*- 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 json
import logging
import urllib
import urllib2
import uuid
from datetime import datetime, timedelta

import requests

from odoo import models, api, fields
from odoo.exceptions import ValidationError
from requests import exceptions
_logger = logging.getLogger(__name__)

"""
玉龙科技-双胞胎钉钉推送接口
"""


class JDGNotifyChannelDingtalkSbt(models.AbstractModel):
    
    _name = 'jd.notify.channel.dingtalk.sbt'
    _description = u'玉龙科技-双胞胎钉钉发送通道'

    
    @api.model
    def push_text(self, receiver, body, **kwargs):
        """
        文本信息推送。
        :param receiver:工号数组。
        :param body: 纯文本，不能含有转义字符。
        :return:
        """
        cr = self.env.cr
        try:
            result = {'result': False, 'result_text': '发送失败'}
            # 系统名称校验
            current_data_node_id = self.env['ir.config_parameter'].sudo().get_param("jadedragon.microapp.data.node.id")
            if int(current_data_node_id) == 1:
                SYSTEM_NAME = 'YZT_NF'
            elif int(current_data_node_id) == 3:
                SYSTEM_NAME = 'YZT_NB'
            else:
                result.update({'result_text': '未识别的数据节点 %s' % current_data_node_id})
                return result
            
            # 接收信息员工校验
            if len(receiver) > 100:
                result.update({'result_text': '接收人员数过多，最大数为100。当前接收人员共%s个' % len(receiver)})

            # 获取推送地址
            ConfigModel = self.env['jd.int.config']
            if hasattr(ConfigModel, 'get_push_link'):
                # 获取接口地址配置
                config = self.env['jd.int.config'].jdg_sudo().get_push_link('dingtalk', 'dingtalk-message')
                link = config['push_link']  # 接口地址
                busid = config['busid']  # 接口编号
                login = config['login']  # 登录名
                password = config['password']  # 密码
                instId = "".join(str(uuid.uuid4()).split('-'))
                userid_list = [{"userid": str(user_id)} for user_id in receiver]
                cr.execute("""
                INSERT INTO jd_notify_channel_message_io(channel, person, content, state, note, create_date)
                VALUES (%s, %s, %s, %s, %s, CURRENT_TIMESTAMP AT TIME ZONE 'UTC')
                RETURNING id
                """, ('dingtalk', ",".join(receiver), body, 'pending', ''))
                io_id = cr.fetchone()[0]
                args = {
                    "common": {
                        "busid": "DTALK0040",
                        "instld": instId,
                        "sender": SYSTEM_NAME,
                        "receiver": "DTALK",
                        "request_time": datetime.strftime(
                            datetime.strptime(fields.Datetime.now(), '%Y-%m-%d %H:%M:%S') + timedelta(hours=8),
                            '%Y%m%d%H%M%S')
                    },
                    "business": {
                        "userid_list": userid_list,
                        "msg": {
                            "msgtype": "text",
                            "text": {"content": body}
                        }
                    }
                }
                request_data = json.dumps(args)
                _logger.info('request_data is %s' % request_data)
                try:
                    response = requests.post(link, data=request_data, headers={"content-type": "application/json"},
                                         auth=(login, password), timeout=5)
                except exceptions.Timeout as e:
                    _logger.error('sbt dingtalk push error %s' % e)
                    result.update({'result_text': '推送钉钉消息超时 %s' % e})
                    cr.execute("""
                    UPDATE jd_notify_channel_message_io
                    SET state = %s, note = %s
                    WHERE id = %s
                                    """, ('failed', '推送钉钉消息超时 %s' % e, io_id))
                    return result
                if not response:
                    cr.execute("""
                    UPDATE jd_notify_channel_message_io
                    SET state = %s, note = %s
                    WHERE id = %s
                    """, ('failed', '推送钉钉消息失败', io_id))
                    result.update({'result_text': '推送钉钉消息失败'})

                response_text = json.loads(response.text)
                
                common = response_text.get('common', {})
                business = response_text.get('business', {})
                returnStatus = common.get('returnStatus')
                errmsg = business.get('errmsg')
                if returnStatus == 'E':
                    cr.execute("""
                    UPDATE jd_notify_channel_message_io
                    SET state = %s, note = %s
                    WHERE id = %s
                                        """, ('failed', '推送钉钉消息失败 %s' % errmsg, io_id))
                    result.update({'result_text': '推送钉钉消息失败 %s' % errmsg})
                    return result
                elif returnStatus == 'S':
                    cr.execute("""
                    UPDATE jd_notify_channel_message_io
                    SET state = %s, note = %s
                    WHERE id = %s
                    """, ('success', '推送钉钉消息成功', io_id))
                    result.update({'result': True, 'result_text': '推送钉钉消息成功'})
                    return result

            else:
                result.update({'result_text': '不是双胞胎钉钉推送格式'})
                return result
        except Exception as e:
            _logger.error('sbt dingtalk push error: %s', e.message)
            cr.execute("""
            UPDATE jd_notify_channel_message_io
            SET state = %s, note = %s
            WHERE id = %s
            """, ('failed', '钉钉消息推送失败，错误信息为：%s' % e.message, io_id))
            return {'result': False, 'result_text': '钉钉消息推送失败，错误信息为：%s' % e.message}
    
    