#!/usr/bin/env python3  
# -*- coding: utf-8 -*-  
"""
@Copyright (C) ansjer cop Video Technology Co.,Ltd.All rights reserved.
@AUTHOR: ASJRD018
@NAME: langer
@software: PyCharm
@DATE: 2019/9/26 16:24
@Version: python3.6
@MODIFY DECORD:ansjer dev
@file: Lottery.py
@Contact: chanjunkai@163.com
"""
import json
import time

from django.views.generic import TemplateView

from model.models import phoneNumModel
from object.AliSmsObject import AliSmsObject
from object.RedisObject import RedisObject
from object.ResponseObject import ResponseObject
from object.TokenObject import TokenObject
from service.CommonService import CommonService
from django.db.models import Q
import datetime

'''
   http://192.168.136.40:7724/lottery/authcode?phone=13119657713
   http://192.168.136.40:7724/lottery/login?phone=13119657713&authcode=xxxxxx
   http://192.168.136.40:7724/lottery/draw?token=xx
   http://192.168.136.40:7724/lottery/setAddr?token=xx&addr=地址
   http://192.168.136.40:7724/lottery/index?token=xx&addr=地址
   '''


class AuthCodeView(TemplateView):

    def post(self, request, *args, **kwargs):
        request.encoding = 'utf-8'
        request_dict = json.loads(request.body.decode('utf-8'))
        return self.validate(request_dict)

    def get(self, request, *args, **kwargs):
        request.encoding = 'utf-8'
        request_dict = request.GET
        return self.validate(request_dict)

    def validate(self, request_dict):
        response = ResponseObject()
        return response.json(10, '活动已结束')
        phone = request_dict.get('phone', None)
        now = datetime.datetime.now()
        start_date = datetime.datetime(2019, 10, 1, 0, 0, 0)
        print(start_date)
        end_date = datetime.datetime(2019, 10, 8, 0, 0, 0)
        if start_date > now:
            return response.json(10, '活动未开始')
        # if now > end_date:
        #     return response.json(10, '活动已结束')
        if phone:
            import re
            # ret = re.match(r"1[35678]\d{9}", tel)
            # 由于手机号位数大于11位也能匹配成功，所以修改如下：
            ret = re.match(r"^1[35678]\d{9}$", phone)
            if ret:
                reds = RedisObject()
                phone_redis_key = '{phone}lottery_phone'.format(phone=phone)
                lottery_phone = reds.get_data(phone_redis_key)
                if lottery_phone:
                    return response.json(301)
                identifyingCode = CommonService.RandomStr(6, True)
                aliSms = AliSmsObject()
                sign_ms = 'Ansjer'
                res = aliSms.send_code_sms(phone=phone, code=identifyingCode, sign_name=sign_ms,
                                           temp_msg='SMS_151600991')
                # print(res)
                if res["Code"] == "OK":
                    if reds.set_data(key=phone_redis_key, val=identifyingCode, expire=300) is not True:
                        # if reds.set_data(key=phone + '_identifyingCode', val=identifyingCode, expire=60) is not True:

                        return response.json(10, '生成缓存系统错误')
                    return response.json(0)
                else:
                    return response.json(10, '发送验证码太频繁，或请更换手机')
                    return response.json(10, res["Message"])
            else:
                return response.json(300)
        else:
            return response.json(444)


class loginView(TemplateView):
    def post(self, request, *args, **kwargs):
        request.encoding = 'utf-8'
        request_dict = json.loads(request.body.decode('utf-8'))
        return self.validate(request_dict)

    def get(self, request, *args, **kwargs):
        request.encoding = 'utf-8'
        request_dict = request.GET
        return self.validate(request_dict)

    def validate(self, request_dict):
        response = ResponseObject()
        return response.json(10, '活动已结束')
        phone = request_dict.get('phone', None)
        authcode = request_dict.get('authcode', None)
        if phone and authcode:
            reds = RedisObject()
            phone_redis_key = '{phone}lottery_phone'.format(phone=phone)
            lottery_phone = reds.get_data(phone_redis_key)
            if lottery_phone is not False:
                if authcode == lottery_phone:
                    user = phoneNumModel.objects.filter(phone=phone)
                    tko = TokenObject()
                    res = tko.generate({'userID': phone})
                    if user.exists():
                        reds.del_data(phone_redis_key)
                        return response.json(0, res)
                    else:
                        nowTime = int(time.time())
                        add_data = {
                            'phone': phone,
                            'addTime': nowTime,
                            'updTime': nowTime
                        }
                        try:
                            phoneNumModel.objects.create(**add_data)
                        except:
                            return response.json(404)
                        else:
                            reds.del_data(phone_redis_key)
                            return response.json(0, res)
                else:
                    return response.json(409)
            else:
                return response.json(407)
        else:
            return response.json(444)


