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

from django.db import transaction
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, Order_Model, CloudVodSurveysAnswer, SurveysUserLog, \
    CloudVodSurveysOperateLog
from Object.utils import LocalDateTimeUtil

from Object.ResponseObject import ResponseObject
from Object.TokenObject import TokenObject
from Service.CommonService import CommonService


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

        ''' API '''
        logger.info('---- this user id:{}，dict{}'.format(userID, request_dict))
        if operation == 'get/info':
            return self.check_stock_user(userID, request_dict, response)
        if operation == 'cloud/answer/save':
            ip = CommonService.get_ip_address(request)
            return self.answer_save(userID, ip, request_dict, response)
        if operation == "cloud/storage/icon/close":
            self.cloud_vob_operate_log_save(status=2, userId=userID)
        if operation == "entrance/cloud/storage/icon":
            return self.entrance_cloud_storage_icon(userID, request_dict, response)
        return response.json(0)

    def check_stock_user(self, user_id, request_dict, response):
        order = Order_Model.objects.filter(userID=user_id, status=1, order_type=0)
        if not order.exists() and order.count() == 0:
            return response.json(10030)
        try:
            lang = request_dict.get('lang', 'en')
            no = '01'
            surveys = Surveys.objects.filter(no=no, user_type=1)
            if not surveys.exists():
                return response.json(173)
            result = surveys[0]
            surveys_title = SurveysTitle.objects.filter(surveys_id=result.id).order_by('-created_time')

            submit = 0
            if surveys_title.exists():
                surveys_title = surveys_title[0]
                cloud_vod = CloudVodSurveysAnswer.objects.filter(title_id=surveys_title.id, user_id=user_id)
                if cloud_vod.exists():
                    submit = 1
            close = self.check_user_is_icon_close(userId=user_id)
            data = {
                'no': result.no,
                'title': 'Zosi Cloud Storage',
                'imageUrl': 'https://d2cjxvw3tr9apc.cloudfront.net/app/images/ansjer-cloud-surveys.png',
                'userType': result.user_type,
                'startTime': result.start_time,
                'endTime': result.end_time,
                'isShow': 0 if close else result.is_show,
                'isSubmit': submit,
                'page': '/surveys?lang=' + lang + '&token=' if result.is_show == 1 else ''
            }
            localTime = int(time.time())
            if result.start_time <= localTime <= result.end_time:
                status = True if submit == 1 else False
                self.surveys_user_log_save(status, user_id)
                if not submit == 1:
                    self.cloud_vob_operate_log_save(2 if close else submit, userId=user_id)
            return response.json(0, data)
        except Exception as e:
            print(e)
            return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))

    @classmethod
    def surveys_user_log_save(cls, status=False, userId='', survey_type=1):
        if userId:
            user_log = SurveysUserLog.objects.filter(user_id=userId, type=survey_type)
            if user_log.exists():
                if status and user_log[0].is_filled == 0:
                    user_log.update(is_filled=1)
            else:
                createdTime = int(time.time())
                user_log = SurveysUserLog(user_id=userId, type=1, created_time=createdTime)
                user_log.save()

    @classmethod
    def check_user_is_icon_close(cls, userId):
        if userId:
            start_time, end_time = LocalDateTimeUtil.get_today_date(True)
            user_operate_log_list = CloudVodSurveysOperateLog.objects.filter(user_id=userId, status=2,
                                                                             created_time__gte=start_time,
                                                                             created_time__lte=end_time)
            if user_operate_log_list.exists():
                return True
        return False

    @classmethod
    def cloud_vob_operate_log_save(cls, status=0, userId=''):
        """ 保存用户操作记录 """
        try:
            with transaction.atomic():
                if userId:
                    start_time, end_time = LocalDateTimeUtil.get_today_date(True)
                    user_operate_qs = CloudVodSurveysOperateLog.objects.filter(user_id=userId,
                                                                               created_time__gte=start_time,
                                                                               created_time__lte=end_time)
                    local_time = int(time.time())
                    if user_operate_qs.exists():
                        operate_log = user_operate_qs.first()
                        if not operate_log.status == status:
                            operate_log.status = status
                            operate_log.updated_time = local_time
                            operate_log.save()
                    else:
                        operate_log = CloudVodSurveysOperateLog(user_id=userId, status=status, updated_time=local_time,
                                                                created_time=local_time)
                        operate_log.save()
        except Exception as e:
            print(e)

    @classmethod
    def answer_save(cls, userId, ip, request_dict, response):
        logger = logging.getLogger('info')
        try:
            ipInfo = CommonService.getIpIpInfo(ip, "CN")
            country_name = ipInfo['country_name']
            no = request_dict.get('no', None)
            if not no:
                return response.json(10, 'no is null')
            survey = Surveys.objects.filter(no=no)
            if survey.exists():
                survey = survey[0]
                survey_title = SurveysTitle.objects.filter(surveys=survey.id)
                if survey_title.exists():
                    survey_title = survey_title[0]
                    cloud_vod = CloudVodSurveysAnswer.objects.filter(title_id=survey_title.id, user_id=userId)
                    if cloud_vod.exists():
                        return response.json(10, "Do not submit twice")
                    score = request_dict.get('score', None)
                    topicA = request_dict.get('topicA', None)
                    topicB = request_dict.get('topicB', None)
                    topicC = request_dict.get('topicC', None)
                    topicD = request_dict.get('topicD', None)
                    topicF = request_dict.get('topicF', None)
                    createdTime = int(time.time())
                    answer = CloudVodSurveysAnswer(title_id=survey_title.id, user_id=userId, ip=ip, answer1=int(score),
                                                   answer2=topicA,
                                                   answer3=topicB, answer4=topicC, answer5=topicD, answer6=topicF,
                                                   created_time=createdTime, country_name=country_name)
                    answer.save()
                    SurveysUserLog.objects.filter(user_id=userId, type=1).update(is_filled=1)
                    cls.cloud_vob_operate_log_save(status=1, userId=userId)
            return response.json(0)
        except Exception as e:
            logger.info('异常详情,errLine:{}, errMsg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
            return response.json(200, repr(e))

    @classmethod
    def entrance_cloud_storage_icon(cls, userID, request_dict, response):
        status = request_dict.get('status', None)
        if not status:
            return response.json(444, 'status')
        status = int(status)
        start_time, end_time = LocalDateTimeUtil.get_today_date(True)
        local_time = int(time.time())
        try:
            if status == 3:  #
                cloud_vod_surveys_Operate_qs = CloudVodSurveysOperateLog.objects.filter(user_id=userID, status=status,
                                                                                        created_time__gte=start_time,
                                                                                        created_time__lte=end_time)
                if not cloud_vod_surveys_Operate_qs.exists():  # 判断用户当天是否查阅问卷
                    cls.cloud_vob_operate_log_save(status=status, userId=userID)
                else:
                    user_record_qs = cloud_vod_surveys_Operate_qs.first()
                    user_record_qs.updated_time = local_time
                    user_record_qs.save()
            return response.json(0)
        except Exception as e:
            print(e)
