#!/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
"""

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, LangValModel, LangKeyModel
import time
from object.TokenObject import TokenObject
from django.http import StreamingHttpResponse


class LangAreaView(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
            user_qs = UserModel.objects.filter(id=userID, username='admin')
            if not user_qs.exists():
                return response.json(403)
            if operation == 'add':
                return self.do_add(request_dict, response)
            elif operation == 'update':
                return self.do_update(request_dict, response)
            elif operation == 'delete':
                return self.do_delete(request_dict, response)
            elif operation == 'query':
                return self.do_query(request_dict, response, userID)
            elif operation == 'export':
                return self.do_export(request_dict, response, userID)
            else:
                return response.json(414)
        else:
            return response.json(tko.code)

    def do_add(self, request_dict, response):
        lang = request_dict.get('lang', None)
        if lang:
            nowTime = int(time.time())
            create_dict = {
                'lang': lang,
                'addTime': nowTime,
                'updTime': nowTime
            }
            try:
                LangAreaModel.objects.create(**create_dict)
            except Exception as e:
                return response.json(404, repr(e))
            else:
                return response.json(0)
        else:
            return response.json(414)

    def do_update(self, request_dict, response):
        lang = request_dict.get('lang', None)
        id = request_dict.get('id', None)
        nowTime = int(time.time())
        update_dict = {
            'lang': lang,
            'updTime': nowTime
        }
        try:
            LangAreaModel.objects.filter(id=id).update(**update_dict)
        except Exception as e:
            return response.json(404, repr(e))
        else:
            return response.json(0)

    def do_delete(self, request_dict, response):
        id = request_dict.get('id', None)
        try:
            LangAreaModel.objects.filter(id=id).delete()
        except Exception as e:
            return response.json(404, repr(e))
        else:
            return response.json(0)

    def do_query(self, request_dict, response, userID):
        user_qs = UserModel.objects.filter(id=userID, username='admin')
        if not user_qs.exists():
            return response.json(403)
        la_qs = LangAreaModel.objects.filter().values('lang', 'id')
        return response.json(0, list(la_qs))

    def do_export(self, request_dict, response, userID):
        print("进来了")
        id = request_dict.get('id', None)
        type = request_dict.get('type', None)
        # key_list = LangKeyModel.objects.filter().values_list('word_key', flat=True)
        en_qs = LangKeyModel.objects.filter(langvalmodel__la__id=20).values('word_key', 'langvalmodel__word_val')
        en_kv = {}
        for e in en_qs:
            en_kv[e['word_key']] = e['langvalmodel__word_val']

        content = ''
        if type == 'ios':
            res_qs = LangKeyModel.objects.filter(langvalmodel__la__id=id).\
                values('word_key', 'langvalmodel__word_val')
            res = {}
            for r in res_qs:
                print(r['langvalmodel__word_val'])
                if r['langvalmodel__word_val']:
                    res[r['word_key']] = r['langvalmodel__word_val']
                elif en_kv[r['word_key']]:
                    res[r['word_key']] = en_kv[r['word_key']]
            for l in res:
                content_val = res[l].replace('"', '\'')
                content = content + '"' + l + '"="' + content_val + '";\n'
        elif type == 'android':
            res_qs = LangKeyModel.objects.filter(langvalmodel__la__id=id).\
                values('word_key', 'langvalmodel__word_val').order_by('addTime')
            res = {}
            for r in res_qs:
                print(r['langvalmodel__word_val'])
                if r['langvalmodel__word_val']:
                    res[r['word_key']] = r['langvalmodel__word_val']
                elif en_kv[r['word_key']]:
                    res[r['word_key']] = en_kv[r['word_key']]
            for l in res:
                lk = l
                lk = lk.replace('.', '_')
                lk = lk.replace('\\n', '_')
                lk = lk.replace('“', '_')
                lk = lk.replace('”', '_')
                lk = lk.replace(' ', '_')
                lk = lk.replace('\\\'', '_')
                lk = lk.replace('\'', '_')
                lk = lk.replace('\\', '_')
                lk = lk.replace('!', '_')
                lk = lk.replace('’', '_')
                lk = lk.replace('...', '_')
                lk = lk.replace('…', '_')
                lk = lk.replace(':', '_')
                lk = lk.replace('：', '_')
                lk = lk.replace('(', '_')
                lk = lk.replace(')', '_')
                lk = lk.replace('?', '_')
                lk = lk.replace(',', '_')
                lk = lk.replace('-', '_')
                lk = lk.replace('%', '_')
                lk = lk.replace(';', '_')
                lk = lk.replace('‘', '_')
                # 正则表达式
                # re.sub("[a-z]+", "$", "123abc78ab9cdeg00t8")
                content_val = res[l].replace("'","\\'")
                content = content + '<string name="' + lk + '">' + content_val + '</string>\n'
        response = StreamingHttpResponse(content)
        response['Content-Type'] = 'application/octet-stream'
        response['Content-Disposition'] = 'attachment;filename="lang.txt"'
        return response
        return response.json(0, res)


from django.http import StreamingHttpResponse


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

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

    def validate(self, request_dict):
        # 得到即将下载文件的路径和名称
        response = StreamingHttpResponse('123l4kjlkfjlksadjlfksdajlf')
        response['Content-Type'] = 'application/octet-stream'
        response['Content-Disposition'] = 'attachment;filename="lang.txt"'
        return response
