import time

from django.core.paginator import Paginator
from django.views import View

from Model.models import CustomCustomerOrderInfo, CustomCustomerDevice
from Object.ResponseObject import ResponseObject
from Object.TokenObject import TokenObject


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

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

    def validation(self, request, request_dict, operation):
        language = request_dict.get('language', 'cn')
        response = ResponseObject(language)
        if operation == 'getCustomCustomer':  # APP查詢定制客户信息
            return self.get_custom_customer(request_dict, response)
        elif operation == 'addCustomerDevice':  # 定制客户设备扫码添加接口
            return self.add_customer_device(request_dict, response)
        elif operation == 'getCustomerDeviceCount':  # 查询定制客户已扫码添加设备数量接口
            return self.get_customer_device_count(request_dict, response)
        else:
            return response.json(414)

    @staticmethod
    def get_custom_customer(request_dict, response):
        """
        APP查询定制客户信息
        :param request_dict:
        :param response:
        :return:
        """
        order_number = request_dict.get('orderNumber', None)
        if not order_number:
            return response.json(444)
        try:
            custom_customer = CustomCustomerOrderInfo.objects.filter(order_number=order_number).first()
            if not custom_customer:
                return response.json(173)
            device_count = CustomCustomerDevice.objects.filter(c_id=custom_customer.id).count()
            custom_customer_data = {
                'cid': custom_customer.id,
                'quantity': custom_customer.quantity,
                'existsDeviceCount': device_count,
                'unexistsDeviceCount': custom_customer.quantity - device_count
            }
            return response.json(0, custom_customer_data)
        except Exception as e:
            return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))

    def add_customer_device(self, request_dict, response):
        """
        定制客户设备扫码添加接口
        :param request_dict:
        :param response:
        :return:
        """
        # 获取并验证请求中的必要参数
        c_id = request_dict.get('cid')
        full_code = request_dict.get('QRcode', '').strip()

        if not c_id or not full_code:
            return response.json(444, "cId、QRcode")

        # 验证客户信息是否存在
        custom_customer = CustomCustomerOrderInfo.objects.filter(id=c_id).first()
        if not custom_customer:
            return response.json(173)

        custom_customer_device_qs = CustomCustomerDevice.objects.filter(full_code=full_code)
        if custom_customer_device_qs.exists():
            return response.json(174)
        # 创建新设备记录
        try:
            # 检查full_code的格式并提取相关字段
            uid, serial_number, device_type = self.process_full_code(full_code)

            CustomCustomerDevice.objects.create(
                c_id=c_id,
                serial_number=serial_number,
                uid=uid,
                full_code=full_code,
                type=device_type,
                created_time=int(time.time()),
                updated_time=int(time.time())
            )
            device_count = CustomCustomerDevice.objects.filter(c_id=c_id).count()
            return response.json(0, {
                'existsDeviceCount': device_count,
                'unexistsDeviceCount': custom_customer.quantity - device_count
            })
        except Exception as e:
            return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))

    @staticmethod
    def process_full_code(full_code):
        """ 处理full_code, 返回uid和serial_number """
        serial_number = ""
        uid = ""
        device_type = 0
        if len(full_code) == 14:
            serial_number = full_code[:9]
            device_type = int(full_code[-4:], 16)
        elif len(full_code) == 20:
            uid = full_code
        return uid, serial_number, device_type

    @staticmethod
    def get_customer_device_count(request_dict, response):
        """
        查询定制客户已扫码添加设备数量
        :param request_dict:
        :param response:
        :return:
        """
        order_number = request_dict.get('orderNumber', None)
        name = request_dict.get('name', None)

        try:
            if not order_number and not name:
                # 如果没有提供 order_number 和 name，返回所有设备的总数
                device_count = CustomCustomerDevice.objects.count()
            else:
                # 初始查询集
                customer_orders_qs = CustomCustomerOrderInfo.objects.all()

                # 根据 order_number 或 name 过滤
                if order_number:
                    customer_orders_qs = customer_orders_qs.filter(order_number=order_number)
                if name:
                    customer_orders_qs = customer_orders_qs.filter(name=name)

                # 获取 c_id 列表
                c_ids = customer_orders_qs.values_list('id', flat=True)

                # 如果没有匹配的订单，返回设备数量为 0
                if not c_ids:
                    device_count = 0
                else:
                    # 根据 c_id 列表查询设备数量
                    device_count = CustomCustomerDevice.objects.filter(c_id__in=c_ids).count()

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