#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
@Copyright (C) ansjer cop Video Technology Co.,Ltd.All rights reserved.
@AUTHOR: ASJRD018
@NAME: AnsjerFormal
@software: PyCharm
@DATE: 2019/1/18 10:45
@Version: python3.6
@MODIFY DECORD:ansjer dev
@file: SysMsg.py
@Contact: chanjunkai@163.com
"""

import json
import time

import oss2
from django.db import transaction
from django.views.generic.base import View

from Ansjer.config import OSS_STS_ACCESS_KEY, OSS_STS_ACCESS_SECRET
from Model.models import FeedBackModel, StatResModel
from Object.ResponseObject import ResponseObject
from Object.TokenObject import TokenObject
from Service.CommonService import CommonService
from Service.ModelService import ModelService


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

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

    def validation(self, request_dict, operation):
        response = ResponseObject()
        token = request_dict.get('token', None)
        tko = TokenObject(token)
        if tko.code == 0:
            userID = tko.userID
            if operation == 'add':
                return self.do_add(userID, request_dict, response)
            elif operation == 'getUploadUrl':
                return self.do_get_upload_url(request_dict, response)
            elif operation == 'query':
                return self.do_query(userID, request_dict, response)
            elif operation == 'delete':
                return self.do_delete(userID, request_dict, response)
            elif operation == 'queryByAdmin':
                return self.do_query_by_admin(userID, request_dict, response)
            elif operation == 'deleteByAdmin':
                return self.do_delete_by_admin(userID, request_dict, response)
            elif operation == 'deleteImage':
                return self.do_delete_image(userID, request_dict, response)
            else:
                return response.json(414)
        else:
            return response.json(tko.code)

    def do_query(self, userID, request_dict, response):
        page = request_dict.get('page', None)
        line = request_dict.get('line', None)
        if page and line:
            page = int(page)
            line = int(line)
        else:
            return response.json(444, 'page,line')

        fb_qs = FeedBackModel.objects.filter(userID_id=userID)[(page - 1) * line:page * line]. \
            values('id', 'status', 'content', 'addTime', 'updTime', 'type')
        sid_list = []
        for fb in fb_qs:
            sid_list.append(fb['id'])
        sm_qs = StatResModel.objects.filter(feedbackmodel__id__in=sid_list).values('id', 'name', 'feedbackmodel__id')
        # return response.json(0,list(sm_qs))
        auth = oss2.Auth(OSS_STS_ACCESS_KEY, OSS_STS_ACCESS_SECRET)
        bucket = oss2.Bucket(auth, 'oss-cn-hongkong.aliyuncs.com', 'statres')
        res = []
        for fb in fb_qs:
            fb['img_url'] = []
            for sm in sm_qs:
                if sm['feedbackmodel__id'] == fb['id']:
                    obj = 'feedback/' + sm['name']
                    img_url = bucket.sign_url('GET', obj, 3600)
                    fb['img_url'].append(img_url)
                    # fb['FS__name'] = sm['name']
            res.append(fb)
        return response.json(0, res)

    def do_add(self, userID, request_dict, response):
        nowTime = int(time.time())
        content = request_dict.get('content', None)
        type = request_dict.get('type', None)
        res_1 = request_dict.get('res_1', None)
        res_2 = request_dict.get('res_2', None)
        res_3 = request_dict.get('res_3', None)

        app = request_dict.get('app', None)
        phone_model = request_dict.get('phone_model', None)
        os_version = request_dict.get('os_version', None)
        uid = request_dict.get('uid', None)
        product_type = request_dict.get('product_type', None)
        app_version = request_dict.get('app_version', None)
        appBundleId = request_dict.get('appBundleId', None)
        email = request_dict.get('email', None)
        score = request_dict.get('score', None)

        try:
            with transaction.atomic():
                fb = FeedBackModel()
                fb.addTime = nowTime
                fb.updTime = nowTime
                fb.content = content
                if type:
                    fb.type = type
                if app:
                    fb.app = app
                if phone_model:
                    fb.phone_model = phone_model
                if os_version:
                    fb.os_version = os_version
                if uid:
                    fb.uid = uid
                if product_type:
                    fb.product_type = product_type
                if app_version:
                    fb.app_version = app_version
                if appBundleId:
                    fb.appBundleId = appBundleId
                if email:
                    fb.email = email
                if score:
                    fb.score = score
                fb.userID_id = userID
                fb.save()
                if res_1:
                    fb.FS.add(StatResModel.objects.create(addTime=nowTime, name=res_1))
                if res_2:
                    fb.FS.add(StatResModel.objects.create(addTime=nowTime, name=res_2))
                if res_3:
                    fb.FS.add(StatResModel.objects.create(addTime=nowTime, name=res_3))
        except Exception as e:
            print(repr(e))
            return response.json(500, repr(e))
        else:
            return response.json(0)

    def do_get_upload_url(self, request_dict, response):
        uploadType = request_dict.get('uploadType', None)
        uploadType = json.loads(uploadType)
        if len(uploadType):
            res = []
            auth = oss2.Auth(OSS_STS_ACCESS_KEY, OSS_STS_ACCESS_SECRET)
            bucket = oss2.Bucket(auth, 'oss-cn-hongkong.aliyuncs.com', 'statres')
            for upType in uploadType:
                name = CommonService.createOrderID()
                s_name = str(name) + '.' + upType
                obj = 'feedback/' + s_name

                url = bucket.sign_url('PUT', obj, 7200)
                res.append({'put_url': url, 'res_name': s_name})
            return response.json(0, res)
        else:
            return response.json(444, 'uploadType')

    def do_delete(self, userID, request_dict, response):
        id = request_dict.get('id', None)
        try:
            fb_qs = FeedBackModel.objects.get(userID_id=userID, id=id)
            sr_id_list = fb_qs.FS.values_list('id', flat=True)
            StatResModel.objects.filter(id__in=sr_id_list).delete()
            fb_qs.delete()
            # is_delete = StatResModel.objects.filter(id__in=sr_id_list).delete()

            # print(is_delete)
            print('----------')

        except Exception as e:
            return response.json(500, repr(e))
        else:
            return response.json(0)

    def do_query_by_admin(self, userID, request_dict, response):
        own_perm = ModelService.check_perm(userID, 30)
        if own_perm:
            page = request_dict.get('page', None)
            line = request_dict.get('line', None)
            status = request_dict.get('status', None)
            username = request_dict.get('username', None)
            type = request_dict.get('type', None)
            if page and line:
                page = int(page)
                line = int(line)
                filter_data = {}
                if status:
                    filter_data = {'status': status}
                if username:
                    filter_data = {'userID_id': ModelService.get_userID_byname(username)}
                if type:
                    filter_data = {'type': type}

                try:
                    fb_qs = FeedBackModel.objects.filter()
                except Exception as e:
                    return response.json(500, repr(e))
                print('----------')
                if filter_data:
                    fb_qs = fb_qs.filter(**filter_data)
                count = fb_qs.count()
                fb_qs = fb_qs[(page - 1) * line:page * line].values('id', 'type', 'status', 'content', 'addTime', 'app',
                                                                    'uid', 'os_version', 'phone_model', 'product_type',
                                                                    'updTime', 'userID__username', 'userID__phone',
                                                                    'userID__userEmail', 'app_version', 'appBundleId',
                                                                    'email', 'score'
                                                                    )
                sid_list = []
                print(fb_qs)
                for fb in fb_qs:
                    sid_list.append(fb['id'])
                sm_qs = StatResModel.objects.filter(feedbackmodel__id__in=sid_list).values('id', 'name',
                                                                                           'feedbackmodel__id')
                auth = oss2.Auth(OSS_STS_ACCESS_KEY, OSS_STS_ACCESS_SECRET)
                bucket = oss2.Bucket(auth, 'oss-cn-hongkong.aliyuncs.com', 'statres')
                res = []
                print(sm_qs)
                for fb in fb_qs:
                    fb['img_url'] = []
                    for sm in sm_qs:
                        if sm['feedbackmodel__id'] == fb['id']:
                            obj = 'feedback/' + sm['name']
                            img_url = bucket.sign_url('GET', obj, 3600)
                            # img_url.replace('statres.oss-cn-hongkong.aliyuncs.com','static.zositech.xyz')
                            fb['img_url'].append(img_url)
                            # fb['FS__name'] = sm['name']
                            if fb['userID__username'] == '':
                                fb['userID__username'] = fb['userID__userEmail']
                            if fb['userID__username'] == '':
                                fb['userID__username'] = fb['userID__phone']
                    res.append(fb)
                return response.json(0, {'datas': res, 'count': count})
            else:
                return response.json(444, 'page,line')
        else:
            return response.json(404)

    def do_delete_by_admin(self, userID, request_dict, response):
        own_perm = ModelService.check_perm(userID, 10)
        if own_perm:

            id = request_dict.get('id', None)
            try:
                fb_qs = FeedBackModel.objects.get(id=id)
                sr_id_list = fb_qs.FS.values_list('id', flat=True)
                StatResModel.objects.filter(id__in=sr_id_list).delete()
                fb_qs.delete()
                print('----------')
            except Exception as e:
                return response.json(500, repr(e))
            else:
                return response.json(0)
        else:
            return response.json(404)

    def do_delete_image(self, userID, request_dict, response):
        # own_perm = ModelService.check_perm(userID, 10)
        # if not own_perm:
        #     return response.json(404)
        end_time = request_dict.get('end_time', None)
        if end_time is None:
            return response.json(444)
        sys_ms_qs = FeedBackModel.objects.filter(addTime__lt=end_time).order_by('id').values('id')
        ids = []
        for sys_ms in sys_ms_qs:
            ids.append(sys_ms['id'])

        sm_qs = StatResModel.objects.filter(feedbackmodel__id__in=ids).values('id', 'name')
        names = []
        time_struct = time.localtime()
        current_year = time_struct.tm_year
        target_year = current_year - 1
        str_prefix = str(target_year)
        print(str_prefix)
        for sm in sm_qs:
            name = sm['name']
            if name.find(str_prefix) == 0:
                names.append('feedback/' + name)

        # auth = oss2.Auth(OSS_STS_ACCESS_KEY, OSS_STS_ACCESS_SECRET)
        # bucket = oss2.Bucket(auth, 'oss-cn-hongkong.aliyuncs.com', 'statres')
        # bucket.batch_delete_objects(names)
        # FeedBackModel.objects.filter(id__in=ids).delete()
        print(names)
        print(len(names))

        return response.json(0)