#!/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
import xlrd
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, LangPermModel
import time
from object.TokenObject import TokenObject
from django.db.models import Q


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'))
        # request_dict = request.POST
        return self.validate(request, 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, request_dict, operation)

    def validate(self, request, request_dict, operation):
        response = ResponseObject()
        print('request_dict:', request_dict)
        print('operation:', operation)
        token = request_dict.get('token', None)
        tko = TokenObject(token)
        # print('tko:',tko.userID)
        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)
            elif operation == 'reset':
                return self.do_reset(request_dict, response, userID)
            elif operation == 'add_new_lang':
                return self.do_add_new_lang(request, 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)
        word_key_type = request_dict.get('word_key_type', None)
        if not word_key_type:
            return response.json(444, 'word_key_type')
        nowTime = int(time.time())
        lang_key_dict = {
            'word_key': word_key,
            'addTime': nowTime,
            'updTime': nowTime,
            'type': word_key_type
        }
        try:
            # var_dump(lang_key_dict)
            lk = LangKeyModel.objects.filter(word_key=word_key)
            if lk.exists():
                print(lk[0].type)
                print(word_key_type)
                type = lk[0].type & word_key_type
                print(type)
                if lk[0].type & word_key_type != 0:
                    var_dump(list(lk))
                    return response.json(473, 'key已存在')
                else:
                    type = word_key_type | lk[0].type
                    data = {
                        'type': type,
                        'updTime': nowTime
                    }
                    lk.update(**data)
                    return response.json(0)
            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'], status=1)

        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)
        status = request_dict.get('status', 0)
        # from var_dump import var_dump
        # var_dump(request_dict)
        if not word_key:
            return response.json(444)
        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)
            # 如果是管理员，是status的值为1，表示记录为新增
            user = UserModel.objects.get(id=userID)
            lang_perm_ql = LangPermModel.objects.filter(user__id=userID).values_list('lang__lang', flat=True)
            lang_perm_ls = list(lang_perm_ql)
            print(lang_perm_ls)

            if user.role_type == 1:
                status = 1
            for w in word_arr:
                lv_qs = LangValModel.objects.filter(lk__word_key=word_key, lk__project__isnull=True, la__lang=w)
                if lv_qs.exists() and w in lang_perm_ql:
                    lv_qs.update(updTime=nowTime, word_val=word_arr[w], status=status)
                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], status=status)
            return response.json(0)
        else:
            return response.json(404)

    def do_delete(self, request_dict, userID, response):
        print('delete')
        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)
        word_key_type = request_dict.get('work_key_type', None)
        print(word_key_type)
        if not word_key_type:
            return response.json(444, 'work_key_type')
        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]
                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()
        except Exception as e:
            return response.json(404, repr(e))
        else:
            return response.json(0)

    def do_query(self, request_dict, response, userID):
        print(request_dict)
        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)
        langType = request_dict.get('langType', 0)
        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)
            print('lang_set_list:', lang_set_list)
            lang_set_list = list(lang_set_list)
            print('lang_set_list:', lang_set_list)
            la_qs = LangAreaModel.objects.filter(id__in=lang_set_list).values('lang', 'id')

            print(langType)
            tmpType = int(langType)
            print(tmpType)
            if tmpType == 0:
                lk_qs = LangKeyModel.objects.filter(type__in=(1, 3, 5, 7))
                print('lk_qs:', lk_qs)
            elif tmpType == 1:
                lk_qs = LangKeyModel.objects.filter(type__in=(2, 3, 6, 7))
            elif tmpType == 2:
                lk_qs = LangKeyModel.objects.filter(type__in=(4, 5, 6, 7))

            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:
                    if searchVal == ' ':
                        lk_qs = lk_qs.filter(langvalmodel__word_val='', langvalmodel__la__lang=searchKey)
                    else:
                        lk_qs = lk_qs.filter(langvalmodel__word_val__contains=searchVal, langvalmodel__la__lang=searchKey)
            if orderByupdate == 1:
                lk_qs = lk_qs.order_by('updTime')
            else:
                lk_qs = lk_qs.order_by('-updTime')
            lk_qs = lk_qs.values('word_key', 'updTime').distinct()  # 去除重复word_key
            count = len(lk_qs)
            lk_qs = lk_qs[(page - 1) * line: page * line]
            k_list = []
            lw_dict = {}
            for lk in lk_qs:
                k_list.append(lk['word_key'])
                lw_dict[lk['word_key']] = {'updTime': lk['updTime']}
            print('k_list:', k_list)
            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', 'status')
            print('lv_qs:', lv_qs)
            user = UserModel.objects.get(id=userID)
            lang_perm_ql = LangPermModel.objects.filter(user__id=userID).values_list('lang__lang', flat=True)
            lang_perm_ls = list(lang_perm_ql)
            print('lang_perm_ql:', lang_perm_ql)
            print('lw_dict:', lw_dict)
            for lv in lv_qs:
                lang = lv['la__lang']
                # print('lang=%s' % lang)
                lw_dict[lv['lk__word_key']][lang] = lv['word_val']
                # print('lw_dict_word_val:', lw_dict)
                if user.role_type == 1:
                    lw_dict[lv['lk__word_key']]['status'] = 0
                elif lang in lang_perm_ls:
                    lw_dict[lv['lk__word_key']]['status'] = lv['status']
                # print('lw_dict_status:', lw_dict)
            res = {
                'la_list': list(la_qs),
                'lw_dict': lw_dict,
                # 'lk_list': list(lk_qs),
                # 'lv_list': list(lv_qs)
                'count': count
            }
            print('res:', res)
            return response.json(0, res)
        else:
            return response.json(444, 'page,line')

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

        word_key = request_dict.get('word_key', None)
        if word_key:
            word_key_list = word_key.split(',')

            # 获取该用户可以修改的语种
            lp_qs = LangPermModel.objects.filter(user_id=userID).values_list('lang__id')
            lq_list = list(lp_qs)
            print('lq_list:', lq_list)
            # ls_qs = LangSetModel.objects.filter(user_id=userID, lang_id__in=lq_list).values_list('lang__id')
            # ls_list = list(ls_qs)
            lk = LangKeyModel.objects.filter(word_key__in=word_key_list).values_list('id')
            lv_qs = LangValModel.objects.filter(Q(lk_id__in=lk) & ~Q(status=0) & Q(la_id__in=lq_list))
            # print(lv_qs.values())
            if lv_qs.exists():
                lv_qs.update(status=0)
                return response.json(0)
            else:
                return response.json(10, "数据已重置")
        else:
            return response.json(404)

    def do_add_new_lang(self, request, request_dict, response, userID):

        file = request.FILES.get('file', None)
        try:
            data = file.read()
            workbook = xlrd.open_workbook(file_contents=data)
            worksheet = workbook.sheet_by_index(0)
            ar_list = worksheet.col_values(1, 1)
            en_list = worksheet.col_values(0, 1)
            lang_key_qs = LangKeyModel.objects.filter(type__in=(1, 3, 5, 7)).values('id', 'word_key')
            now_time = int(time.time())
            ar_result = []
            err_key = []
            for item in lang_key_qs:
                try:
                    ar = ar_list[en_list.index(item['word_key'])]
                    ar_result.append(ar)
                except ValueError:
                    err_key.append(item['word_key'])
                    continue
                lang_val = LangValModel.objects.filter(la__id=36, lk__id=item['id'])
                if lang_val.exists():
                    lang_val.update(word_val=ar, updTime=now_time)
                else:
                    LangValModel.objects.create(lk_id=item['id'], la_id=36, word_val=ar, addTime=now_time, updTime=now_time)
            print(ar_result)
            print(err_key)
            return response.json(0)
        except Exception as e:
            return response.json(404)
