# coding=utf-8

import time
import os
from django.conf import settings
from django.db import models
from django.utils import timezone
from util.wx.wechat import WeChat
from util.exceptions import CustomError


class WechatApplet(models.Model):
    authorizer_appid = models.CharField(max_length=512, verbose_name=u'小程序appid')
    secret = models.CharField(max_length=512, verbose_name=u'小程序秘钥', null=True)

    authorizer_refresh_token = models.CharField(max_length=512, verbose_name=u'刷新令牌', null=True)
    authorizer_access_token = models.CharField(max_length=512, verbose_name=u'令牌', null=True)
    access_token_gtime = models.DateTimeField(verbose_name=u"获取令牌时间", null=True)
    expires_in = models.IntegerField(verbose_name=u'令牌有效期', null=True)

    agent_num = models.CharField(max_length=512, verbose_name=u'商户号', default="")
    agent_key = models.CharField(max_length=512, verbose_name=u'商户密钥', default="")

    cert_serial_no = models.CharField(max_length=512, verbose_name=u'商户证书序列号', default="")
    apiv3_key = models.CharField(max_length=512, verbose_name=u'商户APIv3密钥', default="")

    class Meta:
        db_table = "wechat_applet"
        ordering = ['-id']
        index_together = ()
        verbose_name = u"小程序"
        default_permissions = ()
        permissions = []

    @staticmethod
    def getByAppid(appid):
        instance = WechatApplet.objects.filter(authorizer_appid=appid).first()
        if not instance:
            raise CustomError(u'未找到相应的小程序！')
        return instance

    def getAccessToken(self):
        if self.authorizer_access_token:
            last_time = time.mktime(self.access_token_gtime.timetuple()) + self.expires_in
            now = time.mktime(timezone.now().timetuple())
            if last_time > now:
                return self.authorizer_access_token
        gtime = timezone.now()
        res = WeChat.getAccessToken(self.authorizer_appid, self.secret)
        self.refreshAccessToken(gtime, res['access_token'], res['expires_in'])
        return self.authorizer_access_token

    def refreshAccessToken(self, gtime, access_token, expires_in, refresh_token=''):
        self.authorizer_access_token = access_token
        self.access_token_gtime = gtime
        self.expires_in = expires_in
        self.authorizer_refresh_token = refresh_token
        self.save()

    def generateActivityCode(self, customer_id, activity_id):
        '''生成海报二维码'''
        filename = "{}{}_{}.png".format("wxacode/", activity_id, customer_id)
        full_filename = "{}/{}".format(settings.MEDIA_ROOT, filename)
        if os.path.exists(full_filename):
            return filename
        page = 'pages/index/index'
        filename = WeChat.getActivityCode(self.getAccessToken(), page, customer_id, activity_id)
        return filename

    def generateActivityWXappCode(self, activity_id):
        filename = "{}_{}.png".format("wxacode/", activity_id)
        full_filename = "{}/{}".format(settings.MEDIA_ROOT, filename)
        if os.path.exists(full_filename):
            return filename
        page = 'pages/index/index'
        filename = WeChat.getActivityWXappCode(self.getAccessToken(), page, activity_id)
        return filename

    # def getMsgTemplateId(self, title):
    #     templates = WeChat.getTemplateList(self.getAccessToken())
    #     for template in templates:
    #         if template['title'] == title:
    #             return template['priTmplId']
    #     return ''
    #
    # def sendPayOrderMsg(self, openid, msg_data):
    #     template_id = self.getMsgTemplateId('订单支付成功通知')
    #     if not template_id:
    #         return
    #     data = {
    #         'date3':{'value':msg_data['pay_time'].strftime('%Y-%m-%d %H:%M:%S')},
    #         'phrase4': {'value': msg_data['payment']},
    #         'character_string5': {'value': msg_data['no']},
    #         'amount2':{'value': msg_data['pay_amount']},
    #         'thing7':{'value': msg_data['tips']},
    #     }
    #     page = 'pages/order/order?value=1'
    #     WeChat.sendSubscribeMessage(self.getAccessToken(), openid, template_id, page, data)
