#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import os
import re
import time

from django.db import transaction
from django.views import View
from django.views.decorators.csrf import csrf_exempt

from Ansjer.config import BASE_DIR
from Model.models import RegionModel, CompanyModel, VPGModel, UIDModel, MacModel, UIDCompanySerialModel
from Object.uidManageResponseObject import uidManageResponseObject
from Object.TokenObject import TokenObject
from Service.CommonService import CommonService
from Service.ModelService import ModelService


class VPGView(View):

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

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

    def validate(self, request_dict, operation):
        token = TokenObject(request_dict.get('token', None))
        response = uidManageResponseObject()

        if token.code != 0:
            return response.json(token.code)

        if operation == 'add':
            return self.do_add(token.userID, request_dict, response)
        elif operation == 'update':
            return self.do_update(token.userID, request_dict, response)
        elif operation == 'delete':
            return self.do_delete(token.userID, request_dict, response)
        elif operation == 'list':
            return self.do_list(token.userID, request_dict, response)
        elif operation == 'uid_list':
            return self.do_uid_list(token.userID, request_dict, response)
        else:
            return response.json(404)

    def do_add(self, userID, request_dict, response):
        # perm = ModelService.check_perm_uid_manage(userID, 0)
        # if not perm:
        #     return response.json(309)

        name = request_dict.get('vpg', None)
        region_id = request_dict.get('region_id', None)
        company_id = request_dict.get('company_id', None)

        if name and region_id and company_id:
            region_qs = RegionModel.objects.filter(id=region_id)
            if not region_qs.exists():
                return response.json(374)

            company_qs = CompanyModel.objects.filter(secret=company_id)
            if not company_qs.exists():
                return response.json(373)

            company = company_qs[0]
            now_time = int(time.time())
            vpgModel = VPGModel(name=name, region_id=region_id, company_id=company.id, add_time=now_time, update_time=now_time)
            vpgModel.save()
            return response.json(0)
        else:
            return response.json(444)

    def do_update(self, userID, request_dict, response):
        # perm = ModelService.check_perm_uid_manage(userID, 0)
        # if not perm:
        #     return response.json(309)

        id = request_dict.get('id', None)
        name = request_dict.get('vpg', None)
        region_id = request_dict.get('region_id', None)
        company_id = request_dict.get('company_id', None)

        if id:
            vpg_qs = VPGModel.objects.filter(id=id)

            if vpg_qs.exists():

                now_time = int(time.time())
                update = {
                    'update_time': now_time
                }

                if name:
                    update['name'] = name

                if region_id:
                    update['region_id'] = region_id

                if company_id:
                    update['company_id'] = company_id

                vpg_qs.update(**update)
                return response.json(0)
            else:
                return response.json(173)
        else:
            return response.json(444)

    def do_delete(self, userID, request_dict, response):
        # perm = ModelService.check_perm_uid_manage(userID, 0)
        # if not perm:
        #     return response.json(309)

        id = request_dict.get('id', None)
        if id:
            vpg_qs = VPGModel.objects.filter(id=id)

            if vpg_qs.exists():
                vpg_qs.delete()
                return response.json(0)
            else:
                return response.json(173)
        else:
            return response.json(444)

    def do_list(self, userID, request_dict, response):
        # perm = ModelService.check_perm_uid_manage(userID, 0)
        # if not perm:
        #     return response.json(309)

        company_id = request_dict.get('company_id', None)
        region_id = request_dict.get('region_id', None)
        page = request_dict.get('page', None)
        line = request_dict.get('limit', None)

        if page and line:
            page = int(page)
            line = int(line)

            start = (page - 1) * line
            end = start + line

            vpg_qs = VPGModel.objects.filter()

            if company_id:
                vpg_qs.filter(company_id=company_id)

            if region_id:
                vpg_qs.filter(region_id=region_id)

            count = vpg_qs.count()
            vpg_qs = vpg_qs.values('id', 'name', 'region__name', 'region_id', 'company__name', 'add_time',
                                   'update_time', 'company__secret', 'uid_count')
            vpg_qs = vpg_qs[start:end]
            # for vpg in vpg_qs:
            #     vpg['uid_count'] = UIDModel.objects.filter(vpg_id=vpg['id']).count()

            res = {
                'count': count,
                'data': list(vpg_qs),
            }

            return response.json(0, res)
        else:
            return response.json(444)


    def do_uid_list(self, userID, request_dict, response):
        vpg_id = request_dict.get('vpg_id', None)
        page = int(request_dict.get('page', None))
        line = int(request_dict.get('limit', None))

        if not vpg_id:
            return response.json(444)

        start = (page - 1) * line
        end = start + line
        uid_qs = UIDModel.objects.filter(vpg_id=vpg_id).values('uid')

        count = VPGModel.objects.get(id=vpg_id).uid_count   # 从vpg表获取uid总数
        uid_qs = uid_qs[start:end]  # 显示条数
        res = {
            'count': count,
            'data': list(uid_qs),
        }
        return response.json(0, res)


