# -*- coding: utf-8 -*-
# Copyright 2018 JDG <www.yunside.com>
# Created by YGJ <guojian.ye@yunside.com> at 2018/9/5
# ========系统参数========
# jadedragon.notify.channel.xw.url:网关
# jadedragon.notify.channel.xw.user:账号
# jadedragon.notify.channel.xw.pwd:密码
# =======================
import logging
import urllib
from odoo.exceptions import MissingError
from odoo import models, api
from odoo import tools
import datetime
import threading

_logger = logging.getLogger(__name__)


class SMSThread(threading.Thread):
    def __init__(self, sms_url, sms_user, sms_pwd, sms_encode, mobile, content):
        threading.Thread.__init__(self)
        self.sms_url = sms_url
        self.sms_user = sms_user
        self.sms_pwd = sms_pwd
        self.sms_encode = sms_encode
        self.mobile = mobile
        self.content = content

    def run(self):
        text = self.content.encode(self.sms_encode)
        params = urllib.urlencode({
            'to': self.mobile,
            'text': text,
            'msgtype': 1,
        })
        _logger.info('%s?username=%s&password=%s&%s' % (self.sms_url, "******", "**********", params))
        try:
            res = None
            try:
                res = urllib.urlopen(
                    '%s?username=%s&password=%s&%s' % (self.sms_url, self.sms_user, self.sms_pwd, params))
                result_text = res.read()
                if result_text and result_text.strip() == '0':
                    _logger.info('send sms success.')
                    return {'result': True, 'result_text': '短信发送成功！'}
                else:
                    _logger.info('send sms failed. error code %s' % (result_text,))
                    return {'result': False, 'result_text': '短信发送失败，错误信息为：%s' % result_text}
            finally:
                if res:
                    res.close()
        except Exception as e:
            _logger.error('send sms error: %s', e.message)
            return {'result': False, 'result_text': '短信发送失败，错误信息为：%s' % e.message}


