#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
@Copyright (C) ansjer cop Video Technology Co.,Ltd.All rights reserved.
@AUTHOR: ASJRD019
@NAME: langer
@software: PyCharm
@DATE: 2019/11/14 11:44
@Version: python3.6
@MODIFY DECORD:ansjer dev
@file: LangArea.py
@Contact: pzb3076@163.com
"""

import json
from django.views.generic import TemplateView
from object.ResponseObject import ResponseObject
from model.models import UserModel,skuSuitModel,skuRuleModel,skuConditionModel
import time
from object.TokenObject import TokenObject


class skuRuleView(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)
            if not user_qs.exists():
                return response.json(403)
            if user_qs[0].role_id == "admin":
                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 == 'query_all':
                    return self.do_query_all(request_dict, response, userID)
                else:
                    return response.json(414)
            else:
                if operation == 'query':
                    return self.do_query(request_dict, response, userID)
                elif operation == 'query_all':
                    return self.do_query_all(request_dict, response, userID)
                else:
                    return response.json(414)
        else:
            return response.json(tko.code)

    def do_add(self, request_dict, response):
        name = request_dict.get('name', None)
        rs_id = request_dict.get('id', None)
        if name:
            nowTime = int(time.time())
            create_dict = {
                'rs_id': rs_id,
                'ruleName': name,
                'addTime': nowTime,
                'updTime': nowTime
            }
            try:
                skuRuleModel.objects.create(**create_dict)
            except Exception as e:
                return response.json(404, repr(e))
            else:
                sr_qs = skuRuleModel.objects.filter(ruleName=name).values('ruleName', 'id')
                return response.json(0, list(sr_qs))
        else:
            return response.json(414)

    def do_update(self, request_dict, response):
        name = request_dict.get('name', None)
        id = request_dict.get('id', None)
        nowTime = int(time.time())
        update_dict = {
            'ruleName': name,
            'updTime': nowTime
        }
        try:
            skuRuleModel.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:
            skuConditionModel.objects.filter(cr__id=id).delete()
            skuRuleModel.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)
        if not user_qs.exists():
            return response.json(403)
        la_qs = skuRuleModel.objects.filter().values('ruleName', 'id')
        return response.json(0, list(la_qs))

    def do_query_all(self, request_dict, response, userID):
        user_qs = UserModel.objects.filter(id=userID)
        id = request_dict.get('id', None)
        if not user_qs.exists():
            return response.json(403)
        sr_qs = skuRuleModel.objects.filter(rs__id=id).values('ruleName', 'id').order_by("id")
        for SR in sr_qs:
            try:
                cr_qs = skuConditionModel.objects.filter(cr_id=SR['id']).values('numName', 'conditionName',
                                                                                'id').order_by("id")
                SR['cr_qs'] = list(cr_qs)
            except Exception:
                pass
        return response.json(0, list(sr_qs))