@csrf_exempt
def do_upload_uid(request):
    # 上传UID,需要request.FILES,单独提取出来
    # perm = ModelService.check_perm_uid_manage(userID, 0)
    # if not perm:
    #     return response.json(309)

    request.encoding = 'utf-8'
    response = uidManageResponseObject()
    if request.method == "POST":
        request_dict = request.POST
    elif request.method == "GET":
        request_dict = request.GET
    else:
        return response.json(444)
    file = request.FILES.get('file', None)
    vpg_id = request_dict.get('vpg_id', None)

    bulk = []
    add_time = update_time = int(time.time())
    MAC = MacModel.objects.filter().values('id', 'value', 'is_active')[0]   # 获取最新可用的mac
    current_mac = MAC['value']
    if (not MAC['is_active']) or (current_mac[-8:] == 'FF.FF.FF'):
        return response.json(175)

    # path = '/'.join((BASE_DIR, 'static/uid')).replace('\\', '/') + '/'
    # if not os.path.exists(path):
    #     os.makedirs(path)
    # full_path = path + str(file)
    # with open(full_path, 'wb+') as uid_file:
    try:
        for chunk in file.chunks():
            # str_chunk = str(chunk)
            # print('str(chunk):', str_chunk)
            # str_chunk = re.findall("b\'(.*)\'", str_chunk)[0]
            # str_chunk = str_chunk.split('\\r\\n')
            # print('str(chunk):', str_chunk)
            uid_list = re.findall("b\'(.*)\'", str(chunk))[0].split('\\r\\n')
            for uid in uid_list:
                UID = UIDModel(
                    mac=current_mac,
                    uid_extra='',
                    status=0,
                    add_time=add_time,
                    update_time=update_time,
                    area=0,  # 关联vgp表已有区域信息,可以考虑去掉
                    vpg_id=vpg_id,
                )
                if len(uid) == 14:  # 宸云
                    UID.p2p_type = 1
                    UID.uid = uid
                elif len(uid) == 20:    # tutk
                    UID.p2p_type = 2
                    UID.uid = uid
                elif len(uid) == 23:    # 宸云完整uid
                    a = uid.split('-')
                    new_uid = a[0] + a[1] + a[2].split(',')[0]
                    UID.p2p_type = 1
                    UID.uid = new_uid
                    UID.full_uid_code = uid
                bulk.append(UID)
                temp_mac = CommonService.updateMac(current_mac)    # mac地址值+1;后3个字节为FF时返回None
                if temp_mac:
                    current_mac = temp_mac  # 更新赋值写入uid表
                else:
                    temp_mac = current_mac  # 赋值为FF写入mac表
                    break
        with transaction.atomic():
            UIDModel.objects.bulk_create(bulk)  # 批量写入uid数据
            uid_count = UIDModel.objects.filter(vpg_id=vpg_id).count()  # 获取族群下uid的数量
            VPGModel.objects.filter(id=vpg_id).update(uid_count=uid_count)   # 更新vgp表的uid_count
            MacModel.objects.filter().update(value=temp_mac)  # 更新mac表的mac地址值
        return response.json(0)
    except Exception as e:
        print(e)
        return response.json(500, repr(e))