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

from django.views import View

from Model.models import RegionModel, CountryModel, LanguageModel, CountryLanguageModel
from Object.uidManageResponseObject import uidManageResponseObject
from Object.TokenObject import TokenObject
from Service.CommonService import CommonService
from Service.ModelService import ModelService


class RegionView(View):

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

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

    def validate(self, request_dict, operation):
        token = TokenObject(request_dict.get('token', None))

        response = uidManageResponseObject()

        if operation == 'getCountry':
            return self.get_country(request_dict, response)
        else:
            if token.code != 0:
                return response.json(token.code)

            if operation == 'add':
                return self.do_add(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)
            elif operation == 'addCountry':
                return self.do_add_country(token.userID, request_dict, response)
            elif operation == 'updateCountry':
                return self.do_update_country(token.userID, request_dict, response)
            elif operation == 'deleteCountry':
                return self.do_delete_country(token.userID, request_dict, response)
            elif operation == 'listCountry':
                return self.do_list_country(token.userID, request_dict, response)
            else:
                return response.json(404)

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

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

        if name:
            region = RegionModel(name=name)
            region.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)
        name = request_dict.get('region', None)

        if id and name:
            region_qs = RegionModel.objects.filter(id=id)
            if region_qs.exists():
                region = region_qs[0]
                region.name = name
                region.save()
                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:
            region_qs = RegionModel.objects.filter(id=id)
            if region_qs.exists():
                region_qs.delete()
                return response.json(0)
            else:
                return response.json(173)
        else:
            return response.json(444)

    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

            region_qs = RegionModel.objects.filter()
            count = region_qs.count()

            region_qs = region_qs[start: end].values()

            res = {
                'count': count,
                'data': list(region_qs)
            }

            return response.json(0, res)
        else:
            return response.json(444)

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

        number = request_dict.get('number', None)
        region_id = request_dict.get('region_id', None)
        countries = request_dict.get('countries', None)
        countries_en = request_dict.get('countries_en', None)

        if number and region_id and countries:
            res = {
                '1': countries,
                '2': countries_en
            }
            now_time = int(time.time())
            # countries = json.loads(countries)

            country_qs =CountryModel.objects.filter(number=number)
            if not country_qs.exists():
                country = CountryModel(number=number, region_id=region_id, add_time=now_time, update_time=now_time, country_name=countries)
                country.save()
            else:
                country = country_qs[0]

            for item in res:
                country_language_qs = CountryLanguageModel.objects.filter(language_id=item, country_id=country.id)
                if not country_language_qs.exists():
                    countryLanguage = CountryLanguageModel(
                        country_name=res[item], language_id=item, country_id=country.id, add_time=now_time, update_time=now_time)
                    countryLanguage.save()
            return response.json(0)
        else:
            return response.json(444)

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

        id = request_dict.get('country_id', None)
        number = request_dict.get('number', None)
        region_id = request_dict.get('region_id', None)
        countries = request_dict.get('countries', None)

        if id and number and region_id and countries:

            country_qs = CountryModel.objects.filter(id=id)
            if not country_qs.exists():
                return response.json(173)

            now_time = int(time.time())
            countries = json.loads(countries)
            country = {
                'number': number,
                'region_id': region_id,
                'update_time': now_time,
            }

            country_qs.update(**country)

            return response.json(0)
        else:
            return response.json(444)

    def do_delete_country(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:
            country_qs = CountryModel.objects.filter(id=id)
            if country_qs.exists():
                country_qs.delete()
                return response.json(0)
            else:
                return response.json(173)
        else:
            return response.json(444)

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

        region_id = request_dict.get('region_id', None)
        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

            region_qs = CountryLanguageModel.objects.filter(language_id=1)
            if region_id:
                region_qs = region_qs.filter(country__region__id=region_id)

            count = region_qs.count()

            if region_qs.exists():
                region_qs = region_qs[start: end].values('country_id', 'country_name', 'country__number', 'country__region__name', 'add_time', 'update_time')
            else:
                region_qs = []
            res = {
                'count': count,
                'data': list(region_qs)
            }

            return response.json(0, res)
        else:
            return response.json(444)

    def get_country(self, request_dict, response):
        type = request_dict.get('type', None)
        token = request_dict.get('token', None)
        time_stamp = request_dict.get('time_stamp', None)

        if token and time_stamp and type:
            token = int(CommonService.decode_data(token))
            time_stamp = int(time_stamp)

            now_time = int(time.time())
            distance = now_time - time_stamp

            if token != time_stamp or distance > 60000 or distance < -60000:  # 为了全球化时间控制在一天内
                return response.json(404)

            lang_qs = LanguageModel.objects.filter(lang=type)

            if not lang_qs.exists():
                lang_qs = LanguageModel.objects.filter(lang='en')

            lang = lang_qs[0]
            country_qs = CountryLanguageModel.objects.filter(language_id=lang.id).values('country_name', 'country__number')

            return response.json(0, list(country_qs))
        else:
            return response.json(444)

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

        country_number = request_dict.get('country_number', None)

        if country_number:
            country_language_qs = CountryLanguageModel.objects.filter(country__number=country_number)
            if country_language_qs.exists():
                country_language_qs = country_language_qs
        pass
