# -*- coding: utf-8 -*-
# Copyright 2018 JDG <www.yunside.com>
# Created by YGJ <guojian.ye@yunside.com> at 2018/9/5
# ========通道代号========
# xw_async:玄武异步短信通道
# xw_sync:玄武同步短信通道
# md_async:漫道异步短信通道
# md_sync:漫道同步短信通道
# jd_message:玉龙系统自定义消息推送通道
# jd_notification:玉龙系统内部消息推送通道
# jd_mail:玉龙系统邮件发送通道
# jd_qywx_text:企业微信文本信息推送通道
# jd_qywx_textcard:企业微信卡片信息推送通道
# jd_qywx_img:企业微信图片推送通道
# hd_qywx:海大企业微信推送通道
# dingtalk: 玉龙标准钉钉消息推送
# sbt_dingtalk: 双胞胎钉钉消息推送
# =======================

from odoo import models, fields, api
from odoo.exceptions import MissingError
from odoo.osv import expression
import logging

_logger = logging.getLogger(__name__)


class JDGNotifyChannel(models.AbstractModel):
    _name = 'jd.notify.channel'
    _description = u'玉龙科技统一消息发送通道'

    @api.model
    def notify(self, channel_code, receiver=[], body='', subject='', url='', *args, **kwargs):
        """
        统一发送通道，包括短信、企业微信推送、微信公众号推送、小程序推送、系统内置消息推送、邮件发送等。
        Created By YGJ @2018.09.05
        :param channel_code: 发送通道代号。
        :param receiver: 信息接受人，可传多个进行批量发送。同步单独发送需要传递单元素长度数组。
        :param body: 信息内容。
        :param subject: 信息主题、标题，可选。
        :param url: 信息详情链接，可选。
        :param args: 扩展参数。
        :param kwargs: 扩展参数。
        :return:
        """
        try:
            if channel_code and receiver:
                if channel_code == 'xw_async':
                    result = False
                    result_text = ""
                    if receiver and len(receiver) > 0:
                        for mobile in receiver:
                            res = self.env['jd.notify.channel.xw'].send_async(mobile, body)
                            if res:
                                code = res.get('result')
                                if not code:
                                    result_text += res.get('result_text') if res.get('result_text') else ""
                                    result_text += "; "
                                else:
                                    if not result:
                                        result = True
                    else:
                        result_text = "未设置短信接收人！"
                    return {'result': result, 'result_text': result_text}
                elif channel_code == 'xw_sync':
                    result = False
                    result_text = ""
                    if receiver:
                        for mobile in receiver:
                            res = self.env['jd.notify.channel.xw'].send_sync(mobile, body)
                            if res:
                                code = res.get('result')
                                if not code:
                                    result_text += res.get('result_text') if res.get('result_text') else ""
                                    result_text += "; "
                                else:
                                    if not result:
                                        result = True
                    elif not receiver or len(receiver) == 0:
                        result_text = "未设置短信接收人！"
                    return {'result': result, 'result_text': result_text}
                elif channel_code == 'md_async':
                    result = False
                    result_text = ""
                    if receiver and len(receiver) > 0:
                        for mobile in receiver:
                            res = self.env['jd.notify.channel.md'].send_async(mobile, body)
                            if res:
                                code = res.get('result')
                                if not code:
                                    result_text += res.get('result_text') if res.get('result_text') else ""
                                    result_text += "; "
                                else:
                                    if not result:
                                        result = True
                    else:
                        result_text = "未设置短信接收人！"
                    return {'result': result, 'result_text': result_text}
                elif channel_code == 'md_sync':
                    result = False
                    result_text = ""
                    if receiver:
                        for mobile in receiver:
                            res = self.env['jd.notify.channel.md'].send_sync(mobile, body)
                            if res:
                                code = res.get('result')
                                if not code:
                                    result_text += res.get('result_text') if res.get('result_text') else ""
                                    result_text += "; "
                                else:
                                    if not result:
                                        result = True
                    elif not receiver or len(receiver) == 0:
                        result_text = "未设置短信接收人！"
                    return {'result': result, 'result_text': result_text}
                elif channel_code == 'sbt_md_async':
                    result = False
                    result_text = ""
                    if receiver and len(receiver) > 0:
                        mobile = ','.join(receiver)
                        res = self.env['jd.notify.channel.md.sbt'].send_async(mobile, body)
                        if res:
                            code = res.get('result')
                            if not code:
                                result_text += res.get('result_text') if res.get('result_text') else ""
                                result_text += "; "
                            else:
                                if not result:
                                    result = True
                    else:
                        result_text = "未设置短信接收人！"
                    return {'result': result, 'result_text': result_text}
                elif channel_code == 'sbt_md_sync':
                    result = False
                    result_text = ""
                    if receiver:
                        for mobile in receiver:
                            res = self.env['jd.notify.channel.md.sbt'].send_sync(mobile, body)
                            if res:
                                code = res.get('result')
                                if not code:
                                    result_text += res.get('result_text') if res.get('result_text') else ""
                                    result_text += "; "
                                else:
                                    if not result:
                                        result = True
                    elif not receiver or len(receiver) == 0:
                        result_text = "未设置短信接收人！"
                    return {'result': result, 'result_text': result_text}
                elif channel_code == 'jd_message':
                    kwargs.update({'partner_ids': receiver})
                    self.env['jd.notify.channel.message'].post_message(body=body, subject=subject, **kwargs)
                    return {'result': True, 'result_text': "消息推送成功！"}
                elif channel_code == 'jd_notification':
                    kwargs.update({'partner_ids': receiver})
                    self.env['jd.notify.channel.message'].post_notification(body=body, subject=subject, **kwargs)
                    return {'result': True, 'result_text': "消息推送成功！"}
                elif channel_code == 'jd_mail':
                    pass
                elif channel_code == 'jd_qywx_text':
                    pass
                elif channel_code == 'jd_qywx_textcard':
                    pass
                elif channel_code == 'jd_qywx_img':
                    pass
                elif channel_code == 'hd_qywx':
                    return self.env['jd.notify.channel.hd.qywx'].push_text(receiver=receiver, body=body, **kwargs)
                elif channel_code == 'sbt_dingtalk':
                    return self.env['jd.notify.channel.dingtalk.sbt'].push_text(receiver=receiver, body=body, **kwargs)
                else:
                    return {'result': False, 'result_text': "没有匹配的发送通道！"}
            else:
                _logger.info('Channel_code or Receiver is none!')
                return False
        except Exception as e:
            _logger.error('Notify Error: %s', e.message)
            raise MissingError(u'信息发送失败，错误信息为：%s' % (e.message))
