#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import time

from django.db.models import F, Q, Sum
from django.views.generic.base import View

from Model.models import Lang, ICloudStoreMeal, AiService, Order_Model, Device_User, CountryModel, UidSetModel, \
    Device_Info, VodBucketModel, IcloudUseDetails, IcloudService, IcloudStorageRecord
from Object.AWS.AmazonS3Util import AmazonS3Util
from Object.ResponseObject import ResponseObject
from Object.TokenObject import TokenObject
from Service.CommonService import CommonService
from Ansjer.config import ACCESS_KEY_ID, SECRET_ACCESS_KEY, REGION_NAME, SERVER_DOMAIN, AWS_ACCESS_KEY_ID, \
    AWS_SECRET_ACCESS_KEY, SERVER_DOMAIN_SSL, OAUTH_ACCESS_TOKEN_SECRET


class IcloudServeView(View):
    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):
        language = request_dict.get('language', 'en')
        response = ResponseObject(language, 'pc')
        if operation == 'xxx':  # 不认证token接口
            pass
        else:
            tko = TokenObject(
                request.META.get('HTTP_AUTHORIZATION'),
                returntpye='pc')
            if tko.code != 0:
                return response.json(tko.code)
            response.lang = tko.lang
            user_id = tko.userID
            # icloud套餐信息相关
            if operation == 'getIcloudStoreMealList':
                return self.get_icloud_store_meal_list(request_dict, response)
            elif operation == 'addOrEditIcloudStoreMeal':
                return self.add_or_edit_icloud_store_meal(request_dict, response)
            elif operation == 'getBucket':
                return self.get_bucket(request_dict, response)
            elif operation == 'deleteMeal':
                return self.delete_meal(request_dict, response)
            # icloud套餐语言相关
            elif operation == 'getMealLang':
                return self.get_meal_lang(request_dict, response)
            elif operation == 'addOrEditLang':
                return self.add_or_edit_lang(request_dict, response)
            elif operation == 'deleteLang':
                return self.delete_lang(request_dict, response)
            # 用户云盘信息
            elif operation == 'getUserIcloudInfo':
                return self.get_user_icloud_info(request_dict, response)
            elif operation == 'resetIcloud':
                return self.reset_icloud(request_dict, response)
            # 云盘订单信息
            elif operation == 'getIcloudOrder':
                return self.get_icloud_order(request_dict, response)
            else:
                return response.json(404)

    @staticmethod
    def get_icloud_store_meal_list(request_dict, response):
        is_select = request_dict.get('isSelect', None)
        page = request_dict.get('pageNo', None)
        line = request_dict.get('pageSize', None)
        if is_select:
            # 获取套餐ID作为选项
            icloud_meal_qs = ICloudStoreMeal.objects.filter().values('id')
            return response.json(0, {'list': CommonService.qs_to_list(icloud_meal_qs)})
        if not all([page, line]):
            return response.json(444)
        page = int(page)
        line = int(line)
        try:
            icloud_meal_qs = ICloudStoreMeal.objects.values()
            total = icloud_meal_qs.count()
            icloud_meals = icloud_meal_qs[(page - 1) * line:page * line]
            icloud_meal_list = []
            for icloud_meal in icloud_meals:
                # 获取支付方式列表
                pay_type_list = list(
                    ICloudStoreMeal.objects.filter(id=icloud_meal['id']).values('pay_type__id', 'pay_type__payment'))
                # 获取存储桶信息
                vod_bucket_qs = VodBucketModel.objects.filter(id=icloud_meal['bucket_id']).values('bucket')
                if not vod_bucket_qs.exists():
                    return response.json(173)
                # 组织响应数据
                icloud_meal_list.append({
                    'IcloudMealID': icloud_meal['id'],
                    'price': icloud_meal['price'],
                    'symbol': icloud_meal['symbol'],
                    'currency': icloud_meal['currency'],
                    'is_show': icloud_meal['is_show'],
                    'is_delete': icloud_meal['is_delete'],
                    'expire': icloud_meal['expire'],
                    'pay_type': pay_type_list,
                    'size': icloud_meal['size'],
                    'bucket': vod_bucket_qs[0]['bucket'],
                    'addTime': icloud_meal['add_time'].strftime("%Y-%m-%d %H:%M:%S"),
                    'updTime': icloud_meal['update_time'].strftime("%Y-%m-%d %H:%M:%S"),
                })
            return response.json(0, {'list': icloud_meal_list, 'total': total})
        except Exception as e:
            return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))

    @staticmethod
    def add_or_edit_icloud_store_meal(request_dict, response):
        # 添加/编辑套餐
        meal_id = request_dict.get('IcloudMealID', None)
        expire = int(request_dict.get('expire', None))
        price = request_dict.get('price', None)
        currency = request_dict.get('currency', None)
        symbol = request_dict.get('symbol', None)
        pay_type = request_dict.get('pay_type', None)
        is_show = int(request_dict.get('is_show', 1))
        is_delete = int(request_dict.get('is_delete', 0))
        size = float(request_dict.get('size', None))
        is_edit = request_dict.get('isEdit', None)
        bucket_id = request_dict.get('bucket_id', None)

        if not all([expire, price, currency, symbol, pay_type, size, bucket_id]):
            return response.json(444)
        pay_type = pay_type.split(',')
        try:
            icloud_store_meal_data = {
                'expire': expire,
                'price': price,
                'currency': currency,
                'symbol': symbol,
                'is_show': is_show,
                'size': size,
                'is_delete': is_delete,
                'bucket_id': bucket_id
            }
            if is_edit:
                if not meal_id:
                    return response.json(444)
                ICloudStoreMeal.objects.filter(id=meal_id).update(**icloud_store_meal_data)
                ICloudStoreMeal.objects.get(id=meal_id).pay_type.set(pay_type)
            else:
                icloud_meal_qs = ICloudStoreMeal.objects.create(**icloud_store_meal_data)
                icloud_meal_qs.pay_type.set(pay_type)
            return response.json(0)
        except Exception as e:
            print(e)
            return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))

    @staticmethod
    def get_bucket(request_dict, response):
        try:
            bucket_qs = VodBucketModel.objects.all().values('id', 'bucket')
            return response.json(0, list(bucket_qs))
        except Exception as e:
            print(e)
            return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))

    @staticmethod
    def delete_meal(request_dict, response):
        meal_id = request_dict.get('meal_id', None)
        status = request_dict.get('status', None)
        if not meal_id:
            return response.json(444)
        ICloudStoreMeal.objects.filter(id=meal_id).update(is_delete=status)
        return response.json(0)

    @staticmethod
    def get_meal_lang(request_dict, response):
        is_select = request_dict.get('isSelect', None)
        meal_id = request_dict.get('mealId', None)
        page = request_dict.get('pageNo', None)
        line = request_dict.get('pageSize', None)
        if not all([page, line]):
            return response.json(444)
        lang = Lang.objects.filter(type=3)
        page = int(page)
        line = int(line)
        total = lang.count()
        if is_select:
            lang = ICloudStoreMeal.objects.values('id', 'lang__title')
        else:
            if meal_id:
                lang = lang.filter(icloudstoremeal__id=meal_id).values('icloudstoremeal__id', 'id', 'lang', 'title',
                                                                       'content')
                total = lang.count()
            else:
                lang = lang.values('icloudstoremeal__id', 'id', 'lang', 'title', 'content')[
                       (page - 1) * line:page * line]
        return response.json(0, {'langList': list(lang), 'total': total})

    @staticmethod
    def add_or_edit_lang(request_dict, response):
        lang_id = request_dict.get('lang_id', None)
        meal_id = request_dict.get('meal_id', None)
        lang = request_dict.get('lang', 'en')
        title = request_dict.get('title', None)
        content = request_dict.get('content', None)
        try:
            icloud_meal_qs = ICloudStoreMeal.objects.get(id=meal_id)
            if not icloud_meal_qs:
                return response.json(173)
            if lang_id:
                Lang.objects.filter(id=lang_id).update(lang=lang, title=title, content=content)
            else:
                lang_qs = Lang.objects.filter(lang=lang, title=title, content=content, type=3)
                if not lang_qs.exists():
                    Lang.objects.create(lang=lang, title=title, content=content, type=3)
                    lang_qs = Lang.objects.filter(lang=lang, title=title, content=content, type=3)
                icloud_meal_qs.lang.add(*lang_qs)
            return response.json(0)
        except Exception as e:
            return response.json(500)

    @staticmethod
    def delete_lang(request_dict, response):
        lang_id = request_dict.get('lang_id', None)
        meal_id = request_dict.get('meal_id', None)
        if not all([lang_id, meal_id]):
            return response.json(444)
        try:
            lang = Lang.objects.filter(id=lang_id)
            icloud_meal_qs = ICloudStoreMeal.objects.get(id=meal_id)
            icloud_meal_qs.lang.remove(*lang)
            lang.delete()
            return response.json(0)
        except Exception as e:
            return response.json(500)

    @staticmethod
    def get_user_icloud_info(request_dict, response):
        user_id = request_dict.get('user_id', None)
        page = request_dict.get('pageNo', None)
        line = request_dict.get('pageSize', None)
        if not all([page, line]):
            return response.json(444)
        now_time = int(time.time())
        page = int(page)
        line = int(line)
        try:
            icloud_user_qs = IcloudUseDetails.objects.all()
            if user_id:
                icloud_user_qs = icloud_user_qs.filter(user_id=user_id)
            icloud_user_qs = icloud_user_qs.values('use_size', 'user_id', 'detect_status', 'bucket_id',
                                                   'id')
            total = icloud_user_qs.count()
            icloud_user_qs = icloud_user_qs[(page - 1) * line:page * line]
            for item in icloud_user_qs:
                use_details_id = item['id']
                user_id = item['user_id']
                bucket_id = item['bucket_id']
                user_qs = Device_User.objects.filter(userID=user_id).values('username')
                item['username'] = user_qs[0]['username']
                bucket_qs = VodBucketModel.objects.filter(id=bucket_id).values('bucket')
                item['bucket_name'] = bucket_qs[0]['bucket']
                all_size = IcloudService.objects.filter(Q(use_details_id=use_details_id), Q(use_status=0),
                                                        Q(end_time__gt=now_time) | Q(end_time=0)).values(
                    'size').aggregate(total_size=Sum('size'))['total_size']
                item['all_size'] = float(all_size * 1024) if all_size else 0  # 转换单位为MB

            return response.json(0, {'list': list(icloud_user_qs), 'total': total})
        except Exception as e:
            return response.json(500)

    @staticmethod
    def reset_icloud(request_dict, response):
        use_details_id = request_dict.get('id', None)
        if not all([use_details_id]):
            return response.json(444)
        try:
            icloud_use_qs = IcloudUseDetails.objects.filter(id=use_details_id).values('user_id', 'bucket_id')
            user_id = icloud_use_qs[0]['user_id']
            bucket_id = icloud_use_qs[0]['bucket_id']
            bucket_qs = VodBucketModel.objects.filter(id=bucket_id).values('bucket', 'region', 'mold')
            if not bucket_qs.exists():
                return response.json(173)
            bucket_name = bucket_qs[0]['bucket']
            bucket_region = bucket_qs[0]['region']
            mold = bucket_qs[0]['mold']
            s3_obj = AmazonS3Util(
                AWS_ACCESS_KEY_ID[mold],
                AWS_SECRET_ACCESS_KEY[mold],
                bucket_region
            )
            object_list = s3_obj.get_object_list(bucket_name, user_id)
            for obj in object_list:
                s3_obj.delete_obj(bucket_name, obj['Key'])
            IcloudStorageRecord.objects.filter(user_id=user_id).delete()
            icloud_use_qs.update(use_size=0)
            return response.json(0)
        except Exception as e:
            return response.json(500)

    @staticmethod
    def get_icloud_order(request_dict, response):
        page = request_dict.get('pageNo', None)
        line = request_dict.get('pageSize', None)
        order_id = request_dict.get('order_id', None)
        username = request_dict.get('username', None)
        pay_type = request_dict.get('pay_type', None)
        status = request_dict.get('status', None)
        time_range = request_dict.get('time_range', None)
        trade_no = request_dict.get('trade_no', None)
        if not all([page, line]):
            return response.json(444)
        page = int(page)
        line = int(line)
        try:
            order_qs = Order_Model.objects.filter(order_type=4)
            if order_id:
                order_qs = order_qs.filter(orderID=order_id)
            if username:
                order_qs = order_qs.filter(userID__username=username)
            if pay_type:
                order_qs = order_qs.filter(payType=pay_type)
            if status:
                order_qs = order_qs.filter(status=status)
            if time_range:
                start_time, end_time = time_range.split(',')
                order_qs = order_qs.filter(addTime__gte=start_time, addTime__lte=end_time)
            if trade_no:
                order_qs = order_qs.filter(trade_no=trade_no)
            count = order_qs.count()
            order_qs = order_qs.values('orderID', 'trade_no', 'userID__username', 'price', 'status', 'payType', 'desc',
                                       'unify_combo_id', 'paypal', 'refunded_amount', 'addTime', 'updTime')[
                       (page - 1) * line:page * line]
            order_list = []
            for item in order_qs:
                icloud_dict = {
                    'order_id': item['orderID'],
                    'trade_no': item['trade_no'],
                    'username': item['userID__username'],
                    'price': item['price'],
                    'status': item['status'],
                    'pay_type': item['payType'],
                    'refunded_amount': item['refunded_amount'],
                    'add_time': item['addTime'],
                    'upd_time': item['updTime'],
                }
                icloud_meal_qs = ICloudStoreMeal.objects.filter(id=item['unify_combo_id']).values('expire', 'size')
                icloud_dict['expire'] = icloud_meal_qs[0]['expire'] if icloud_meal_qs.exists() else ''
                icloud_dict['size'] = icloud_meal_qs[0]['size'] if icloud_meal_qs.exists() else ''
                icloud_dict['paypal'] = item['paypal'] if item['paypal'] else ''
                order_list.append(icloud_dict)
            return response.json(0, {'list': order_list, 'total': count})
        except Exception as e:
            return response.json(500)
