#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
@Copyright (C) ansjer cop Video Technology Co.,Ltd.All rights reserved.
@AUTHOR: ASJRD018
@NAME: Ansjer
@software: PyCharm
@DATE: 2018/5/29 17:07
@Version: python3.6
@MODIFY DECORD:ansjer dev
@file: MealManage.py
@Contact: chanjunkai@163.com
"""
import traceback

from django.db.models import F
from django.utils import timezone
from django.utils.decorators import method_decorator
from django.views.decorators.csrf import csrf_exempt
from django.views.generic.base import View

from Model.models import Store_Meal, VodBucketModel, Pay_Type, Lang
from Object.ResponseObject import ResponseObject
from Object.TokenObject import TokenObject
from Service.CommonService import CommonService
from Service.ModelService import ModelService

'''
http://192.168.136.40:8077/meal/manage?operation=add&token=local&title=套餐A&price=$199&content=存7天&day=7&id=1
http://192.168.136.45:8077/meal/manage?operation=update&token=test&id=1&title=套餐A&price=$199&content=存3天&day=7
http://192.168.136.40:8077/meal/manage?operation=query&token=test&page=1&line=10
http://192.168.136.40:8077/meal/manage?operation=delete&token=test&id=1&id=2&id=3&id=4&id=5
'''


class MealManage(View):
    @method_decorator(csrf_exempt)
    def dispatch(self, *args, **kwargs):
        return super(MealManage, self).dispatch(*args, **kwargs)

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

    def post(self, request, *args, **kwargs):
        request.encoding = 'utf-8'
        return self.validation(request_dict=request.POST)

    def validation(self, request_dict, *args, **kwargs):
        response = ResponseObject()
        token = request_dict.get('token', None)
        operation = request_dict.get('operation', None)
        if token is None:
            return response.json(309)
        tko = TokenObject(token)
        response.lang = tko.lang
        if tko.code != 0:
            return response.json(tko.code)
        userID = tko.userID
        if userID is None:
            return response.json(309)
        if operation == 'query':
            return self.query(request_dict, response)
        elif operation == 'add':
            return self.add(request_dict, userID, response)
        elif operation == 'update':
            return self.update(request_dict, userID, response)
        elif operation == 'delete':
            return self.delete(request_dict, userID, response)
        elif operation == 'find':
            return self.find(request_dict, userID, response)
        elif operation == 'query_language':
            return self.query_language(request_dict, response)
        elif operation == 'add_language':
            return self.add_language(request_dict, response)
        elif operation == 'delete_language':
            return self.delete_language(request_dict, response)
        elif operation == 'edit_language':
            return self.edit_language(request_dict, response)
        else:
            return response.json(444, 'operation')

    def add(self, request_dict, userID, response):
        # title = request_dict.get('title', None)
        id = request_dict.get('id', None)
        price = request_dict.get('price', None)
        # content = request_dict.get('content', None)
        day = request_dict.get('day', None)
        commodity_code = request_dict.get('commodity_code', None)
        currency = request_dict.get('currency', None)
        bucketID = request_dict.get('bucketID', None)
        paytype = request_dict.get('paytype', None)
        virtual_price = request_dict.get('virtual_price', None)
        is_discounts = request_dict.get('is_discounts', None)
        discount_price = request_dict.get('discount_price', None)
        expire = request_dict.get('expire', None)
        symbol = request_dict.get('symbol', None)
        is_show = request_dict.get('is_show', None)

        # if not title or not id or not price or not day or not content:
        if not id or not price or not day:
            return response.json(444, 'title,id,price,content,day,bucketID')
        own_perm = ModelService.check_perm(userID=userID, permID=40)
        if own_perm is not True:
            return response.json(404)
        try:
            bucketQs = VodBucketModel.objects.filter(id=bucketID)
            if Store_Meal.objects.filter(id=id):
                return response.json(10, '已存在')
            store_meal = Store_Meal(id=id, price=price, day=day, bucket_id=bucketID, commodity_code=commodity_code,
                                    currency=currency, virtual_price=virtual_price, is_discounts=is_discounts,
                                    discount_price=discount_price, expire=expire, symbol=symbol, is_show=is_show)
            store_meal.save()
            paytype = paytype.split(',')
            if len(paytype) > 0:
                Store_Meal.objects.get(id=id).pay_type.set(paytype)
        except Exception:
            errorInfo = traceback.format_exc()
            print(errorInfo)
            return response.json(500, {'details': errorInfo})
        else:
            if store_meal.id:
                return response.json(0, {
                    'bucket__bucket': bucketQs[0].bucket,
                    'bucket__storeDay': bucketQs[0].storeDay,
                    'id': id,
                    'price': price,
                    'currency': currency,
                    'day': day,
                    'add_time': str(store_meal.add_time),
                    'update_time': str(store_meal.update_time)})

    def query(self, request_dict, response):
        page = int(request_dict.get('page', None))
        line = int(request_dict.get('line', None))
        lang = request_dict.get('lang', 'cn')
        if page is None or line is None:
            return response.json(444)

        qs = Store_Meal.objects.filter(lang__lang=lang)
        qs = qs.annotate(title=F('lang__title'), content=F('lang__content'))
        qs = qs.values("id", "title", "price", "day", "add_time", "update_time", "currency", "expire", "symbol"
                       , "commodity_type", "commodity_code", "virtual_price", "is_discounts", "discount_price"
                       , "bucket_id", "bucket__bucket", "bucket__area", "bucket__storeDay", "bucket__mold", "is_show")
        res = {}
        items_list = []
        if qs.exists():
            ql = list(qs)
            from operator import itemgetter
            from itertools import groupby
            ql.sort(key=itemgetter('bucket__area'))
            ql = CommonService.qs_to_list(ql[(page - 1) * line:page * line])
            # for area, items in groupby(ql, key=itemgetter('bucket__area')):
            items_list = list(ql)
            for key, val in enumerate(items_list):
                pay_types = Pay_Type.objects.filter(store_meal=items_list[key]['id']).values("id", "payment")
                items_list[key]['pay_type'] = list(pay_types)

        res['count'] =Store_Meal.objects.filter(lang__lang=lang).count()
        res['data'] = items_list
        return response.json(0, res)

    def update(self, request_dict, userID, response):
        id = request_dict.get('id', None)
        # title = request_dict.get('title', None)
        price = request_dict.get('price', None)
        day = request_dict.get('day', None)
        # content = request_dict.get('content', None)
        currency = request_dict.get('currency', None)
        bucketID = request_dict.get('bucketID', None)
        commodity_type = request_dict.get('commodity_type', None)
        commodity_code = request_dict.get('commodity_code', None)
        virtual_price = request_dict.get('virtual_price', None)
        is_discounts = request_dict.get('is_discounts', None)
        discount_price = request_dict.get('discount_price', None)
        expire = request_dict.get('expire', None)
        symbol = request_dict.get('symbol', None)
        type = request_dict.get('type', None)
        is_show = request_dict.get('is_show', None)
        # if not id or not title or not price or not content or not day or not type:
        if not id or not price or not day or not type:
            # return response.json(444, 'id, title, price, content, day,type')
            return response.json(444, 'id, price, day,type')
        own_perm = ModelService.check_perm(userID=userID, permID=30)
        if own_perm is not True:
            return response.json(404)
        try:
            store_meal = Store_Meal.objects.get(id=id)
            now_time = timezone.localtime(timezone.now())
            print(now_time)
            # store_meal.title = title
            store_meal.price = price
            # store_meal.content = content
            store_meal.commodity_type = commodity_type
            store_meal.commodity_code = commodity_code
            store_meal.virtual_price = virtual_price
            store_meal.is_discounts = is_discounts
            store_meal.discount_price = discount_price
            store_meal.expire = expire
            store_meal.symbol = symbol
            store_meal.is_show = is_show
            store_meal.day = day
            if bucketID:
                store_meal.bucket_id = bucketID
            if currency:
                store_meal.currency = currency
            store_meal.save()
            type = type.split(',')
            if len(type) > 0:
                Store_Meal.objects.get(id=id).pay_type.set(type)
            else:
                Store_Meal.objects.get(id=id).pay_type.clear()

        except Exception:
            errorInfo = traceback.format_exc()
            print(errorInfo)
            return response.json(424, {'details': errorInfo})
        else:
            return response.json(0, {'update_id': store_meal.id, 'update_time': str(now_time)})

    def delete(self, request_dict, userID, response):
        id_list = request_dict.getlist('id', None)
        if not id_list:
            return response.json(444, 'id')
        own_perm = ModelService.check_perm(userID=userID, permID=10)
        if own_perm is not True:
            return response.json(404)
        try:
            for id in id_list:
                Store_Meal.objects.filter(id=id).delete()
        except Exception as e:
            errorInfo = traceback.format_exc()
            print(errorInfo)
            return response.json(424, {'details': repr(e)})
        else:
            return response.json(0)

    def find(self, request_dict, userID, response):
        page = int(request_dict.get('page', None))
        line = int(request_dict.get('line', None))
        if not page or not line:
            return response.json(444, 'page,line')
        own_perm = ModelService.check_perm(userID=userID, permID=30)
        if own_perm is not True:
            return response.json(404)
        qs = Store_Meal.objects.all()
        if qs.exists():
            count = qs.count()
            res = qs[(page - 1) * line:page * line]
            send_json = CommonService.qs_to_dict(res)
            send_json['count'] = count
            return response.json(0, send_json)
        return response.json(0)

    def query_language(self, request_dict, response):
        # 查询套餐语言
        page = int(request_dict.get('page', None))
        line = int(request_dict.get('line', None))
        id = request_dict.get('id', None)
        if page is None or line is None:
            return response.json(444)

        if id:
            # 如果传入id,只查询id下的语言
            storeMeal_lang_qs = Store_Meal.objects.filter(id=id, lang__isnull=False).values('id', 'lang__id',
                                                                                            'lang__lang',
                                                                                            'lang__title',
                                                                                            'lang__content',
                                                                                            'lang__discount_content')
        else:
            storeMeal_lang_qs = Store_Meal.objects.filter(lang__isnull=False).values('id', 'lang__id', 'lang__lang',
                                                                                     'lang__title', 'lang__content',
                                                                                     'lang__discount_content')
        count = storeMeal_lang_qs.count()
        storeMeal_lang_qs = storeMeal_lang_qs[(page - 1) * line:page * line]
        res = {
            'datas': list(storeMeal_lang_qs),
            'count': count
        }
        return response.json(0, res)

    def add_language(self, request_dict, response):
        # 添加套餐语言
        store_meal_id = request_dict.get('store_meal_id', None)
        # lang_id = request_dict.get('lang_id', None)
        lang = request_dict.get('lang', None)
        title = request_dict.get('title', None)
        content = request_dict.get('content', None)
        discount_content = request_dict.get('discount_content', '')
        if not store_meal_id or not lang or not title or not content:
            return response.json(444, 'store_meal_id,lang,title,content')
        # 查询该套餐是否存在
        storeMeal_qs = Store_Meal.objects.get(id=store_meal_id)
        if not storeMeal_qs:
            return response.json(500)
        lang_obj = Lang.objects.filter(lang=lang, title=title, content=content, discount_content=discount_content)
        if not lang_obj.exists():
            # 数据不存在,lang表创建数据
            Lang.objects.create(lang=lang, title=title, content=content, discount_content=discount_content)
            lang_obj = Lang.objects.filter(lang=lang, title=title, content=content, discount_content=discount_content)
        storeMeal_qs.lang.add(*lang_obj)  # store_meal表添加语言数据
        return response.json(0)

    def edit_language(self, request_dict, response):
        # 编辑套餐语言
        store_meal_id = request_dict.get('store_meal_id', None)
        lang_id = request_dict.get('lang_id', None)
        lang = request_dict.get('lang', None)
        title = request_dict.get('title', None)
        content = request_dict.get('content', None)
        discount_content = request_dict.get('discount_content', '')
        if not store_meal_id or not lang_id or not lang or not title or not content:
            return response.json(444, 'store_meal_id,lang_id,lang,title,content')
        storeMeal_qs = Store_Meal.objects.get(id=store_meal_id)
        if not storeMeal_qs:
            return response.json(500)
        Lang.objects.filter(id=lang_id).update(lang=lang, title=title, content=content, discount_content=discount_content)
        return response.json(0)
        # # 删除原有数据
        # lang_qs = Lang.objects.filter(id=lang_id)
        # storeMeal_qs.lang.remove(*lang_qs)
        # lang_obj = Lang.objects.filter(lang=lang, title=title, content=content, discount_content=discount_content)
        # if not lang_obj.exists():
        #     # 数据不存在,lang表创建数据
        #     Lang.objects.create(lang=lang, title=title, content=content, discount_content=discount_content)
        #     lang_obj = Lang.objects.filter(lang=lang, title=title, content=content, discount_content=discount_content)
        # storeMeal_qs.lang.add(*lang_obj)  # store_meal表添加语言数据
        # return response.json(0)

    def delete_language(self, request_dict, response):
        # 删除套餐语言
        store_meal_id = request_dict.get('store_meal_id', None)
        lang_id = request_dict.get('lang_id', None)

        storeMeal_qs = Store_Meal.objects.get(id=store_meal_id)
        if not storeMeal_qs:
            return response.json(500)
        lang_qs = Lang.objects.filter(id=lang_id)
        storeMeal_qs.lang.remove(*lang_qs)
        return response.json(0)


'''
用户获取全部套餐信息
http://192.168.136.40:8077/meal/list?token=local
'''


class MealView(View):
    @method_decorator(csrf_exempt)
    def dispatch(self, *args, **kwargs):
        return super(MealView, self).dispatch(*args, **kwargs)

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

    def post(self, request, *args, **kwargs):
        request.encoding = 'utf-8'
        operation = kwargs.get('operation')
        return self.validation(request.POST, request, operation)

    def validation(self, request_dict, request, operation):
        response = ResponseObject()
        if operation is None:
            return response.json(444, 'error path')
        token = request_dict.get('token', None)
        # 设备主键uid
        tko = TokenObject(token)
        response.lang = tko.lang
        if tko.code != 0:
            return response.json(tko.code)
        elif operation == 'query':
            return self.do_query(request_dict, response)
        else:
            return response.json(414)

    def do_query(self, request_dict, response):
        mold = request_dict.get('request_dict', None)
        if mold:
            qs = Store_Meal.objects.filter(bucket__mold=1). \
                values("id", "title", "content", "price", "day", "currency",
                       "bucket__storeDay", "bucket__bucket", "bucket__area",
                       "type", "symbol")
        else:
            qs = Store_Meal.objects.all(). \
                values("id", "title", "content", "price", "day", "currency",
                       "bucket__storeDay", "bucket__bucket", "bucket__area",
                       "type", "symbol")
        if qs.exists():
            ql = list(qs)
            from operator import itemgetter
            from itertools import groupby
            ql.sort(key=itemgetter('bucket__area'))
            res = []
            for area, items in groupby(ql, key=itemgetter('bucket__area')):
                res_c = {'area': area, 'items': list(items)}
                res.append(res_c)
            result = {
                'meals': res,
                'extra':
                    {
                        'cloud_banner': 'https://www.dvema.com/web/images/cloud_cn_banner.png',
                        'cloud_en_baner': 'https://www.dvema.com/web/images/cloud_en_banner.png'
                    }
            }
            return response.json(0, result)
        else:
            return response.json(0)
