#!/usr/bin/python3.6
# -*- coding: utf-8 -*-
#
# Copyright (C) 2022 #
# @Time    : 2022/3/9 9:20
# @Author  : ming
# @Email   : zhangdongming@asj6.wecom.work
# @File    : SurveysManageController.py
# @Software: PyCharm
import json
import time

from django.db import connection
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 Surveys, SurveysTitle, CloudVodSurveysAnswer, Device_User, SurveysUserLog
from Object.ResponseObject import ResponseObject
from Object.TokenObject import TokenObject


class SurveysView(View):
    @method_decorator(csrf_exempt)
    def dispatch(self, *args, **kwargs):
        return super(SurveysView, 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):
        token = TokenObject(request.META.get('HTTP_AUTHORIZATION'))
        response = ResponseObject()
        if token.code != 0:
            return response.json(token.code)

        ''' 后台管理'''
        response = ResponseObject(returntype='pc')
        if operation == 'save':
            return self.save(request_dict, response)
        if operation == 'edit':
            return self.edit(request_dict, response)
        if operation == 'list':
            return self.get_page(request_dict, response)
        if operation == 'title/list':
            return self.get_title_list(request_dict, response)
        if operation == 'title/save':
            return self.title_save(request_dict, response)
        if operation == 'title/edit':
            return self.title_edit(request_dict, response)
        if operation == 'title/del':
            return self.title_del(request_dict, response)
        if operation == 'cloud/vod/answer/page':
            return self.cloud_surveys_answer_page(request_dict, response)
        if operation == 'cloud/storage/log/page':
            return self.cloud_storage_user_log_page(request_dict, response)
        return response.json(0)

    @classmethod
    def get_page(cls, request_dict, response):
        pageNo = request_dict.get('pageNo', None)
        pageSize = request_dict.get('pageSize', None)
        if not all([pageNo, pageSize]):
            return response.json(444)

        page = int(pageNo)
        line = int(pageSize)
        try:
            request_qs = Surveys.objects.all()
            total = request_qs.count()
            surveys_page = request_qs.filter().order_by('-created_time')[(page - 1) * line:page * line]
            result_list = []
            for surveys in surveys_page:
                start_time = time.localtime(surveys.start_time)
                endT_time = time.localtime(surveys.end_time)
                created_time = time.localtime(surveys.created_time)
                result_list.append({
                    'id': surveys.id,
                    'no': surveys.no,
                    'userType': surveys.user_type,
                    'startTime': time.strftime("%Y-%m-%d %H:%M:%S", start_time),
                    'endTime': time.strftime("%Y-%m-%d %H:%M:%S", endT_time),
                    'isShow': surveys.is_show,
                    'createdTime': time.strftime("%Y-%m-%d %H:%M:%S", created_time),
                })
            return response.json(0, {'list': result_list, 'total': total})
        except Exception as e:
            print(e)
            return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))

    @classmethod
    def save(cls, request_dict, response):
        no = request_dict.get('no', None)
        if not no:
            return response.json(0)
        if Surveys.objects.filter(no=no).exists():
            return response.json(10, '已存在')
        no = request_dict.get('no', None)
        user_type = request_dict.get('userType', None)
        start_time = request_dict.get('dateTime[0]', None)
        end_time = request_dict.get('dateTime[1]', None)
        is_show = request_dict.get('isShow', None)
        is_show = 1 if is_show == 'true' else 0
        createdTime = int(time.time())
        try:
            surveys = Surveys(no=no, user_type=user_type, start_time=int(start_time),
                              end_time=end_time, is_show=is_show, created_time=int(createdTime))
            surveys.save()
            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)))

    @classmethod
    def edit(cls, request_dict, response):
        sur_id = request_dict.get('id', None)
        if not sur_id:
            return response.json(10, 'id不存在')

        user_type = request_dict.get('userType', None)
        start_time = request_dict.get('dateTime[0]', None)
        end_time = request_dict.get('dateTime[1]', None)
        is_show = request_dict.get('isShow', None)
        is_show = 1 if is_show == 'true' else 0
        Surveys.objects.filter(id=int(sur_id)).update(user_type=int(user_type), start_time=int(start_time),
                                                      end_time=int(end_time),
                                                      is_show=int(is_show))
        return response.json(0)

    @classmethod
    def delete(cls, request_dict, response):
        sId = request_dict.get('id', None)
        if not sId:
            return response.json(10, 'id不存在')
        Surveys.objects.filter(id=sId).delete()
        response.json(0)

    @classmethod
    def title_save(cls, request_dict, response):
        survey_id = request_dict.get('surveyId', None)
        if not survey_id:
            return response(10, 'surveyId is null')
        t_id = request_dict.get('id', None)
        content = request_dict.get('content', None)
        created_time = int(time.time())
        try:
            title = SurveysTitle.objects.filter(id=t_id)
            if title.exists():
                title.update(title_content=content)
            else:
                surveys_title = SurveysTitle(surveys_id=survey_id, title_content=content, created_time=created_time)
                surveys_title.save()
            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)))

    @classmethod
    def get_title_list(cls, request_dict, response):
        survey_id = request_dict.get('surveyId', None)
        info = request_dict.get('info', None)
        if not survey_id:
            return response.json(10, '问卷id不存在')
        title_list = SurveysTitle.objects.filter(surveys_id=survey_id).order_by('-created_time')
        if not title_list.exists():
            if info:
                return response.json(0, {'id': None, 'content': None})
            return response.json(173)
        content = title_list[0]
        if info:
            return response.json(0, {'id': content.id, 'content': content.title_content})
        data = json.loads(content.title_content)
        return response.json(0, {'answers': data})

    @classmethod
    def title_edit(cls, request_dict, response):
        title_id = request_dict.get('id', None)
        if not title_id:
            return response.json(10, 'id不存在')
        content = request_dict.get('content', None)
        surveys_title = SurveysTitle.objects.filter(surveys_id=title_id)
        surveys_title.update(title_content=content)
        return response.json(0)

    @classmethod
    def title_del(cls, request_dict, response):
        title_id = request_dict.get('id', None)
        if not title_id:
            return response.json(10, 'id不存在')
        SurveysTitle.objects.filter(id=title_id).delete()
        return response.json(0)

    @classmethod
    def cloud_surveys_answer_page(cls, request_dict, response):
        pageNo = request_dict.get('pageNo', None)
        pageSize = request_dict.get('pageSize', None)
        user_name = request_dict.get('userName', None)
        country_name = request_dict.get('countryName', None)
        time_range = request_dict.getlist('timeRange[]', None)
        num = request_dict.get('num', 0)
        num = int(num)
        opt_val = request_dict.getlist('optVal', None)
        if not all([pageNo, pageSize]):
            return response.json(444)

        page = int(pageNo)
        line = int(pageSize)
        try:
            request_qs = CloudVodSurveysAnswer.objects.all()
            if user_name:
                request_qs = request_qs.filter(user__username__contains=user_name)
            if country_name:
                request_qs = request_qs.filter(country_name=country_name)
            if num >= 0 and len(opt_val) > 0:
                condition = int(opt_val[0])
                if condition == 1:
                    request_qs = request_qs.filter(answer1__gt=num)
                elif condition == 2:
                    request_qs = request_qs.filter(answer1__lt=num)
                elif condition == 3:
                    request_qs = request_qs.filter(answer1=num)
                elif condition == 4:
                    request_qs = request_qs.filter(answer1__gte=num)
                elif condition == 5:
                    request_qs = request_qs.filter(answer1__lte=num)

            if time_range:
                startTime, endTime = int(time_range[0][:-3]), int(time_range[1][:-3])
                request_qs = request_qs.filter(created_time__gte=startTime, created_time__lte=endTime)
            if not request_qs.exists():
                return response.json(0)
            total = request_qs.count()
            answer_page = request_qs.order_by('-created_time')[(page - 1) * line:page * line]
            result_list = []
            for answer in answer_page:
                d_user_qs = Device_User.objects.filter(userID=answer.user_id)
                if not all(d_user_qs):
                    return response.json(173)
                d_user_qs = d_user_qs[0]
                created_time = time.localtime(answer.created_time)
                result_list.append({
                    'id': answer.id,
                    'uId': d_user_qs.userID,
                    'uName': d_user_qs.username,
                    'nickName': d_user_qs.NickName,
                    'answer1': answer.answer1,
                    'answer2': answer.answer2,
                    'answer3': answer.answer3,
                    'answer4': answer.answer4,
                    'answer5': answer.answer5,
                    'answer6': answer.answer6,
                    'country': answer.country_name,
                    'createdTime': time.strftime("%Y-%m-%d %H:%M:%S", created_time),
                })
            return response.json(0, {'list': result_list, 'total': total})
        except Exception as e:
            print(e)
            return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))

    ''' 云存用户问卷调查统计 '''

    @classmethod
    def cloud_storage_user_log_page(cls, request_dict, response):
        pageNo = request_dict.get('pageNo', None)
        pageSize = request_dict.get('pageSize', None)
        if not all([pageNo, pageSize]):
            return response.json(444)
        try:
            page = int(pageNo)
            size = int(pageSize)
            cursor = connection.cursor()
            sql = 'SELECT o.orderID,o.userID_id,ca.id,ca.country_name as countryName '
            sql += 'FROM orders o LEFT JOIN cloud_vod_surveys_answer ca ON o.userID_id = ca.user_id '
            sql += ' WHERE o.status = %s AND o.order_type = %s GROUP BY o.userID_id '
            cursor.execute(sql, [1, 0, ])
            cloud_count = cursor.fetchall()
            total = len(cloud_count)
            readCount = SurveysUserLog.objects.count()
            unreadCount = total - readCount
            sql += 'order by ca.created_time DESC,orderID DESC LIMIT %s,%s '
            cursor.execute(sql, [1, 0, ((page - 1) * size), size, ])
            data_obj = cursor.fetchall()
            cursor.close()  # 执行完，关闭
            connection.close()
            result_list = []
            col_names = [desc[0] for desc in cursor.description]
            for item in data_obj:
                tMap = dict(zip(col_names, item))
                user_id = tMap['userID_id']
                d_user = Device_User.objects.filter(userID=user_id)
                tMap['uName'] = d_user[0].username
                tMap['nickName'] = d_user[0].NickName
                tMap.update({"type": 1})
                survey_log_qs = SurveysUserLog.objects.filter(user_id=user_id)
                if survey_log_qs.exists():
                    survey_log = survey_log_qs[0]
                    created_time = time.localtime(survey_log.created_time)
                    tMap.update({"type": survey_log.type})
                    tMap.update({"isFilled": survey_log.is_filled})
                    tMap['createdTime'] = time.strftime("%Y-%m-%d %H:%M:%S", created_time),
                    tMap.update({"isUpgrade": 1})
                else:
                    tMap.update({"isFilled": 0})
                    tMap.update({"createdTime": ''})
                    tMap.update({"isUpgrade": 0})
                result_list.append(tMap)
            return response.json(0, {'list': result_list, 'total': total, 'readCount': readCount,
                                     'unreadCount': unreadCount})
        except Exception as e:
            print(e)
            return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
