# -*- coding: utf-8 -*-
# Copyright 2018 JDG <www.yunside.com>
# Created by LLH <lianghua.liu@yunside.com> at 2019/8/8

"""
微信公众号对接设置
"""

from odoo import models, fields, api
from odoo.exceptions import ValidationError

import requests

import json

import time

import logging
_logger = logging.getLogger(__name__)


class JdWechatPublicSet(models.Model):
    _name = 'jd.wechat.public.set'
    _inherit = 'jdg.abstract.base.data'
    _description = u'公众号设置'

    company_id = fields.Many2one('res.company', string=u'组织', default=False)
    app_id = fields.Char(string=u'AppID', required=True)
    app_secret = fields.Char(string=u'AppSecret', required=True)
    access_token = fields.Char(string=u'AccessToken')
    expires_in = fields.Char(string=u'有效时长')
    time_get = fields.Datetime(string=u'获取时间')
    template_ids = fields.One2many('jd.wechat.public.set.template', 'parent_id', string=u'消息模板')

    @api.multi
    def get_access_token(self):
        """
        获取access_token
        :return:
        """
        self.ensure_one()
        item = self[0]
        token_url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s' % \
                    (item.app_id, item.app_secret)
        token_data = json.loads(requests.get(token_url).content)
        if 'access_token' in token_data:
            item.write({
                'access_token': token_data['access_token'],
                'expires_in': token_data['expires_in'],
                'time_get': fields.Datetime.now()
            })
            return True
        else:
            return False

    @api.model
    def refresh_access_token(self):
        """
        定时任务
        自动根据有效时长刷新access_token
        :return:
        """
        set_recs = self.env['jd.wechat.public.set'].search([])
        for rec in set_recs:
            if rec.get_access_token():
                return True
            else:
                return False

    @api.multi
    def use_access_token(self):
        """
        返回可用的access_token
        返回之前判断access_token是否过期，过期则先刷新，刷新失败则给出提醒
        :return:
        """
        self.ensure_one()
        item = self[0]
        if item.access_token:
            # 判断access_token是否过期
            time_delta = time.mktime(time.strptime(fields.Datetime.now(), "%Y-%m-%d %H:%M:%S")) - time.mktime(
                time.strptime(item.time_get, "%Y-%m-%d %H:%M:%S"))
            if time_delta >= item.expires_in:
                if item.get_access_token():
                    return item.access_token
                else:
                    raise ValidationError(u'获取不到有效的access_token')
            else:
                return item.access_token
        else:
            if item.get_access_token():
                return item.access_token
            else:
                raise ValidationError(u'获取不到有效的access_token')

    @api.multi
    def get_openid_by_code(self, code):
        """
        根据code获取openID
        :return:
        """
        self.ensure_one()
        item = self[0]
        url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid=%s&secret=%s&code=%s&grant_type=authorization_code' \
              % (item.app_id, item.app_secret, code)
        data = json.loads(requests.get(url).content)
        if 'openid' in data:
            return data['openid']
        else:
            return False

    @api.multi
    def send_msg(self, open_id, template_id, msg_data, url=None):
        """
        发送消息给openID用户
        :param open_id:
        :param template_id:
        :param msg_data:
        :param url: 回调url
        :return:
        """
        self.ensure_one()
        item = self[0]

        access_token = item.use_access_token()

        msg_url = 'https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=%s' % access_token
        data = {'touser': open_id,
                'template_id': template_id,
                'data': msg_data}
        if url:
            data['url'] = url
        ans = requests.post(url=msg_url, data=json.dumps(data))
        content = json.loads(ans.content)
        return content


class JdWechatPublicSetTemplate(models.Model):
    _name = 'jd.wechat.public.set.template'
    _description = u'消息模板'

    parent_id = fields.Many2one('jd.wechat.public.set', string=u'公众号设置', ondelete='cascade')
    name = fields.Char(string=u'名称', required=True)
    template_id = fields.Char(string=u'templateId', required=True)
    description = fields.Char(string=u'描述')
    params = fields.Text(string=u'参数说明')
