# coding=utf-8

import time
import os
from django.conf import settings
from django.db import models
from django.utils import timezone
from apps.WechatTp.models import WechatTp
from utils.wx.wechat import WeChat
from utils.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'刷新令牌')
    authorizer_access_token = models.CharField(max_length=512, verbose_name=u'令牌')
    access_token_gtime = models.DateTimeField(verbose_name=u"获取令牌时间")
    expires_in = models.IntegerField(verbose_name=u'令牌有效期')

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

    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):
        self.authorizer_access_token = access_token
        self.access_token_gtime = gtime
        self.expires_in = expires_in
        self.save()

    def sendFinishMsg(self, openid, name, address, fault_des, no):
        template_id = settings.WEAPP['message_template_finish']
        if not template_id:
            return
        time = timezone.now().strftime('%Y-%m-%d %H:%M:%S')
        data = {
            'time5': {'value': time},
            'name4':{'value':name},
            'thing3':{'value':address},
            'thing2':{'value': fault_des},
            'character_string7':{'value': no},
        }
        page = 'pages/repairList/repairList?sort=yiwangong&name=已完工'
        WeChat.sendSubscribeMessage(self.getAccessToken(), openid, template_id, page, data)

    def sendWaitCheckMsg(self, openid, name, address, fault_des, no):
        template_id = settings.WEAPP['message_template_wait_check']
        if not template_id:
            return
        data = {
            'character_string12': {'value': no},
            'thing1':{'value':'新报修审核'},
            'thing19':{'value':fault_des},
            'name3':{'value': name},
            'thing10':{'value': address},
        }
        page = '/pages/certificate/certificate'
        WeChat.sendSubscribeMessage(self.getAccessToken(), openid, template_id, page, data)

    def sendDispatchMsg(self, openid, name, address, fault_des, time, no):
        template_id = settings.WEAPP['message_template_dispatch']
        if not template_id:
            return
        data = {
            'character_string1': {'value': no},
            'thing3':{'value':fault_des},
            'time5':{'value':time.strftime('%Y-%m-%d %H:%M:%S')},
            'thing6':{'value': name},
            'thing8':{'value': address},
        }
        page = '/pages/repairList/repairList?sort=wodepaidan&name=我的派单'
        WeChat.sendSubscribeMessage(self.getAccessToken(), openid, template_id, page, data)

    def getWXAppCode(self, company_no):
        page = 'pages/index/index'
        filename = WeChat.getWXAppCode(self.getAccessToken(),page, company_no)
        return filename

    def getDeviceCode(self, device_id, company_no):
        page = 'pages/index/index'
        filename = WeChat.getDeviceCode(self.getAccessToken(),page, device_id, company_no)
        return filename
