#coding=utf-8

from django.conf import settings
from django.contrib.auth import get_user_model
from util.wx.wechat import WeChat
from util.wx.WXBizDataCrypt import WXBizDataCrypt

from apps.exceptions import CustomError

from apps.activity.models import Activity
from apps.WechatApplet.models import WechatApplet
from apps.customer.models import Customer, CustomerWechat

User = get_user_model()


class WechatHandel(object):
    @staticmethod
    def login(code, appid, activity_id):
        app = WechatApplet.getByAppid(appid)
        if activity_id:
            activity = Activity.objects.filter(id=activity_id, delete=False, check_status=settings.PASS).first()
            if not activity:
                activity = Activity.objects.filter(delete=False, check_status=settings.PASS).order_by('-create_time').first()
        else:
            activity = Activity.objects.filter(delete=False, check_status=settings.PASS).order_by('-create_time').first()

        if not activity:
            raise CustomError(u'未找到活动！')

        res = WeChat.code2Session(appid, app.secret, code)
        instance = CustomerWechat.objects.filter(openid=res['openid'], branch=activity.branch).first()
        if not instance:
            instance = CustomerWechat.objects.create(
                branch=activity.branch,
                openid=res['openid'],
                session_key=res['session_key']
            )
        else:
            instance.session_key = res['session_key']
            instance.save()
        return instance, activity.id

    @staticmethod
    def bindWechat(appid, openid, phoneEncryptedData, phoneIv, activity_id):
        WechatApplet.getByAppid(appid)
        activity = Activity.objects.filter(id=activity_id).first()
        if not activity:
            raise CustomError(u'未找到相应的活动')

        customer_wechat = CustomerWechat.objects.filter(openid=openid, branch=activity.branch).first()
        if not customer_wechat:
            raise CustomError(u'未找到相应的微信客户！')

        pc = WXBizDataCrypt(appid, customer_wechat.session_key)
        phon_data = pc.decrypt(phoneEncryptedData, phoneIv)

        tel = phon_data['purePhoneNumber']

        if customer_wechat.customer:
            if customer_wechat.customer.user.username != tel:
                raise CustomError(u'微信绑定的手机号与系统记录的不符！')
            else:
                return customer_wechat.customer
        user = User.objects.filter(username=tel).first()
        if not user:
            user = User.objects.create_user(User.CUSTOMER, tel, password=tel, **{'name': tel, 'tel': tel})

        customer = Customer.objects.filter(branch=customer_wechat.branch, user=user).first()
        if not customer:
            customer = Customer.objects.create(branch=customer_wechat.branch, user=user, name=tel, tel=tel)

        customer_wechat.customer = customer
        customer_wechat.save()
        return customer
