#!/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

import requests
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, iotdeviceInfoModel, UidSetModel
from Object.ResponseObject import ResponseObject
from Object.TokenObject import TokenObject
from Service.CommonService import CommonService
from Ansjer.config import SERVER_DOMAIN_TEST, SERVER_DOMAIN_CN, SERVER_DOMAIN_US, SERVER_DOMAIN_EUR


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)
        elif operation == 'getSerialData':  # 获取需要同步的序列号数据
            return self.getSerialData(request_dict, response)
        elif operation == 'unbindUid':  # 解绑序列号
            return self.unbind_uid(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 == 'syncSerial':   # 同步序列号数据
                return self.sync_serial(request, 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(414)

    @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 in ['中国', '测试'] 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)))

    @staticmethod
    def sync_serial(request, request_dict, response):
        serial = request_dict.get('serial', None)
        sync_region = request_dict.get('syncRegion', None)
        if not all([serial, sync_region]):
            return response.json(444)

        # 判断序列号是否已绑定uid
        uid_company_serial_qs = UIDCompanySerialModel.objects.filter(company_serial__serial_number=serial)
        if uid_company_serial_qs.exists():
            return response.json(174)

        if sync_region == 'test':
            url = SERVER_DOMAIN_TEST
        elif sync_region == 'cn':
            url = SERVER_DOMAIN_CN
        elif sync_region == 'us':
            url = SERVER_DOMAIN_US
        elif sync_region == 'eu':
            url = SERVER_DOMAIN_EUR
        else:
            return response.json(444)

        try:
            # 请求需要同步的地区获取数据
            url = url + 'serial/getSerialData'
            data = {'serial': serial}
            req = requests.post(url=url, data=data, timeout=5)
            if req.status_code != 200:
                return response.json(503)
            req = req.json()
            if req['result_code'] != 0:
                return response.json(173)
            res_data = req['result']['res_data']

            # 查询是否存在该uid,存在修改状态为已使用,否则写入数据
            uid = res_data['uid']
            uid_qs = UIDModel.objects.filter(uid=uid).values('id')
            with transaction.atomic():
                if uid_qs.exists():
                    uid_qs.update(status=2)
                    uid_id = uid_qs[0]['id']
                else:
                    uid_data = {
                        'uid': uid,
                        'mac': res_data['mac'],
                        'uid_extra': res_data['uid_extra'],
                        'status': res_data['status'],
                        'add_time': res_data['add_time'],
                        'update_time': res_data['update_time'],
                        'area': res_data['area'],
                        'vpg_id': res_data['vpg_id'],
                        'p2p_type': res_data['p2p_type'],
                        'full_uid_code': res_data['full_uid_code'],
                        'platform': res_data['platform'],
                        'init_string': res_data['init_string'],
                        'init_string_app': res_data['init_string_app']
                    }
                    uid_obj = UIDModel.objects.create(**uid_data)
                    uid_id = uid_obj.id

                # 查询tb_company_serial表id
                company_serial_qs = CompanySerialModel.objects.filter(serial_number=serial).values('id')
                company_serial_id = company_serial_qs[0]['id']
                # 序列号绑定uid
                now_time = int(time.time())
                UIDCompanySerialModel.objects.create(add_time=now_time, update_time=now_time,
                                                     uid_id=uid_id, company_serial_id=company_serial_id)
                # 修改序列号状态为绑定uid
                company_serial_qs.update(status=2)

                # 同步iot数据
                if res_data.get('certificate_id'):
                    iot_device_info_qs = iotdeviceInfoModel.objects.filter(serial_number=serial).\
                        values('certificate_id')
                    iot_data = {
                        'certificate_id': res_data['certificate_id'],
                        'certificate_pem': res_data['certificate_pem'],
                        'public_key': res_data['public_key'],
                        'private_key': res_data['private_key'],
                        'thing_name': res_data['thing_name'],
                        'thing_groups': res_data['thing_groups'],
                        'endpoint': res_data['endpoint'],
                        'token_iot_number': res_data['token_iot_number']
                    }
                    if iot_device_info_qs.exists():
                        if iot_device_info_qs[0]['certificate_id'] != res_data['certificate_id']:
                            iot_device_info_qs.update(**iot_data)
                    else:
                        iot_data['serial_number'] = serial
                        iotdeviceInfoModel.objects.create(**iot_data)

                # 同步uid_set数据
                if res_data.get('uid_set') is not None:
                    uid_set_qs = UidSetModel.objects.filter(uid=uid)
                    uid_set_data = {
                        'channel': res_data['uid_set']['channel'],
                        'detect_status': res_data['uid_set']['detect_status'],
                        'detect_interval': res_data['uid_set']['detect_interval'],

                        'addTime': res_data['uid_set']['addTime'],
                        'updTime': res_data['uid_set']['updTime'],
                        'ucode': res_data['uid_set']['ucode'],

                        'version': res_data['uid_set']['version'],
                        'p2p_region': res_data['uid_set']['p2p_region'],
                        'tz': res_data['uid_set']['tz'],

                        'video_code': res_data['uid_set']['video_code'],
                        'nickname': res_data['uid_set']['nickname'],
                        'ip': res_data['uid_set']['ip'],

                        'detect_group': res_data['uid_set']['detect_group'],
                        'pwd': res_data['uid_set']['pwd'],
                        'resetTime': res_data['uid_set']['resetTime'],

                        'region_alexa': res_data['uid_set']['region_alexa'],
                        'deviceModel': res_data['uid_set']['deviceModel'],
                        'TimeZone': res_data['uid_set']['TimeZone'],

                        'TimeStatus': res_data['uid_set']['TimeStatus'],
                        'SpaceUsable': res_data['uid_set']['SpaceUsable'],
                        'SpaceSum': res_data['uid_set']['SpaceSum'],

                        'MirrorType': res_data['uid_set']['MirrorType'],
                        'RecordType': res_data['uid_set']['RecordType'],
                        'OutdoorModel': res_data['uid_set']['OutdoorModel'],

                        'WIFIName': res_data['uid_set']['WIFIName'],
                        'isDetector': res_data['uid_set']['isDetector'],
                        'DetectorRank': res_data['uid_set']['DetectorRank'],

                        'is_human': res_data['uid_set']['is_human'],
                        'is_custom_voice': res_data['uid_set']['is_custom_voice'],
                        'double_wifi': res_data['uid_set']['double_wifi'],

                        'isSupportFourPoint': res_data['uid_set']['isSupportFourPoint'],
                        'mobile_4g': res_data['uid_set']['mobile_4g'],
                        'is_ptz': res_data['uid_set']['is_ptz'],

                        'is_ai': res_data['uid_set']['is_ai'],
                        'cloud_vod': res_data['uid_set']['cloud_vod'],
                        'is_alexa': res_data['uid_set']['is_alexa'],

                        'is_notification': res_data['uid_set']['is_notification'],
                        'new_detect_interval': res_data['uid_set']['new_detect_interval'],
                        'tb_country': res_data['uid_set']['tb_country'],

                        'device_type': res_data['uid_set']['device_type'],
                        'ai_type': res_data['uid_set']['ai_type'],
                        'msg_notify': res_data['uid_set']['msg_notify']
                    }
                    if uid_set_qs.exists():
                        uid_set_qs.update(**uid_set_data)
                    else:
                        uid_set_data['uid'] = uid
                        UidSetModel.objects.create(**uid_set_data)

                # 记录操作日志
                ip = CommonService.get_ip_address(request)
                content = json.loads(json.dumps(request_dict))
                log = {
                    'ip': ip,
                    'user_id': 1,
                    'status': 200,
                    'time': now_time,
                    'url': 'serial/syncSerial',
                    'content': json.dumps(content),
                    'operation': '序列号{}同步{}服数据'.format(serial, sync_region)
                }
                LogModel.objects.create(**log)
            return response.json(0)
        except Exception as e:
            return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))

    @staticmethod
    def getSerialData(request_dict, response):
        serial = request_dict.get('serial', None)
        if not serial:
            return response.json(444)

        try:
            # 查询绑定的uid数据
            uid_company_serial_qs = UIDCompanySerialModel.objects.filter(company_serial__serial_number=serial).\
                values('uid__uid', 'uid__mac', 'uid__uid_extra', 'uid__status', 'uid__add_time', 'uid__update_time',
                       'uid__area', 'uid__vpg_id', 'uid__p2p_type', 'uid__full_uid_code', 'uid__platform',
                       'uid__init_string', 'uid__init_string_app')
            if not uid_company_serial_qs.exists():
                return response.json(173)

            uid = uid_company_serial_qs[0]['uid__uid']

            res_data = {
                'uid': uid,
                'mac': uid_company_serial_qs[0]['uid__mac'],
                'uid_extra': uid_company_serial_qs[0]['uid__uid_extra'],
                'status': uid_company_serial_qs[0]['uid__status'],
                'add_time': uid_company_serial_qs[0]['uid__add_time'],
                'update_time': uid_company_serial_qs[0]['uid__update_time'],
                'area': uid_company_serial_qs[0]['uid__area'],
                'vpg_id': uid_company_serial_qs[0]['uid__vpg_id'],
                'p2p_type': uid_company_serial_qs[0]['uid__p2p_type'],
                'full_uid_code': uid_company_serial_qs[0]['uid__full_uid_code'],
                'platform': uid_company_serial_qs[0]['uid__platform'],
                'init_string': uid_company_serial_qs[0]['uid__init_string'],
                'init_string_app': uid_company_serial_qs[0]['uid__init_string_app']
            }

            # 查询iot数据
            iot_device_info_qs = iotdeviceInfoModel.objects.filter(serial_number=serial).values(
                'certificate_id', 'certificate_pem', 'public_key', 'private_key', 'thing_name',
                'thing_groups', 'endpoint', 'token_iot_number')
            if iot_device_info_qs.exists():
                res_data['certificate_id'] = iot_device_info_qs[0]['certificate_id']
                res_data['certificate_pem'] = iot_device_info_qs[0]['certificate_pem']
                res_data['public_key'] = iot_device_info_qs[0]['public_key']
                res_data['private_key'] = iot_device_info_qs[0]['private_key']
                res_data['thing_name'] = iot_device_info_qs[0]['thing_name']
                res_data['thing_groups'] = iot_device_info_qs[0]['thing_groups']
                res_data['endpoint'] = iot_device_info_qs[0]['endpoint']
                res_data['token_iot_number'] = iot_device_info_qs[0]['token_iot_number']

            # 查询uid_set数据
            uid_set_qs = UidSetModel.objects.filter(uid=uid).values()
            if uid_set_qs.exists():
                res_data['uid_set'] = {}

                res_data['uid_set']['channel'] = uid_set_qs[0]['channel']
                res_data['uid_set']['detect_status'] = uid_set_qs[0]['detect_status']
                res_data['uid_set']['detect_interval'] = uid_set_qs[0]['detect_interval']

                res_data['uid_set']['addTime'] = uid_set_qs[0]['addTime']
                res_data['uid_set']['updTime'] = uid_set_qs[0]['updTime']
                res_data['uid_set']['ucode'] = uid_set_qs[0]['ucode']

                res_data['uid_set']['version'] = uid_set_qs[0]['version']
                res_data['uid_set']['p2p_region'] = uid_set_qs[0]['p2p_region']
                res_data['uid_set']['tz'] = uid_set_qs[0]['tz']

                res_data['uid_set']['video_code'] = uid_set_qs[0]['video_code']
                res_data['uid_set']['nickname'] = uid_set_qs[0]['nickname']
                res_data['uid_set']['ip'] = uid_set_qs[0]['ip']

                res_data['uid_set']['detect_group'] = uid_set_qs[0]['detect_group']
                res_data['uid_set']['pwd'] = uid_set_qs[0]['pwd']
                res_data['uid_set']['resetTime'] = uid_set_qs[0]['resetTime']

                res_data['uid_set']['region_alexa'] = uid_set_qs[0]['region_alexa']
                res_data['uid_set']['deviceModel'] = uid_set_qs[0]['deviceModel']
                res_data['uid_set']['TimeZone'] = uid_set_qs[0]['TimeZone']

                res_data['uid_set']['TimeStatus'] = uid_set_qs[0]['TimeStatus']
                res_data['uid_set']['SpaceUsable'] = uid_set_qs[0]['SpaceUsable']
                res_data['uid_set']['SpaceSum'] = uid_set_qs[0]['SpaceSum']

                res_data['uid_set']['MirrorType'] = uid_set_qs[0]['MirrorType']
                res_data['uid_set']['RecordType'] = uid_set_qs[0]['RecordType']
                res_data['uid_set']['OutdoorModel'] = uid_set_qs[0]['OutdoorModel']

                res_data['uid_set']['WIFIName'] = uid_set_qs[0]['WIFIName']
                res_data['uid_set']['isDetector'] = uid_set_qs[0]['isDetector']
                res_data['uid_set']['DetectorRank'] = uid_set_qs[0]['DetectorRank']

                res_data['uid_set']['is_human'] = uid_set_qs[0]['is_human']
                res_data['uid_set']['is_custom_voice'] = uid_set_qs[0]['is_custom_voice']
                res_data['uid_set']['double_wifi'] = uid_set_qs[0]['double_wifi']

                res_data['uid_set']['isSupportFourPoint'] = uid_set_qs[0]['isSupportFourPoint']
                res_data['uid_set']['mobile_4g'] = uid_set_qs[0]['mobile_4g']
                res_data['uid_set']['is_ptz'] = uid_set_qs[0]['is_ptz']

                res_data['uid_set']['is_ai'] = uid_set_qs[0]['is_ai']
                res_data['uid_set']['cloud_vod'] = uid_set_qs[0]['cloud_vod']
                res_data['uid_set']['is_alexa'] = uid_set_qs[0]['is_alexa']

                res_data['uid_set']['is_notification'] = uid_set_qs[0]['is_notification']
                res_data['uid_set']['new_detect_interval'] = uid_set_qs[0]['new_detect_interval']
                res_data['uid_set']['tb_country'] = uid_set_qs[0]['tb_country']

                res_data['uid_set']['device_type'] = uid_set_qs[0]['device_type']
                res_data['uid_set']['ai_type'] = uid_set_qs[0]['ai_type']
                res_data['uid_set']['msg_notify'] = uid_set_qs[0]['msg_notify']

            # 修改序列号状态为占用,uid状态为3(数据被同步)
            CompanySerialModel.objects.filter(serial_number=serial).update(status=3)
            UIDModel.objects.filter(uid=uid).update(status=3)

            return response.json(0, {'res_data': res_data})
        except Exception as 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)))

    def unbind_uid(self, request_dict, response):
        serial_number = request_dict.get('serialNumber', None)
        try:
            # Step 1: 查找并更新序列号状态
            CompanySerialModel.objects.filter(serial_number=serial_number).update(status=3,
                                                                                  update_time=int(time.time()))
            # Step 2: 解绑UID与序列号的关联
            UIDCompanySerialModel.objects.filter(company_serial__serial_number=serial_number).delete()
        except CompanySerialModel.DoesNotExist:
            return response.json(173)

        return response.json(0)
