#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import json
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, LogModel
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', 'p2p_type', 'platform', 'init_string', 'init_string_app')

        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,单独提取出来

    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)
    p2p_type = request_dict.get('p2p_type', None)
    platform = request_dict.get('platform', '')
    init_string = request_dict.get('init_string', '')
    init_string_app = request_dict.get('init_string_app', '')

    if not all([vpg_id, p2p_type]):
        return response.json(444)

    try:
        bulk = []
        p2p_type = int(p2p_type)
        # 尚云必须输入平台和初始化字符
        if p2p_type == 1 and (not platform or not platform or not init_string_app):
            return response.json(444)
        p2p = '尚云' if p2p_type == 1 else 'tutk'
        area = 1 if vpg_id != '1' else 0    # vpg_id为'1':国内
        add_time = update_time = int(time.time())
        for chunk in file.chunks():
            uid_list = re.findall("b\'(.*)\'", str(chunk))[0].split('\\r\\n')
            for uid in uid_list:
                UID = UIDModel(
                    mac='',
                    uid_extra='',
                    status=0,
                    add_time=add_time,
                    update_time=update_time,
                    area=area,  # 关联vgp表已有区域信息,可以考虑去掉
                    vpg_id=vpg_id,
                    p2p_type=p2p_type,
                    platform=platform,
                    init_string=init_string,
                    init_string_app=init_string_app
                )
                # 尚云完整uid,eg.ACN-000005-FHCGR,VRWEDU -> ACN000005FHCGR,必须包含','
                if p2p == '尚云':
                    if '-' in uid and ',' in uid:
                        UID.full_uid_code = uid
                        uid_split = uid.split('-')
                        uid = uid_split[0] + uid_split[1] + uid_split[2].split(',')[0]
                    else:
                        return response.json(376)
                # tutk uid长度为14或20
                elif len(uid) != 14 and len(uid) != 20:
                    return response.json(376)
                UID.uid = uid
                bulk.append(UID)

        ip = CommonService.get_ip_address(request)
        content = json.loads(json.dumps(request_dict))
        log = {
            'ip': ip,
            'user_id': 1,
            'status': 200,
            'time': add_time,
            'url': 'vpgUid/uid',
            'content': json.dumps(content),
            'operation': '上传{}个{}uid到VPG ID {}'.format(len(uid_list), p2p, vpg_id),
        }
        
        with transaction.atomic():
            LogModel.objects.create(**log)  # 记录操作日志
            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
        return response.json(0)
    except Exception as e:
        print(e)
        return response.json(500, repr(e))
