#!/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: 2018/9/11 15:08
@Version: python3.6
@MODIFY DECORD:ansjer dev
@file: UserController.py
@Contact: chanjunkai@163.com
"""
import datetime
import traceback
import time
import logging
import jwt
import oss2
import simplejson
import simplejson as json
import requests
from django.contrib.auth.hashers import make_password, check_password  # 对密码加密模块
from django.db import transaction
from django.db.models import Q
from django.http import HttpResponseRedirect
from django.utils.decorators import method_decorator
from django.utils.timezone import utc
from django.views.decorators.csrf import csrf_exempt
from django.views.generic import TemplateView
from jwt.algorithms import RSAAlgorithm
from ratelimit.decorators import ratelimit

from Ansjer.config import AuthCode_Expire, SERVER_DOMAIN, APNS_CONFIG, JPUSH_CONFIG, FCM_CONFIG, TUTK_PUSH_DOMAIN, \
    OSS_STS_ACCESS_KEY, OSS_STS_ACCESS_SECRET
from Controller.CheckUserData import DataValid, date_handler, RandomStr
from Model.models import Device_User, Role, UidPushModel, UserOauth2Model, UserExModel, Device_Info, UidSetModel, \
    UserAppFrequencyModel, CountryIPModel, CountryModel, UidChannelSetModel, MenuModel, FeedBackModel, StatResModel, \
    SysMassModel, App_Info, SysMsgModel
from Object.AWS.SesClassObject import SesClassObject
from Object.AliSmsObject import AliSmsObject
from Object.RedisObject import RedisObject
from Object.ResponseObject import ResponseObject
from Object.TokenObject import TokenObject
from Service.CommonService import CommonService
from Service.ModelService import ModelService
from Service.TemplateService import TemplateService
from django.views.generic import View
import base64
import random
from io import BytesIO
from PIL import Image, ImageDraw, ImageFont
from django.shortcuts import HttpResponse
from Ansjer.config import BASE_DIR


# 登录
class LoginView(TemplateView):
    @method_decorator(csrf_exempt)  # @csrf_exempt
    def dispatch(self, *args, **kwargs):
        return super(LoginView, self).dispatch(*args, **kwargs)

    def post(self, request, *args, **kwargs):
        request.encoding = 'utf-8'
        request_dict = request.POST
        language = request_dict.get('language', 'en')
        response = ResponseObject(language,'pc')

        return self.validates(request_dict, response)



    def validates(self, request_dict, response):
        username = request_dict.get('username', None)
        password = request_dict.get('password', None)
        if not username or not password:
            return response.json(111)
        username = username.strip()
        password = password.strip()
        data_valid = DataValid()
        if data_valid.email_validate(username):
            return self.do_email_login(username, password, response)
        elif data_valid.mobile_validate(username):
            return self.do_phone_login(username, password, response)
        elif data_valid.name_validate(username):
            return self.do_name_login(username, password, response)
        else:
            return response.json(107)

    def do_email_login(self, email, password, response):
        user_qs = Device_User.objects.filter(Q(username=email) | Q(userEmail=email))
        return self.valid_login(user_qs, password, response)

    def do_phone_login(self, phone, password, response):
        user_qs = Device_User.objects.filter(Q(phone=phone) | Q(username=phone), is_active=True, user_isValid=True)
        return self.valid_login(user_qs, password, response)

    def do_name_login(self, username, password, response):
        user_qs = Device_User.objects.filter(Q(username=username) | Q(phone=username) | Q(userEmail=username),
                                             is_active=True, user_isValid=True)
        return self.valid_login(user_qs, password, response)

    def valid_login(self, user_qs, password, response):
        if not user_qs.exists():
            return response.json(104)
        # users = user_qs.values('role__rid', 'role__roleName', 'userID', 'role', 'NickName', 'username', 'userEmail',
        #                        'phone', 'password', 'userIconPath', 'user_isValid', 'is_active')[0]
        users = user_qs.values('role__rid', 'role__roleName', 'userID', 'NickName', 'username', 'userEmail',
                               'phone', 'password', 'userIconPath')[0]
        if not check_password(password, users['password']):
            return response.json(111)
        userID = users['userID']
        tko = TokenObject(returntpye='pc')
        res = tko.generate(
            data={'userID': userID, 'lang': response.lang, 'user': users['username'], 'm_code': '123413243214'})
        if tko.code == 0:
            now_time = datetime.datetime.utcnow().replace(tzinfo=utc).astimezone(utc)
            user_qs.update(last_login=now_time, language=response.lang)
            res['rid'] = users['role__rid']
            res['roleName'] = users['role__roleName']
            res['permList'] = ModelService.own_permission(userID)
            res['userID'] = userID
            # 昵称，邮箱，电话，刷新，头像
            userIconPath = str(users['userIconPath'])
            if userIconPath and userIconPath.find('static/') != -1:
                userIconPath = userIconPath.replace('static/', '').replace('\\', '/')
                res['userIconUrl'] = SERVER_DOMAIN + 'account/getAvatar/' + userIconPath
            else:
                res['userIconUrl'] = ''
            res['NickName'] = users['NickName'] if users['NickName'] is not None else ''
            res['username'] = users['username'] if users['username'] is not None else ''
            res['userEmail'] = users['userEmail'] if users['userEmail'] is not None else ''
            res['phone'] = users['phone'] if users['phone'] is not None else ''
            return response.json(0, res)
        else:
            return response.json(tko.code)




# 获取登录权限
class GetPermissions(TemplateView):
    @method_decorator(csrf_exempt)  # @csrf_exempt
    def dispatch(self, *args, **kwargs):
        return super(GetPermissions, self).dispatch(*args, **kwargs)

    def get(self, request, *args, **kwargs):
        token = request.META.get('HTTP_AUTHORIZATION')
        request.encoding = 'utf-8'
        request_dict = request.GET
        language = request_dict.get('language', 'en')
        response = ResponseObject(language, 'pc')
        return self.validates(request_dict,token, response)




    def validates(self, request_dict,token, response):
        tko = TokenObject(token,returntpye='pc')
        response.lang = tko.lang
        if tko.code != 0:
            return response.json(tko.code)
        userID = tko.userID


        user_qs = Device_User.objects.filter(userID=userID)
        if not user_qs.exists():
            return response.json(104)
        #待补充逻辑
        username = user_qs[0].username
        userIconPath = user_qs[0].userIconPath.url
        if userIconPath:
            if userIconPath.find('static/') != -1:
                userIconPath = userIconPath.replace('static/', '').replace('\\', '/')
                userIconUrl = SERVER_DOMAIN + 'account/getAvatar/' + userIconPath

        role_qs = Role.objects.filter(device_user=userID)
        menu_qs = MenuModel.objects.filter(role__in=role_qs,menutype=2);
        perms = []
        for menu in menu_qs:
            perms.append(menu.menu_code)
        res={
          "code": 200,
          "msg": "success",
          "data": {
            "roles": ["admin"], # 一个用户可包含多个角色如["admin","editor","XXXX"]，必须返回，如小项目用不到角色权限请返回 ["admin"]
            "ability": ["READ", "WRITE", "DELETE"], # 如果用不到rabc精细化权限可以不返回，建议返回
            "username": username, # 用户名，必须返回
            "avatar": userIconUrl,# 头像，必须返回
            "perms": perms
          }
        }
        return response.json(0, res)


# 获取菜单
class GetList(TemplateView):
    @method_decorator(csrf_exempt)  # @csrf_exempt
    def dispatch(self, *args, **kwargs):
        return super(GetList, self).dispatch(*args, **kwargs)

    def get(self, request, *args, **kwargs):
        token = request.META.get('HTTP_AUTHORIZATION')
        request.encoding = 'utf-8'
        request_dict = request.GET
        language = request_dict.get('language', 'en')
        response = ResponseObject(language, 'pc')
        return self.validates(request_dict,token, response)


    def validates(self, request_dict,token, response):
        tko = TokenObject(token,returntpye='pc')
        response.lang = tko.lang
        if tko.code != 0:
            return response.json(tko.code)
        userID = tko.userID

        role_qs =Role.objects.filter(device_user=userID)
        menu_qs = MenuModel.objects.filter(parentId=0,role__in=role_qs,menutype=1);
        list = []

        for menu in menu_qs:
            list.append(
                {
                'id': menu.id,
                'parentId': menu.parentId,
                'path': menu.path,
                'name': menu.name,
                'component': menu.component,
                'meta': {
                        'hidden': menu.hidden,
                        'levelHidden': menu.levelHidden,
                        'title': menu.title,
                        'icon': menu.icon,
                        'isCustomSvg':menu.isCustomSvg,
                        'noKeepAlive': menu.noKeepAlive,
                        'noClosable':menu.noClosable,
                        'badge': menu.badge,
                        'tabHidden': menu.tabHidden,
                        'activeMenu': menu.activeMenu,
                        'dot':menu.dot,
                        'dynamicNewTab': menu.dynamicNewTab,
                        'sort': menu.sort
                    }
                }
            )
        menu_qs = MenuModel.objects.filter(role__in=role_qs,menutype=1)
        menulist = []
        for objlist in list:
            menulist.append(self.menulist(menu_qs, objlist))
        return response.json(0, {'list': menulist})

    def menulist(self, menu_qs, objlist):
        if objlist is None:
            return
        for menu in menu_qs:
            if objlist['id'] == menu.parentId:
                if 'children' not in objlist:
                    objlist['children'] = []

                obj = {
                    'id': menu.id,
                    'parentId': menu.parentId,
                    'path': menu.path,
                    'name': menu.name,
                    'component': menu.component,
                    'menutype': menu.menutype,
                    'menu_code': menu.menu_code,
                    'meta': {
                        'hidden': menu.hidden,
                        'levelHidden': menu.levelHidden,
                        'title': menu.title,
                        'icon': menu.icon,
                        'isCustomSvg': menu.isCustomSvg,
                        'noKeepAlive': menu.noKeepAlive,
                        'noClosable': menu.noClosable,
                        'badge': menu.badge,
                        'tabHidden': menu.tabHidden,
                        'activeMenu': menu.activeMenu,
                        'dot': menu.dot,
                        'dynamicNewTab': menu.dynamicNewTab,
                        'sort': menu.sort
                    }
                }
                objlist['children'].append(
                    obj
                )
                self.menulist(menu_qs, obj)

        return objlist



class UserManagement(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 == 'sendSysMessage':
            return self.sendSysMessage(request_dict, response)
        elif operation == 'getAppDataList':
            return self.getAppDataList(request_dict, response)
        elif operation == 'replyFeedBack':
            return self.replyFeedBack(request_dict, response)
        elif operation == 'sendSysMsgToUser':
            return self.sendSysMsgToUser(request_dict, response)
        else:
            tko = TokenObject(request.META.get('HTTP_AUTHORIZATION'), returntpye='pc')
            if tko.code != 0:
                return response.json(tko.code)
            response.lang = tko.lang
            userID = tko.userID
            if operation == 'getUserInfo':
                return self.getUserInfo(userID, request_dict, response)
            elif operation == 'AddOrEditAccount':
                return self.AddOrEditAccount(userID, request_dict, response)
            elif operation == 'doDelete':
                return self.doDelete(request_dict, response)
            elif operation == 'resetPassword':
                return self.resetPassword(request_dict, response)
            elif operation == 'getFeedbackList':
                return self.getFeedbackList(request_dict, response)
            elif operation == 'deleteFeedBack':
                return self.deleteFeedBack(request_dict, response)
            elif operation == 'getSysMessageList':
                return self.getSysMessageList(request_dict, response)
            else:
                return response.json(404)

    def getUserInfo(self, userID, request_dict, response):
        print('request_dict: ', request_dict)
        username = request_dict.get('username', '').strip()   # 移除字符串头尾的空格
        NickName = request_dict.get('NickName', '').strip()
        phone = request_dict.get('phone', '').strip()
        userEmail = request_dict.get('userEmail', '').strip()
        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:
            if username or NickName or phone or userEmail:
                # 条件查询
                if username:
                    device_user_qs = Device_User.objects.filter(username__contains=username)
                if NickName:
                    device_user_qs = Device_User.objects.filter(NickName__contains=NickName)
                if phone:
                    device_user_qs = Device_User.objects.filter(phone__contains=phone)
                if userEmail:
                    device_user_qs = Device_User.objects.filter(userEmail__contains=userEmail)
                if not device_user_qs.exists():
                    return response.json(0)
                total = len(device_user_qs)
                device_users = device_user_qs[(page - 1) * line:page * line]

            else:
                total = Device_User.objects.filter().count()
                device_users = Device_User.objects.filter()[(page - 1) * line:page * line]
            user_list = []
            for device_user in device_users:
                role = device_user.role.first()
                rid = role.rid if role else 1   # 不存在角色默认分配为'Users'
                user_list.append({
                    'userID': device_user.userID,
                    'username': device_user.username,
                    'NickName': device_user.NickName,
                    'role': Role.objects.get(rid=rid).roleName,
                    'phone': device_user.phone,
                    'userEmail': device_user.userEmail,
                    'data_joined': device_user.data_joined.strftime("%Y-%m-%d %H:%M:%S"),
                    'last_login': device_user.last_login.strftime("%Y-%m-%d %H:%M:%S"),
                    'online': device_user.online,
                })
            print('user_list: ', user_list)
            return response.json(0, {'list': user_list, 'total': total})
        except Exception as e:
            print(e)
            return response.json(500, repr(e))

    def AddOrEditAccount(self, userID, request_dict, response):
        # 添加/编辑用户
        print('request_dict: ', request_dict)
        username = request_dict.get('username', '').strip()   # 移除字符串头尾的空格
        userEmail = request_dict.get('userEmail', '').strip()
        roleName = request_dict.get('role', None)
        password = request_dict.get('password', None)
        isEdit = request_dict.get('isEdit', None)

        # 校验用户名,邮箱,密码是否符合规则
        dataValid = DataValid()
        if not username or not dataValid.name_validate(username):
            return response.json(444, {'Parameter error': 'username'})
        if userEmail and not dataValid.email_validate(userEmail):
            return response.json(444, {'Parameter error': 'userEmail'})
        if not isEdit:  # 添加用户需要输入密码
            if not password or not dataValid.password_validate(password):
                return response.json(444, {'Parameter error': 'password'})

        try:
            if isEdit:  # 编辑用户信息
                userID = request_dict.get('userID')
                user_data = {
                    "username": username,
                    "NickName": username,
                    "userEmail": userEmail,
                    "password": make_password(password),
                }
                device_user_qs = Device_User.objects.filter(userID=userID)
                device_user_qs.update(**user_data)

                # 如果角色改变,修改用户角色
                device_user_role = device_user_qs[0].role
                user_role = device_user_role.first()
                if not user_role or roleName != user_role.roleName:
                    device_user_role.clear()
                    role_qs = Role.objects.filter(roleName=roleName)  # 账号角色
                    device_user_qs[0].role.set(role_qs)
            else:   # 添加用户
                # 查询邮箱是否已注册
                if Device_User.objects.filter(userEmail=userEmail).exists():
                    return response.json(103)
                role_qs = Role.objects.filter(roleName=roleName)    # 账号角色
                # 创建用户
                user_data = {
                    "username": username,
                    "NickName": username,
                    "userEmail": userEmail,
                    "password": make_password(password),
                    "userID": CommonService.getUserID(μs=False, setOTAID=True),
                    "is_active": True,
                    "user_isValid": True,
                }
                Device_User.objects.create(**user_data).role.set(role_qs)
            return response.json(0)
        except Exception as e:
            print(e)
            return response.json(500, repr(e))

    def doDelete(self, request_dict, response):
        userID = request_dict.get('userID', '')
        if not userID:
            return response.json(444)
        try:
            Device_User.objects.filter(userID=userID).delete()
            return response.json(0)
        except Exception as e:
            print(e)
            return response.json(500, repr(e))

    def resetPassword(self, request_dict, response):
        userID = request_dict.get('userID', None)
        if not userID:
            return response.json(444)
        try:
            password = '123456'
            is_update = Device_User.objects.filter(userID=userID).update(password=make_password(password))
            if is_update:
                return response.json(0)
            else:
                return response.json(177)
        except Exception as e:
            print(e)
            return response.json(500, repr(e))

    def getFeedbackList(self, request_dict, response):
        status = request_dict.get('status', 0)
        username = request_dict.get('username', None)
        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:
            filter_data = {}
            if status or username:
                if status:
                    filter_data['status'] = int(status)
                if username:
                    filter_data['userID_id'] = ModelService.get_userID_byname(username)
            feed_back_qs = FeedBackModel.objects.filter()
            if filter_data:
                feed_back_qs = feed_back_qs.filter(**filter_data)
            total = feed_back_qs.count()
            feed_backs = feed_back_qs[(page - 1) * line:page * line]. values(
                'id',
                'userID__username',
                'userID__phone',
                'userID__userEmail',
                'content',
                'addTime',
                'status',
                'type',
                'app',
                'app_version',
                'phone_model',
                'os_version',
                'uid',
                'appBundleId',
                'score')

            feed_back_id_list = [feed_back['id'] for feed_back in feed_backs]
            stat_res_qs = StatResModel.objects.filter(
                feedbackmodel__id__in=feed_back_id_list).values(
                'name', 'feedbackmodel__id')
            auth = oss2.Auth(OSS_STS_ACCESS_KEY, OSS_STS_ACCESS_SECRET)
            bucket = oss2.Bucket(
                auth, 'oss-cn-hongkong.aliyuncs.com', 'statres')
            feed_back_list = []
            for feed_back in feed_backs:
                feed_back['img_url'] = []
                for stat_res in stat_res_qs:
                    if stat_res['feedbackmodel__id'] == feed_back['id']:
                        obj = 'feedback/' + stat_res['name']
                        img_url = bucket.sign_url('GET', obj, 3600)
                        feed_back['img_url'].append(img_url)
                        if not feed_back['userID__username']:
                            feed_back['userID__username'] = feed_back['userID__userEmail'] if feed_back[
                                'userID__userEmail'] else feed_back['userID__phone']
                feed_back_list.append(feed_back)
            return response.json(0, {'list': feed_back_list, 'total': total})
        except Exception as e:
            print(e)
            return response.json(500, repr(e))

    def replyFeedBack(self, request_dict, response):
        feedBackID = request_dict.get('feedBackID', None)
        msg = request_dict.get('msg', None)
        uid = request_dict.get('uid', None)

        if not all([feedBackID, msg]):
            return response.json(444)

        try:
            nowTime = int(time.time())
            feed_back_qs = FeedBackModel.objects.filter(id=feedBackID)
            if not feed_back_qs.exists():
                return response.json(173)
            with transaction.atomic():
                SysMsgModel.objects.create(userID_id=feed_back_qs.first().userID_id, msg=msg, uid=uid,
                                           addTime=nowTime, updTime=nowTime)   # 创建系统消息
                feed_back_qs.update(status=1)   # 更新状态为已回复
            return response.json(0)
        except Exception as e:
            print(e)
            return response.json(500, repr(e))

    def sendSysMsgToUser(self, request_dict, response):
        userID = request_dict.get('userID', None)
        msg = request_dict.get('msg', None)

        if not all([userID, msg]):
            return response.json(444)

        try:
            nowTime = int(time.time())
            SysMsgModel.objects.create(userID_id=userID, msg=msg, addTime=nowTime, updTime=nowTime)
            return response.json(0)
        except Exception as e:
            print(e)
            return response.json(500, repr(e))

    def deleteFeedBack(self, request_dict, response):
        feedBackID = request_dict.get('feedBackID', None)
        if not feedBackID:
            return response.json(444)
        try:
            feed_back = FeedBackModel.objects.get(id=feedBackID)
            sr_id_list = feed_back.FS.values_list('id', flat=True)
            StatResModel.objects.filter(id__in=sr_id_list).delete()
            feed_back.delete()
            return response.json(0)
        except Exception as e:
            print(e)
            return response.json(500, repr(e))

    def getSysMessageList(self, request_dict, response):
        print('request_dict: ', request_dict)
        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:
            sys_mass_qs = SysMassModel.objects.filter()
            total = sys_mass_qs.count()
            sys_mass_qs = sys_mass_qs.values('id', 'sender__username', 'addTime', 'updTime', 'lang', 'recever', 'msg',
                                             'platform')
            sys_mass_qs = sys_mass_qs[(page - 1) * line:page * line]
            return response.json(0, {'list': list(sys_mass_qs), 'total': total})
        except Exception as e:
            print(e)
            return response.json(500, repr(e))

    def getAppDataList(self, request_dict, response):
        print('request_dict: ', request_dict)
        platform = request_dict.get('platform', None)

        if platform == 'ios':
            app_type = [1]
        elif platform == 'android':
            app_type = [2]
        else:
            app_type = [1, 2]

        try:
            app_info_qs = App_Info.objects.filter(app_type__in=app_type).values('appBundleId', 'appName').distinct()
            appBundleId_list = []
            for app_info in app_info_qs:
                appBundleId_list.append(app_info['appBundleId'])
            return response.json(0, {'appBundleId_list': appBundleId_list})
        except Exception as e:
            print(e)
            return response.json(500, repr(e))

    def sendSysMessage(self, request_dict, response):
        print('request_dict: ', request_dict)
        lang = request_dict.get('lang', None)
        platform = request_dict.get('platform', None)
        recever = request_dict.get('app_list', None)
        msg = request_dict.get('msg', None)

        if not all([lang, platform, recever, msg]):
            return response.json(444)

        try:
            with transaction.atomic():
                # SysMassModel表创建群发消息记录数据
                nowTime = int(time.time())
                sender_id = Device_User.objects.filter(username='13800138001').values('userID').first()['userID']
                SysMassModel.objects.create(
                    sender_id=sender_id,
                    lang=lang,
                    platform=platform,
                    recever=recever,
                    msg=msg,
                    addTime=nowTime,
                    updTime=nowTime,
                )
                # 根据UserExModel表的userID群发消息给用户
                region_list = lang.split(',')
                appBundleId_list = recever.split(',')
                userID_list = UserExModel.objects.filter(appBundleId__in=appBundleId_list, region__in=region_list)\
                    .values_list('userID_id', flat=True)
                sys_msg_list = []
                for userID in userID_list:
                    sys_msg_list.append(SysMsgModel(userID_id=userID, msg=msg, addTime=nowTime, updTime=nowTime))
                    if len(sys_msg_list) > 5000:
                        SysMsgModel.objects.bulk_create(sys_msg_list)
                        sys_msg_list = []
                SysMsgModel.objects.bulk_create(sys_msg_list)
            return response.json(0)
        except Exception as e:
            print(e)
            return response.json(500, repr(e))

