#!/usr/bin/python3.6
# -*- coding: utf-8 -*-
#
# Copyright (C) 2022 #
# @Time    : 2022/3/9 9:20
# @Author  : ming
# @Email   : zhangdongming@asj6.wecom.work
# @File    : SurveysManageController.py
# @Software: PyCharm
import json
import time

from django.db import transaction
from django.utils.decorators import method_decorator
from django.views.decorators.csrf import csrf_exempt
from django.views.generic.base import View

from Model.models import CompanyModel, VPGModel, UIDModel, UIDCompanySerialModel, CompanySerialModel, \
    LogModel
from Object.ResponseObject import ResponseObject
from Object.TokenObject import TokenObject
from Service.CommonService import CommonService


class SerialView(View):
    @method_decorator(csrf_exempt)
    def dispatch(self, *args, **kwargs):
        return super(SerialView, self).dispatch(*args, **kwargs)

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

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

    def validation(self, request_dict, request, operation):
        response = ResponseObject()
        if operation == 'uploadUid':
            return self.uploadUid(request, request_dict, response)
        else:
            token = TokenObject(request.META.get('HTTP_AUTHORIZATION'))
            if token.code != 0:
                return response.json(token.code)
            response = ResponseObject(returntype='pc')
            if operation == 'company-page':
                return self.company_page(request_dict, response)
            if operation == 'number/page':
                return self.serial_page(request_dict, response)
            if operation == 'vpg-info/page':
                return self.vpg_page(request_dict, response)
            if operation == 'uid-info/page':
                return self.uid_page(request_dict, response)
            return response.json(0)

    @classmethod
    def uploadUid(cls, request, request_dict, response):
        uid_list = request_dict.get('uid_list', 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)

        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'
        add_time = update_time = int(time.time())

        try:
            # 根据vpg关联的region确定area
            region = VPGModel.objects.filter(id=vpg_id).values('region__name')[0]['region__name']
            area = 0 if region == '中国' else 1
            uid_list = uid_list.splitlines()  # 按行('\r', '\r\n', \n')切割字符串返回列表
            bulk = []
            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': 'serial/uploadUid',
                'content': json.dumps(content),
                'operation': '上传{}个{}uid到vpg {}'.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, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))

    @classmethod
    def company_page(cls, request_dict, response):

        isSelect = request_dict.get('isSelect', None)
        if isSelect:
            # 获取企业名称作为选项
            company_qs = CompanyModel.objects.all().values('id', 'name')
            return response.json(0, {'list': list(company_qs)})

        pageNo = request_dict.get('pageNo', None)
        pageSize = request_dict.get('pageSize', None)
        if not all([pageNo, pageSize]):
            return response.json(444)

        page = int(pageNo)
        line = int(pageSize)
        try:
            request_qs = CompanyModel.objects.all()
            if not request_qs.exists():
                return response.json(0, {'list': '', 'total': 0})
            total = request_qs.count()
            company_page = request_qs[(page - 1) * line:page * line].values()
            return response.json(0, {'list': list(company_page), 'total': total})
        except Exception as e:
            print(e)
            return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))

    @classmethod
    def serial_page(cls, request_dict, response):
        company_name = request_dict.get('companyName', None)
        serial_number = request_dict.get('serialNumber', None)
        status = request_dict.get('status', None)

        pageNo = request_dict.get('pageNo', None)
        pageSize = request_dict.get('pageSize', None)
        if not all([pageNo, pageSize]):
            return response.json(444)
        page = int(pageNo)
        line = int(pageSize)

        try:
            company_serial_qs = CompanySerialModel.objects.filter()
            if company_name:
                company_serial_qs = company_serial_qs.filter(company__name=company_name)
            if serial_number:
                company_serial_qs = company_serial_qs.filter(serial_number__contains=serial_number)
            if status:
                status = int(status)
                company_serial_qs = company_serial_qs.filter(status=status)
            if not company_serial_qs.exists():
                return response.json(0, {'list': '', 'total': 0})
            total = company_serial_qs.count()
            serial_number_page = company_serial_qs.order_by('-serial_number')[(page - 1) * line:page * line]. \
                values('serial_number', 'company__name', 'status', 'add_time', 'update_time')
            return response.json(0, {'list': list(serial_number_page), 'total': total})
        except Exception as e:
            print(e)
            return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))

    @classmethod
    def vpg_page(cls, request_dict, response):

        isSelect = request_dict.get('isSelect', None)
        if isSelect:
            # 获取vpg id作为选项
            vpg_qs = VPGModel.objects.all().values('id')
            return response.json(0, {'list': list(vpg_qs)})

        pageNo = request_dict.get('pageNo', None)
        pageSize = request_dict.get('pageSize', None)
        if not all([pageNo, pageSize]):
            return response.json(444)
        page = int(pageNo)
        line = int(pageSize)
        try:
            query = VPGModel.objects.filter()
            if not query.exists():
                return response.json(0, {'list': '', 'total': 0})
            total = query.count()
            vpg_page = query[(page - 1) * line:page * line] \
                .values('id', 'name',
                        'region__name',
                        'region_id',
                        'company__name',
                        'add_time',
                        'update_time',
                        'company__secret',
                        'uid_count')
            if vpg_page.exists():
                for vpg in vpg_page:
                    vpg['shangyun_use_count'] = UIDModel.objects.filter(vpg=vpg['id'], status=2, p2p_type=1).count()
                    vpg['shangyun_unuse_count'] = UIDModel.objects.filter(vpg=vpg['id'], status=0, p2p_type=1).count()
                    vpg['tutk_use_count'] = UIDModel.objects.filter(vpg=vpg['id'], status=2, p2p_type=2).count()
                    vpg['tutk_unuse_count'] = UIDModel.objects.filter(vpg=vpg['id'], status=0, p2p_type=2).count()
                return response.json(0, {'list': list(vpg_page), 'total': total})
            return response.json(173)
        except Exception as e:
            print(e)
            return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))

    @classmethod
    def uid_page(cls, request_dict, response):
        vpg_id = request_dict.get('vpg_id', None)
        status = request_dict.get('status', None)
        serial_number = request_dict.get('serialNumber', None)
        uid = request_dict.get('uid', None)
        p2p_type = request_dict.get('p2pType', None)
        pageNo = request_dict.get('pageNo', None)
        pageSize = request_dict.get('pageSize', None)
        if not all([pageNo, pageSize]):
            return response.json(444)
        page = int(pageNo)
        line = int(pageSize)
        try:
            query = UIDModel.objects.filter()
            if serial_number:
                company_serial_qs = CompanySerialModel.objects.filter(serial_number__contains=serial_number).values()
                if company_serial_qs.exists():
                    cs_id = str(company_serial_qs[0]['id'])
                    uid_company_serial_qs = UIDCompanySerialModel.objects.filter(company_serial_id=cs_id).values(
                        'uid_id')
                    if uid_company_serial_qs.exists():
                        uid_id = uid_company_serial_qs[0]['uid_id']
                        query = query.filter(id=uid_id)
                else:
                    return response.json(0, {'list': '', 'total': 0})
            if vpg_id:
                query = query.filter(vpg_id=int(vpg_id))
            if status:
                query = query.filter(status=int(status))
            if uid:
                query = query.filter(uid__contains=uid)
            if p2p_type:
                query = query.filter(p2p_type=int(p2p_type))
            if not query.exists():
                return response.json(0, {'list': '', 'total': 0})
            total = query.count()
            uid_page = query[(page - 1) * line:page * line]
            result_list = []
            if not uid_page.exists():
                return response.json(0, {'list': '', 'total': 0})
            for vo in uid_page:
                uid_company_serial_qs = UIDCompanySerialModel.objects.filter(uid_id=vo.id).values('uid_id',
                                                                                                  'company_serial_id')
                serial = None
                if uid_company_serial_qs.exists():
                    company_serial_id = uid_company_serial_qs[0]['company_serial_id']
                    company_serial_qs = CompanySerialModel.objects.filter(id=company_serial_id).values()
                    if company_serial_qs.exists():
                        serial = str(company_serial_qs[0]['serial_number'])
                result_list.append({
                    'vpg_id': vo.vpg_id,
                    'id': vo.id,
                    'uid': vo.uid,
                    'serial': serial,
                    'status': vo.status,
                    'area': vo.area,
                    'p2pType': vo.p2p_type,
                    'platform': vo.platform,
                    'fullUidCode': vo.full_uid_code,
                    'init_string': vo.init_string,
                    'init_string_app': vo.init_string_app,
                    'addTime': vo.add_time,
                    'updateTime': vo.update_time,
                })
            return response.json(0, {'list': result_list, 'total': total})

        except Exception as e:
            print(e)
            return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
