#!/usr/bin/env python3  
# -*- coding: utf-8 -*-  
"""
@Copyright (C) ansjer cop Video Technology Co.,Ltd.All rights reserved.
@AUTHOR: ASJRD018
@NAME: langer
@software: PyCharm
@DATE: 2019/6/4 11:44
@Version: python3.6
@MODIFY DECORD:ansjer dev
@file: LangArea.py
@Contact: chanjunkai@163.com
"""
from var_dump import var_dump
import json
from django.http import HttpResponse

from django.views.generic import TemplateView
from django.views.decorators.csrf import csrf_exempt
from django.utils.decorators import method_decorator
from object.ResponseObject import ResponseObject
from django.contrib.auth.hashers import make_password, check_password
from model.models import UserModel, LangSetModel, LangAreaModel, LangKeyModel, LangValModel
import time
from object.TokenObject import TokenObject


class LangWordView(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()
        token = request_dict.get('token', None)
        tko = TokenObject(token)
        if tko.code == 0:
            userID = tko.userID
            if operation == 'add':
                user_qs = UserModel.objects.filter(id=userID, username='admin')
                if not user_qs.exists():
                    return response.json(403)
                return self.do_add(request_dict, response)
            elif operation == 'update':
                return self.do_update(request_dict, response, userID)
            elif operation == 'delete':
                user_qs = UserModel.objects.filter(id=userID, username='admin')
                if not user_qs.exists():
                    return response.json(403)
                return self.do_delete(request_dict, userID, response)
            # search index table
            elif operation == 'query':
                return self.do_query(request_dict, response, userID)
            else:
                return response.json(414)
        else:
            return response.json(tko.code)

    def do_add(self, request_dict, response):
        word_key = request_dict.get('word_key', None)
        word_arr = request_dict.get('word_arr', None)
        nowTime = int(time.time())
        lang_key_dict = {
            'word_key': word_key,
            'addTime': nowTime,
            'updTime': nowTime
        }
        try:
            # var_dump(lang_key_dict)
            lk = LangKeyModel.objects.filter(word_key=word_key)
            if lk.exists():
                var_dump(list(lk))

                return response.json(473,'key已存在')
            lk = LangKeyModel.objects.create(**lang_key_dict)
            for w in word_arr:
                LangValModel.objects.create(la_id=w['la_id'], lk_id=lk.id, addTime=nowTime, updTime=nowTime,
                                            word_val=w['val'])

        except Exception as e:
            print(repr(e))
            return response.json(404, repr(e))
        else:
            return response.json(0)

    '''
    post_data = {
        word_key_id:1,
        word_key:xxx,
        word_arr:[
            {'lang':'','val':''},
            {'lang':'','val':''},
            {'lang':'','val':''}
        ]
    }
    '''

    def do_update(self, request_dict, response, userID):
        old_word_key = request_dict.get('old_word_key', None)
        word_key = request_dict.get('word_key', None)
        word_arr = request_dict.get('word_arr', None)
        # from var_dump import var_dump
        # var_dump(request_dict)
        lk = LangKeyModel.objects.filter(word_key=old_word_key)
        nowTime = int(time.time())
        if lk.exists():
            lk_id = lk[0].id
            if old_word_key != word_key:
                user_qs = UserModel.objects.filter(id=userID, username='admin')
                if user_qs.exists():
                    lk.update(word_key=word_key, updTime=nowTime)
            else:
                lk.update(updTime=nowTime)
            for w in word_arr:
                lv_qs = LangValModel.objects.filter(lk__id=lk_id, la__lang=w)
                if lv_qs.exists():
                    lv_qs.update(updTime=nowTime, word_val=word_arr[w])
                else:
                    la_qs = LangAreaModel.objects.filter(lang=w)
                    if la_qs.exists():
                        la_id = la_qs[0].id
                        LangValModel.objects.create(la_id=la_id, lk_id=lk_id, addTime=nowTime, updTime=nowTime,
                                                    word_val=word_arr[w])
            return response.json(0)
        else:
            return response.json(404)

    def do_delete(self, request_dict, userID, response):
        user_qs = UserModel.objects.filter(id=userID, username='admin')
        if not user_qs.exists():
            return response.json(403)
        word_key = request_dict.get('word_key', None)
        try:
            LangKeyModel.objects.filter(word_key=word_key).delete()
            LangValModel.objects.filter(lk__word_key=word_key).delete()
        except Exception as e:
            return response.json(404, repr(e))
        else:
            return response.json(0)

    def do_query(self, request_dict, response, userID):
        page = int(request_dict.get('page', None))
        line = int(request_dict.get('line', None))
        searchKey = request_dict.get('searchKey', None)
        searchVal = request_dict.get('searchVal', None)
        if searchKey:
            searchKey = searchKey.strip()
        if searchVal:
            searchKey = searchKey.strip()
        orderByupdate = request_dict.get('orderByupdate', 0)
        if page and line:
            lang_set_list = LangSetModel.objects.filter(user__id=userID).values_list('lang__id', flat=True)
            lang_set_list = list(lang_set_list)
            la_qs = LangAreaModel.objects.filter(id__in=lang_set_list).values('lang', 'id')
            lk_qs = LangKeyModel.objects.filter()
            if searchKey and searchVal:
                if searchKey == 'key':
                    lk_qs = lk_qs.filter(word_key__contains=searchVal)
                    # lk_qs = lk_qs.filter(word_key=searchVal)
                else:
                    lk_qs = lk_qs.filter(langvalmodel__word_val__contains=searchVal, langvalmodel__la__lang=searchKey)
            count = lk_qs.count()
            # lk_qs = lk_qs[(page - 1) * line:page * line].values_list('word_key', flat=True)
            # if orderByupdate == 1:
            #     lk_qs = lk_qs.order_by('updTime')
            # else:
            #     lk_qs = lk_qs.order_by('-updTime')
            lk_qs = lk_qs[(page - 1) * line:page * line].values('word_key', 'updTime')
            k_list = []
            lw_dict = {}
            for lk in lk_qs:
                k_list.append(lk['word_key'])
                lw_dict[lk['word_key']] = {'updTime': lk['updTime']}
            lv_qs = LangValModel.objects.filter(lk__word_key__in=k_list, la__id__in=lang_set_list). \
                values('word_val', 'la__id', 'la__lang', 'lk__word_key', 'lk__id')
            for lv in lv_qs:
                lw_dict[lv['lk__word_key']][lv['la__lang']] = lv['word_val']
            res = {
                'la_list': list(la_qs),
                'lw_dict': lw_dict,
                # 'lk_list': list(lk_qs),
                # 'lv_list': list(lv_qs)
                'count': count
            }
            return response.json(0, res)
        else:
            return response.json(444, 'page,line')
