#!/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.uidManageResponseObject import uidManageResponseObject
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 = uidManageResponseObject()

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

        token = TokenObject(request_dict.get('token', None))
        if token.code != 0:
            return response.json(token.code)

        if operation == 'create':
            return self.do_create(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)
        else:
            return response.json(404)

    def do_create(self, userID, request_dict, response):

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

        name = request_dict.get('name', None)
        mark = request_dict.get('mark', None)

        if name and mark:
            now_time = int(time.time())
            company_qs = CompanyModel.objects.filter(mark=mark)
            if company_qs.exists():
                return response.json(174)

            secret = self.create_secret(mark)
            print(secret)

            company = CompanyModel(
                name=name,
                mark=mark,
                secret=secret,
                quantity=0,
                add_time=now_time,
                update_time=now_time
            )
            company.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)

        if id:
            name = request_dict.get('name', None)
            quantity = request_dict.get('quantity', None)

            update = {}

            if name:
                update['name'] = name

            if quantity:
                update['quantity'] = quantity

            company_qs = CompanyModel.objects.filter(id=id)
            if company_qs.exists():
                company_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:
            CompanyModel.objects.filter(id=id).delete()
            return response.json(0)
        else:
            return response.json(444)

    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)
        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)

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

        try:
            company = company_qs[0]
            start_1 = sum_Serial_company
            end_1 = int(start_1) + int(quantity)
            serial_qs = SerialNumberModel.objects.filter()[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(
                        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))

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

        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

            company_qs = CompanyModel.objects.filter()
            count = company_qs.count()

            company_qs = company_qs[start: end].values()
            print(company_qs)

            res = {
                'count': count,
                'data': list(company_qs)
            }
            return response.json(0, res)
        else:
            return response.json(444)

    def create_secret(self, mark):
        len1 = len(mark)
        secret = ''
        for i in range(len1):
            secret += CommonService.RandomStr(randomlength=1)
            secret += mark[i]

        print(mark)
        return CommonService.encode_data_without_salt(secret)