class JDGNotifyChannelXW(models.AbstractModel):
    _name = 'jd.notify.channel.xw'
    _description = u'玉龙科技玄武短信发送通道'

    @api.multi
    def send_async(self, mobile=None, text=None):
        """
        玄武短信异步接口。
        :param mobile:
        :param text:
        :return:
        """
        if (not mobile) or (not text):
            _logger.warning('mobile or text is empty.')

        url_rec = self.env['ir.config_parameter'].sudo().get_param("jadedragon.notify.channel.xw.url")
        if not url_rec or url_rec == 'False':
            _logger.warning(u'未配置玄武短信网关，请联系技术人员进行配置！')
            raise Exception(u'未配置玄武短信网关，请联系技术人员进行配置！')
        else:
            sms_url = url_rec
        user_rec = self.env['ir.config_parameter'].sudo().get_param("jadedragon.notify.channel.xw.user")
        if not user_rec or user_rec == 'False':
            _logger.warning(u'系统参数中未配置玄武短信网关登录用户，请联系技术人员进行配置')
            raise Exception(u'未配置玄武短信网关登录用户，请联系技术人员进行配置！')
        else:
            sms_user = user_rec
        pwd_rec = self.env['ir.config_parameter'].sudo().get_param("jadedragon.notify.channel.xw.pwd")
        if not pwd_rec or pwd_rec == 'False':
            _logger.warning(u'系统参数中未配置玄武短信网关登录密码，请联系技术人员进行配置')
            raise Exception(u'未配置玄武短信网关登录密码，请联系技术人员进行配置！')
        else:
            sms_pwd = pwd_rec

        encode = self.env['ir.config_parameter'].sudo().get_param("jadedragon.notify.channel.xw.encode")
        if not encode or encode == 'False':
            _logger.warning(u'未配置漫道短信网关短信编码格式，请联系技术人员进行配置！')
            raise Exception(u'未配置漫道短信网关短信编码格式，请联系技术人员进行配置！')
        else:
            sms_encode = encode

        if sms_url == 'False' or sms_pwd == 'False' or sms_user == 'False' or sms_encode == 'False':
            _logger.warning("未配置玄武短信网关相关信息，请联系技术人员进行配置！")
            raise Exception("未配置玄武短信网关相关信息，请联系技术人员进行配置！")

        if True:
            SMSThread(sms_url, sms_user, sms_pwd, sms_encode, mobile, text).start()
            return {'result': True, 'result_text': '短信发送成功！'}
        else:
            _logger.warning("ignore sms to %s" % mobile)
            _logger.warning("Do not sent sms, Because you are not in prod environment.")
            return {'result': False, 'result_text': '非生产环境不发送短信！'}

    @api.multi
    def send_sync(self, mobile=None, text=None):
        """
        玄武短信同步接口。
        :param mobile:
        :param text:
        :return:
        """
        if (not mobile) or (not text):
            _logger.warning('mobile or text is empty.')

        url_rec = self.env['ir.config_parameter'].sudo().get_param("jadedragon.notify.channel.xw.url")
        if not url_rec or url_rec == 'False':
            _logger.warning(u'未配置玄武短信网关，请联系技术人员进行配置！')
            raise Exception(u'未配置玄武短信网关，请联系技术人员进行配置！')
        else:
            sms_url = url_rec
        user_rec = self.env['ir.config_parameter'].sudo().get_param("jadedragon.notify.channel.xw.user")
        if not user_rec or user_rec == 'False':
            _logger.warning(u'系统参数中未配置玄武短信网关登录用户，请联系技术人员进行配置')
            raise Exception(u'未配置玄武短信网关登录用户，请联系技术人员进行配置！')
        else:
            sms_user = user_rec
        pwd_rec = self.env['ir.config_parameter'].sudo().get_param("jadedragon.notify.channel.xw.pwd")
        if not pwd_rec or pwd_rec == 'False':
            _logger.warning(u'系统参数中未配置玄武短信网关登录密码，请联系技术人员进行配置')
            raise Exception(u'未配置玄武短信网关登录密码，请联系技术人员进行配置！')
        else:
            sms_pwd = pwd_rec

        encode = self.env['ir.config_parameter'].sudo().get_param("jadedragon.notify.channel.xw.encode")
        if not encode or encode == 'False':
            _logger.warning(u'未配置漫道短信网关短信编码格式，请联系技术人员进行配置！')
            raise Exception(u'未配置漫道短信网关短信编码格式，请联系技术人员进行配置！')
        else:
            sms_encode = encode

        if sms_url == 'False' or sms_pwd == 'False' or sms_user == 'False' or sms_encode == 'False':
            _logger.warning("未配置玄武短信网关相关信息，请联系技术人员进行配置！")
            raise Exception("未配置玄武短信网关相关信息，请联系技术人员进行配置！")

        # if tools.config.get('environment', 'dev') == 'prod':
        if True:
            text = text.encode(sms_encode)
            params = urllib.urlencode({
                'to': mobile,
                'text': text,
                'msgtype': 1,
            })
            _logger.info('%s?username=%s&password=%s&%s' % (sms_url, "******", "**********", params))
            try:
                res = None
                try:
                    res = urllib.urlopen(
                        '%s?username=%s&password=%s&%s' % (sms_url, sms_user, sms_pwd, params))
                    result_text = res.read()
                    if result_text and result_text.strip() == '0':
                        _logger.info('send sms success.')
                        return {'result': True, 'result_text': '短信发送成功！'}
                    else:
                        _logger.info('send sms failed. error code %s' % (result_text,))
                        return {'result': False, 'result_text': '短信发送失败，错误信息为：%s' % result_text}
                finally:
                    if res:
                        res.close()
            except Exception as e:
                _logger.error('send sms error: %s', e.message)
                return {'result': False, 'result_text': '短信发送失败，报错信息为：%s' % e.message}
        else:
            _logger.warning("ignore sms to %s" % mobile)
            _logger.warning("Do not sent sms, Because you are not in prod environment.")
            return {'result': False, 'result_text': '非生产环境不发送短信！'}