class drawView(TemplateView):
    def post(self, request, *args, **kwargs):
        request.encoding = 'utf-8'
        request_dict = json.loads(request.body.decode('utf-8'))
        return self.validate(request_dict)

    def get(self, request, *args, **kwargs):
        request.encoding = 'utf-8'
        request_dict = request.GET
        return self.validate(request_dict)

    def validate(self, request_dict):
        response = ResponseObject()
        token = request_dict.get('token', None)
        tko = TokenObject(token=token)
        now = datetime.datetime.now()
        return response.json(10, '活动已结束')
        start_date = datetime.datetime(2019, 10, 1, 0, 0, 0)
        print(start_date)
        end_date = datetime.datetime(2019, 10, 8, 0, 0, 0)
        if start_date > now:
            return response.json(10, '活动未开始')
        if now > end_date:
            return response.json(10, '活动已结束')

        if tko.code == 0:
            phone = tko.userID
            qs = phoneNumModel.objects.filter(phone=phone, status=0)
            # if True:
            if qs.exists():
                # status c611=>1 , c612=>2 ,不中间=>3
                # 权重
                test = randomMachine()
                # test.setWeight({1: 1, 2: 1, 3: 50})
                # has_chow = test.drawing()
                user = phoneNumModel.objects.filter(phone=phone)
                count_1 = phoneNumModel.objects.filter(status=1).count()
                count_2 = phoneNumModel.objects.filter(status=2).count()
                print('count_1')
                print(count_1)
                print('count_2')
                print(count_2)
                if count_1 >= 5 > count_2:
                    print('type1')
                    # 权重组
                    chow_weight = {2: 1, 3: 25}
                    test.setWeight(chow_weight)
                    has_chow = test.drawing()
                elif count_1 < 5 <= count_2:
                    print('type2')
                    chow_weight = {1: 1, 3: 25}
                    test.setWeight(chow_weight)
                    has_chow = test.drawing()
                elif count_1 == 5 == count_2:
                    print('type3')
                    has_chow = 3
                else:
                    print('type4')
                    chow_weight = {1: 1, 2: 1, 3: 50}
                    test.setWeight(chow_weight)
                    has_chow = test.drawing()
                # 如果抽奖额度满了
                print(has_chow)

                user.update(status=has_chow)
                return response.json(0, {'status': has_chow})
            else:
                # 您已抽过奖
                return response.json(233)
        else:
            return response.json(tko.code)


class indexView(TemplateView):
    def post(self, request, *args, **kwargs):
        request.encoding = 'utf-8'
        request_dict = json.loads(request.body.decode('utf-8'))
        return self.validate(request_dict)

    def get(self, request, *args, **kwargs):
        request.encoding = 'utf-8'
        request_dict = request.GET
        return self.validate(request_dict)

    def validate(self, request_dict):
        response = ResponseObject()
        return response.json(10, '活动已结束')
        token = request_dict.get('token', None)
        tko = TokenObject(token=token)
        if tko.code == 0:
            phone = tko.userID
            # 当前用户信息
            qs = phoneNumModel.objects.filter(phone=phone).values('status', 'addr')
            # 获取所有中奖名单
            phone_list = phoneNumModel.objects.filter(~Q(status=0)).values_list('phone', flat=True)
            if qs.exists():
                status = qs[0]['status']
                # 中奖详情
                # lottery_dict = {
                #
                # }
                return response.json(0, {'status': status, 'phone_list': list(phone_list), 'user': phone,
                                         'addr': qs[0]['addr']})
            else:
                return response.json(10, '您已抽过奖了')
        else:
            return response.json(tko.code)


class setAddrView(TemplateView):
    def post(self, request, *args, **kwargs):
        request.encoding = 'utf-8'
        request_dict = json.loads(request.body.decode('utf-8'))
        return self.validate(request_dict)

    def get(self, request, *args, **kwargs):
        request.encoding = 'utf-8'
        request_dict = request.GET
        return self.validate(request_dict)

    def validate(self, request_dict):
        response = ResponseObject()
        token = request_dict.get('token', None)
        addr = request_dict.get('addr', None)
        return response.json(10, '活动已结束')
        tko = TokenObject(token=token)
        if tko.code == 0:
            phone = tko.userID
            qs = phoneNumModel.objects.filter(phone=phone)
            qs = qs.filter(Q(status=1) | Q(status=2))

            if qs.exists():
                qs.update(addr=addr)
                return response.json(0)
            else:
                return response.json(0, '您未中奖')
        else:
            return response.json(tko.code)


class randomMachine(object):
    import random as rd
    def setWeight(self, weight):
        self.weight = weight
        self.chanceList = []
        for k, v in self.weight.items():
            for t in range(v):
                self.chanceList.append(k)

    def drawing(self):
        r = self.rd.randrange(0, len(self.chanceList))  # 随机数
        # print("随机数 : ", r)
        has_chow = self.chanceList.pop(r)
        # print(has_chow)
        return has_chow

    def graphicsUI(self):
        pass

    def start(self):
        pass
