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

from django.db import transaction
from django.views import View

from Model.models import CompanyModel, UserModel, SerialNumberModel, CompanySerialModel
from Object.ResponseObject import ResponseObject
from Object.TokenObject import TokenObject
from Service.CommonService import CommonService
from Service.ModelService import ModelService


class CompanyView(View):

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

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

    def validate(self, request_dict, operation):
        response = ResponseObject()
        if operation == 'createSerial':
            return self.do_create_serial(request_dict, response)

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

        id = request_dict.get('id', None)
        p2p = request_dict.get('p2p', None)
        quantity = request_dict.get('quantity', None)

        if not all([id, quantity]):
            return response.json(444)

        company_qs = CompanyModel.objects.filter(id=id)
        if not company_qs.exists():
            return response.json(444)

        p2p_sum_Serial = SerialNumberModel.objects.filter(p2p=p2p).count()
        p2p_sum_Serial_company = CompanySerialModel.objects.filter(p2p=p2p).count()
        p2p_sum_bind = p2p_sum_Serial - p2p_sum_Serial_company  # 剩余可绑定的序列号
        if int(quantity) > int(p2p_sum_bind):
            return response.json(10041)

        try:
            company = company_qs[0]
            start_1 = p2p_sum_Serial_company
            end_1 = int(start_1) + int(quantity)
            serial_qs = SerialNumberModel.objects.filter(p2p=p2p)[start_1:end_1]
            if serial_qs.exists():
                company_serial_bulk = []
                now_time = int(time.time())
                for item in serial_qs:
                    company_serial_bulk.append(CompanySerialModel(
                        p2p=p2p,
                        status=1,
                        add_time=now_time,
                        update_time=now_time,
                        company_id=company.id,
                        serial_number=item.serial_number,
                    ))
                with transaction.atomic():
                    CompanySerialModel.objects.bulk_create(company_serial_bulk)
                    company.quantity = CompanySerialModel.objects.filter(company_id=id).count()
                    company.save()
                return response.json(0)
            else:
                return response.json(173)
        except Exception as e:
            djangoLogger = logging.getLogger('django')
            djangoLogger.exception(repr(e))
            return response.json(176, str(e))
