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

from django.views.generic.base import TemplateView

from model.models import LangClassModel, LangKeyModel, LangAreaModel, LangValModel, LangKeyClassModel, \
    LangLocationModel, UserModel
from object.ResponseObject import ResponseObject
from object.TokenObject import TokenObject


class LangAVSSView(TemplateView):
    def post(self, request, *args, **kwargs):
        request.encoding = 'utf-8'
        operation = kwargs.get('operation', None)
        request_dict = json.loads(request.body.decode('utf-8'))
        return self.validate(request_dict, operation)

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

    def validate(self, request_dict, operation):
        response = ResponseObject()
        if operation == 'add':
            return self.do_add(request_dict, response)
        elif operation == 'delete':
            return self.do_delete(request_dict, response)
        elif operation == 'add_single':
            return self.do_add_single(request_dict, response)
        elif operation == 'translate':
            return self.do_translate(request_dict, response)
        else:
            return response.json(404)

    def do_add(self, request_dict, response):
        data = request_dict.get('data', None)
        print(data)
        if data:
            data = json.loads(data)
            keys = data.keys()
            for key in keys:
                # 取出模块，每个context
                langClass = data[key]
                # print(langClass['name'])

                lc_qs = LangClassModel.objects.filter(name=key)
                if not lc_qs.exists():
                    LangClassModel.objects.create(**{'name': key})

                langClassModel = LangClassModel.objects.get(name=key)

                # 每个context里面的语言
                languages = langClass['languages']
                # print(languages)
                langKeys = languages.keys()
                for langKey in langKeys:
                    # print(langKey)

                    # 取出每个语言
                    language = languages[langKey]
                    # print(language)
                    lk_qs = LangKeyModel.objects.filter(word_key=langKey)
                    lkModel = None
                    if lk_qs.exists():
                        lkModel = lk_qs[0]
                        lkModel.type = 2
                        lkModel.save()

                    else:
                        # 插入新的key
                        addTime = int(time.time())
                        lk = {
                            'word_key': language['source'],
                            'addTime': addTime,
                            'updTime': addTime,
                            'type': 1,
                        }
                        lkModel = LangKeyModel.objects.create(**lk)
                        # lkModel = lkModel[0]
                        translations = language['translation']
                        for translation in translations:
                            la_id = translation['la_id']
                            val = translation['val']
                            langArea = LangAreaModel.objects.filter(id=la_id)[0]
                            # 插入key对应的value
                            # 插入新的key
                            addTime = int(time.time())
                            langValue = {
                                'lk': lkModel,
                                'la': langArea,
                                'word_val': val,
                                'addTime': addTime,
                                'updTime': addTime,
                                'status': 1
                            }
                            LangValModel.objects.create(**langValue)

                    # 语言的key
                    # print('source = ' + language['source'])
                    # 语言的value
                    # print('translation = ' + language['translation'])

                    lkc_qs = LangKeyClassModel.objects.filter(lk__id=lkModel.id, clazz__id=langClassModel.id)
                    if not lkc_qs.exists():
                        # 创建langClass和langKey的映射关系
                        langKeyClass = {
                            'lk': lkModel,
                            'clazz': langClassModel
                        }
                        LangKeyClassModel.objects.create(**langKeyClass)

                        # 语言的在代码中的位置
                        locations = language['locations']
                        for location in locations:
                            # print(location['filename'])
                            # print(location['line'])
                            langlocaltionmodel = LangLocationModel.objects.filter(lk=lkModel.id,
                                                                                  filename=location['filename'])
                            if langlocaltionmodel.exists():
                                langlocaltionmodel.update(line=location['line'])
                            else:
                                locationValue = {
                                    'lk': lkModel,
                                    'filename': location['filename'],
                                    'line': location['line']
                                }
                                LangLocationModel.objects.create(**locationValue)
            return response.json(0)
        else:
            return response.json(444)

    def do_add_single(self, request_dict, response):
        word_class = request_dict.get('word_class', None)
        word_key = request_dict.get('word_key', None)
        word_array = request_dict.get('word_array', None)
        location_array = request_dict.get('location_array', None)

        if word_class and word_key and word_array and location_array:
            # 判断lang_class是否存在
            lc_qs = LangClassModel.objects.filter(name=word_class)
            if not lc_qs.exists():
                LangClassModel.objects.create(**{'name': word_class})

            langClassModel = LangClassModel.objects.get(name=word_class)

            # 取出每个语言
            lk_qs = LangKeyModel.objects.filter(word_key=word_key)
            lkModel = None
            if lk_qs.exists():
                lkModel = lk_qs[0]
                lkModel.type = lkModel.type | 2
                lkModel.save()
                # if lkModel.type == 0:
                #     lkModel.type = 2

            else:
                # 插入新的key
                addTime = int(time.time())
                lk = {
                    'word_key': word_key,
                    'addTime': addTime,
                    'updTime': addTime,
                    'type': 2,
                }
                lkModel = LangKeyModel.objects.create(**lk)
                # lkModel = lkModel[0]
            translations = list(word_array)
            for translation in translations:
                la_id = translation['la_id']
                val = translation['val']
                addTime = int(time.time())
                langval = LangValModel.objects.filter(la=la_id, lk=lkModel.id)
                if langval.exists():
                    langval.update(word_val=val, updTime=addTime)
                else:
                    # 插入key对应的value
                    # 插入新的key
                    langarea = LangAreaModel.objects.filter(id=la_id)[0]
                    langValue = {
                        'lk': lkModel,
                        'la': langarea,
                        'word_val': val,
                        'addTime': addTime,
                        'updTime': addTime,
                        'status': 1
                    }
                    LangValModel.objects.create(**langValue)

            lkc_qs = LangKeyClassModel.objects.filter(lk__id=lkModel.id, clazz__id=langClassModel.id)
            if not lkc_qs.exists():
                # 创建langClass和langKey的映射关系
                langKeyClass = {
                    'lk': lkModel,
                    'clazz': langClassModel
                }
                LangKeyClassModel.objects.create(**langKeyClass)

                # 语言的在代码中的位置
            locations = list(location_array)
            for location in locations:
                # print(location['filename'])
                # print(location['line'])
                langlocation = LangLocationModel.objects.filter(lk=lkModel.id, filename=location['filename'])
                if langlocation.exists():
                    langlocation.update(line=location['line'])
                else:
                    locationValue = {
                        'lk': lkModel,
                        'filename': location['filename'],
                        'line': location['line']
                    }
                    LangLocationModel.objects.create(**locationValue)
            return response.json(0)
        else:
            return response.json(444)

    def do_delete(self, request_dict, response):
        word_key = request_dict.get('word_key', None)
        token = request_dict.get('token', None)
        word_key_type = request_dict.get('word_key_type', None)

        response = ResponseObject()

        token = TokenObject(token)
        if token.code != 0:
            return response.json(token.code)

        user_qs = UserModel.objects.filter(id=token.userID, username='admin')
        if not user_qs.exists():
            return response.json(403)

        print(word_key_type)
        if not word_key_type:
            return response.json(444, 'word_key_type')

        if word_key:
            try:
                word_key_type = int(word_key_type)
                print(word_key_type)
                lk_qs = LangKeyModel.objects.filter(word_key=word_key)
                if lk_qs.exists():
                    #     lk = lk_qs[0]
                    #     if lk.type == 2:
                    #         lk.type = 0
                    #         lk.save()
                    #     else:
                    #         lk_qs.delete()
                    #         LangValModel.objects.filter(lk__word_key=word_key).delete()
                    lk = lk_qs[0]
                    print(lk.type)
                    if lk.type < word_key_type:
                        return response.json(444, 'work_key_type')
                    else:
                        lk.type -= word_key_type
                        if lk.type > 0:
                            lk.save()
                        else:
                            lk_qs.delete()
                            LangValModel.objects.filter(lk__word_key=word_key).delete()
                LangLocationModel.objects.filter(lk__word_key=word_key).delete()
                LangKeyClassModel.objects.filter(lk__word_key=word_key).delete()
            except Exception as e:
                return response.json(404, repr(e))
            else:
                return response.json(0)
        else:
            return response.json(444)

    def do_translate(self, request_dict, response):
        print("进来了")
        lang = request_dict.get('lang', None)
        if not lang:
            return response.json(444)
        langkeymodel = LangKeyModel.objects.filter(langvalmodel__la__lang=lang, type__in=(2, 3, 6, 7)).values(
            'word_key',
            'langkeyclassmodel__clazz__name',
            'langvalmodel__word_val')
        result = {}
        for item in langkeymodel:
            classname = item['langkeyclassmodel__clazz__name']
            key = item['word_key']
            value = item['langvalmodel__word_val']
            if classname not in result:
                result[classname] = {key: value}
            else:
                result[classname][key] = value
        return response.json(0, result)
