import os
import traceback

import boto3
import botocore
from botocore import client
import simplejson as json
from django.http import HttpResponse
from django.utils.decorators import method_decorator
from django.views.decorators.csrf import csrf_exempt
from django.views.generic import TemplateView, View

from Ansjer.cn_config.config_test import REGION_NAME2
from Ansjer.config import BASE_DIR, ACCESS_KEY_ID, SECRET_ACCESS_KEY, REGION_NAME, AVATAR_BUCKET, CONFIG_INFO, \
    CONFIG_CN, CONFIG_TEST, LOGGER
from Ansjer.config import SERVER_DOMAIN
from Model.models import Role, Device_User, UserOauth2Model, UserExModel, CountryLanguageModel, LanguageModel, App_Info, \
    IcloudUseDetails
from Object.ContentSecurityObject import ContentSecurity
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


class showUserMoreView(TemplateView):
    @method_decorator(csrf_exempt)
    def dispatch(self, *args, **kwargs):
        return super(showUserMoreView, self).dispatch(*args, **kwargs)

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

    def get(self, request, *args, **kwargs):
        request.encoding = 'gb2312'
        return self.validation(request.GET)

    def validation(self, request_dict):
        response = ResponseObject()
        token = request_dict.get('token', None)
        lang = request_dict.get('lang', 'en')
        app_bundle_id = request_dict.get('app_bundle_id', None)

        tko = TokenObject(token)
        response.lang = tko.lang
        if tko.code != 0:
            return response.json(tko.code)
        user_id = tko.userID
        if not user_id:
            return response.json(104)

        return self.show_user_more(user_id, lang, app_bundle_id, response)

    @staticmethod
    def show_user_more(user_id, lang, app_bundle_id, response):
        """
        获取用户完整信息
        @param user_id: 用户id
        @param lang: 语言
        @param app_bundle_id: app包id
        @param response: 响应
        @return: response
        """
        device_user_qs = Device_User.objects.filter(userID=user_id)
        if not device_user_qs.exists():
            return response.json(104)
        try:
            sqlDict = CommonService.qs_to_dict(device_user_qs)
            for k, v in enumerate(sqlDict["datas"]):
                sqlDict['datas'][k]['fields'].pop('password')
                userIconPath = sqlDict['datas'][k]['fields']['userIconPath']
                region_status = sqlDict['datas'][k]['fields']['region_status']
                if userIconPath:
                    if userIconPath.find('static/') != -1:
                        userIconPath = userIconPath.replace('static/', '').replace('\\', '/')
                        userIconUrl = SERVER_DOMAIN + 'account/getAvatar/' + userIconPath
                        sqlDict['datas'][k]['fields']['userIconUrl'] = userIconUrl

                # 判断用户是否开通云盘
                icloud_user_qs = IcloudUseDetails.objects.filter(user_id=user_id)
                v['fields']['is_cloudDrive'] = 1 if icloud_user_qs.exists() else 0
                # 确认地区字段
                sqlDict['datas'][k]['fields']['region_status'] = 1 if region_status else 0

                if len(v['fields']['role']):
                    roleName = ModelService.getRole(rid=v['fields']['role'][0])
                    sqlDict["datas"][k]['fields']['rolename'] = roleName

                # 根据region_country的值返回api和region数据
                sqlDict["datas"][k]['fields']['api'] = ''
                sqlDict['datas'][k]['fields']['region'] = ''
                region_country = sqlDict["datas"][k]['fields']['region_country']
                if region_country != 0:
                    # api数据
                    country_qs = CountryLanguageModel.objects.filter(country_id=region_country).values(
                        'country__region__api', 'country__region__zosi_api', 'country__region__loocam_api')
                    sqlDict["datas"][k]['fields']['api'] = country_qs[0]['country__region__api']
                    if region_country == 1:     # 中国返回美洲域名
                        sqlDict["datas"][k]['fields']['api'] = 'https://www.dvema.com/'
                    # 根据app_bundle_id返回对应域名
                    if app_bundle_id:
                        # 查询app名
                        app_inf_qs = App_Info.objects.filter(appBundleId=app_bundle_id).values('appName')
                        if app_inf_qs.exists():
                            app_name = app_inf_qs[0]['appName']
                            if 'Zosi' in app_name:
                                sqlDict['datas'][k]['fields']['api'] = country_qs[0]['country__region__zosi_api']
                                if region_country == 1:
                                    sqlDict['datas'][k]['fields']['api'] = 'https://api.zositech2.com/'
                            elif 'Loocam' in app_name:
                                sqlDict['datas'][k]['fields']['api'] = country_qs[0]['country__region__loocam_api']
                                if region_country == 1:
                                    sqlDict['datas'][k]['fields']['api'] = 'https://api.loocam2.com/'

                    # region数据
                    region_country = sqlDict['datas'][k]['fields']['region_country']
                    language_qs = LanguageModel.objects.filter(lang=lang).values('id')
                    region_qs = CountryLanguageModel.objects.filter(country_id=region_country,
                                                                    language_id=language_qs[0]['id']). \
                        values('country_name')
                    sqlDict['datas'][k]['fields']['region'] = region_qs[0]['country_name'] if region_qs.exists() else ''

            # 增加oauth2关联数据
            ua_qs = UserOauth2Model.objects.filter(userID_id=user_id).values_list('authType', flat=True)
            sqlDict['oauth2'] = list(ua_qs)
            return response.json(0, sqlDict)
        except Exception as e:
            return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))


class perfectUserInfoView(TemplateView):
    # 完善个人信息
    @method_decorator(csrf_exempt)
    def dispatch(self, *args, **kwargs):
        return super(perfectUserInfoView, self).dispatch(*args, **kwargs)

    def post(self, request, *args, **kwargs):
        request.encoding = 'utf-8'
        userContent = request.POST.get('content', None)
        userIcon = request.FILES.get('userIcon', None)
        token = request.POST.get('token', None)
        return self.ValidationError(token, userContent, userIcon)

    def get(self, request, *args, **kwargs):
        request.encoding = 'gb2312'
        userContent = request.GET.get('content', None)
        userIcon = request.FILES.get('userIcon', None)
        token = request.GET.get('token', None)
        return self.ValidationError(token, userContent, userIcon)

    def ValidationError(self, token, userContent, userIcon):
        response = ResponseObject()
        tko = TokenObject(token)
        response.lang = tko.lang
        if tko.code != 0:
            return response.json(tko.code)
        userID = tko.userID
        if not userID:
            return response.json(309)

        userIconPath = ''
        if userIcon:
            # 上传头像到aws s3
            aws_s3_client = boto3.client(
                's3',
                region_name=REGION_NAME,
                aws_access_key_id=ACCESS_KEY_ID,
                aws_secret_access_key=SECRET_ACCESS_KEY,
                config=botocore.client.Config(signature_version='s3v4'),
            )
            Key = userID + '/' + userIcon.name
            aws_s3_client.put_object(Bucket=AVATAR_BUCKET, Key=Key, Body=userIcon)
            userIconPath = userID + '/' + userIcon.name

            #  测试/国内服,验证头像是否合规
            if CONFIG_INFO == CONFIG_CN or CONFIG_INFO == CONFIG_TEST:
                # 测试服头像地区为us-west-1
                if CONFIG_INFO == CONFIG_TEST:
                    aws_s3_client = boto3.client(
                        's3',
                        region_name=REGION_NAME2,
                        aws_access_key_id=ACCESS_KEY_ID,
                        aws_secret_access_key=SECRET_ACCESS_KEY,
                        config=botocore.client.Config(signature_version='s3v4'),
                    )

                params = {'Bucket': AVATAR_BUCKET, 'Key': Key}
                image_url = aws_s3_client.generate_presigned_url('get_object', Params=params)
                service = 'profilePhotoCheck'
                LOGGER.info('头像链接:{}'.format(image_url))
                service_dict = {'imageUrl': image_url}
                service_parameters = json.dumps(service_dict)
                legal = ContentSecurity().image_review(service, service_parameters)
                if not legal:
                    return response.json(106)

        if userContent:
            dataValid = json.loads(userContent)
            if 'userID' and 'password' and 'is_superuser' in dataValid.keys():
                return response.json(444)

        if not userIconPath and not userContent:
            return response.json(444)
        elif not userIconPath and userContent:
            return self.perfectUserInfoUpdate(userID, response, userContent=userContent)
        elif userIconPath and not userContent:
            return self.perfectUserInfoUpdate(userID, response, userIconPath=userIconPath)
        else:
            return self.perfectUserInfoUpdate(userID, response, userIconPath=userIconPath, userContent=userContent)

    def perfectUserInfoUpdate(slef, userID, response, **kwargs):
        """
        :param username:
        :param userContent:
        :param args:
        :param kwargs:
        :return:
        """
        User = Device_User.objects.filter(userID=userID)
        if not User.exists():
            return response.json(104)
        userIconPath = kwargs.get('userIconPath', None)
        userContent = kwargs.get('userContent', None)
        userIconUrl = ""
        if userIconPath:
            userIconUrl = SERVER_DOMAIN + 'account/getAvatar/' + userIconPath
        if userContent:
            try:
                UserData = json.loads(userContent)
            except Exception as e:
                return response.json(444, repr(e))

            # 测试/国内服,验证昵称是否合规
            if CONFIG_INFO == CONFIG_CN or CONFIG_INFO == CONFIG_TEST:
                nickname = UserData.get('NickName')
                if nickname:
                    service = 'nickname_detection'
                    service_dict = {'content': nickname}
                    service_parameters = json.dumps(service_dict)
                    legal = ContentSecurity().text_review(service, service_parameters)
                    if not legal:
                        return response.json(108)

        try:
            if userIconPath and userContent:
                User.update(userIconPath=userIconPath, userIconUrl=userIconUrl, **UserData)
            elif not userIconPath and userContent:
                User.update(**UserData)
            elif userIconPath and not userContent:
                User.update(userIconPath=userIconPath, userIconUrl=userIconUrl)
        except Exception as e:
            return response.json(117, repr(e))
        else:
            res = CommonService.qs_to_dict(User)
            for k, v in enumerate(res["datas"]):
                res['datas'][k]['fields'].pop('password')
                userIconPath = res['datas'][k]['fields']['userIconPath']
                region_status = res['datas'][k]['fields']['region_status']
                if region_status is True:
                    res['datas'][k]['fields']['region_status'] = 1
                else:
                    res['datas'][k]['fields']['region_status'] = 0
                if userIconPath and userIconUrl != '':
                    res['datas'][k]['fields']['userIconUrl'] = userIconUrl
            return response.json(0, res)


class getAvatarView(TemplateView):
    @method_decorator(csrf_exempt)
    def dispatch(self, *args, **kwargs):
        return super(getAvatarView, self).dispatch(*args, **kwargs)

    def post(self, request, *args, **kwargs):
        request.encoding = 'utf-8'
        filePath = kwargs.get('filePath', '')
        filePath.encode(encoding='utf-8', errors='strict')
        return self.getAvatar(filePath)

    def get(self, request, *args, **kwargs):
        request.encoding = 'utf-8'
        filePath = kwargs.get('filePath', '')
        filePath.encode(encoding='utf-8', errors='strict')
        return self.getAvatar(filePath)

    def getAvatar(self, filePath):
        response = ResponseObject()
        if not filePath:
            return response.json(800)
        if filePath == 'User/default.png' or filePath == 'User/defaultUser.png':
            # 使用默认头像
            try:
                aws_s3_client = boto3.client(
                    's3',
                    region_name=REGION_NAME,
                    aws_access_key_id=ACCESS_KEY_ID,
                    aws_secret_access_key=SECRET_ACCESS_KEY,
                    config=botocore.client.Config(signature_version='s3v4'),
                )
                get_object_response = aws_s3_client.get_object(Bucket=AVATAR_BUCKET, Key='default/default.png')
                return HttpResponse(get_object_response['Body'], content_type="image/jpeg")
            except Exception as e:
                print(e)
                return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))

        fullPath = os.path.join(BASE_DIR, "static", filePath).replace('\\', '/')
        if os.path.isfile(fullPath):
            try:
                imageData = open(fullPath, 'rb').read()
                return HttpResponse(imageData, content_type="image/jpeg")
            except Exception as e:
                return response.json(906, repr(e))
        else:
            try:
                aws_s3_client = boto3.client(
                    's3',
                    region_name=REGION_NAME,
                    aws_access_key_id=ACCESS_KEY_ID,
                    aws_secret_access_key=SECRET_ACCESS_KEY,
                    config=botocore.client.Config(signature_version='s3v4'),
                )
                get_object_response = aws_s3_client.get_object(Bucket=AVATAR_BUCKET, Key=filePath)
                return HttpResponse(get_object_response['Body'], content_type="image/jpeg")
            except Exception as e:
                return response.json(906, repr(e))


@csrf_exempt
def delUserInterface(request):
    response = ResponseObject()
    if request.method == 'POST':
        request_dict = request.POST
    elif request.method == 'GET':
        request_dict = request.GET
    else:
        return response.json(404)
    token = request_dict.get('token', None)
    delUserID = request_dict.get('delUserID', None)
    if not token or not delUserID:
        return response.json(444, 'token,delUserID')
    tko = TokenObject(token)
    response.lang = tko.lang
    if tko.code != 0:
        return response.json(tko.code)
    userID = tko.userID
    if not userID:
        return response.json(309)
    userValid = Device_User.objects.filter(userID=userID)
    if not userValid.exists():
        return response.json(104)
    own_perm = ModelService.check_perm(userID=userID, permID=10)
    if own_perm is not True:
        return response.json(404)
    delUser = Device_User.objects.filter(userID=delUserID)
    if not delUser.exists():
        return response.json(104)
    delUser.delete()
    return response.json(0)


@csrf_exempt
def showAllUserInterface(request):
    response = ResponseObject()
    if request.method == 'POST':
        request_dict = request.POST
    elif request.method == 'GET':
        request_dict = request.GET
    else:
        return response.json(404)
    token = request_dict.get('token', None)
    type = request_dict.get('type', None)
    tko = TokenObject(token)
    response.lang = tko.lang
    if tko.code != 0:
        return response.json(tko.code)
    userID = tko.userID
    if not userID:
        return response.json(104)
    if type == 'PC':
        line = int(request.POST.get('line', None))
        page = int(request.POST.get('page', None))
        userValid = Device_User.objects.filter(userID=userID).order_by('-data_joined')
        if not userValid:
            return response.json(104)
        # 管理员查询
        own_permission = ModelService.check_perm(userID=userID, permID=30)
        if own_permission is not True:
            return response.json(404)
        device_user_queryset = Device_User.objects.all()
        device_user_count = device_user_queryset.count()
        device_user_res = device_user_queryset.order_by('-data_joined')[(page - 1) * line:page * line]
        sqlDict = CommonService.qs_to_dict(device_user_res)
        redisObj = RedisObject(db=3)
        for k, v in enumerate(sqlDict["datas"]):
            if len(v['fields']['role']) > 0:
                role_query_set = Role.objects.get(rid=v['fields']['role'][0])
                sqlDict["datas"][k]['fields']['role'].append(role_query_set.roleName)
            if redisObj.get_data(key=v['pk']):
                sqlDict["datas"][k]['fields']['online'] = True
            else:
                sqlDict["datas"][k]['fields']['online'] = False

            ue = UserExModel.objects.filter(userID=sqlDict["datas"][k]['pk'])
            if ue.exists():
                sqlDict["datas"][k]['fields']['appBundleId'] = ue[0].appBundleId
            else:
                sqlDict["datas"][k]['fields']['appBundleId'] = ''
        sqlDict['count'] = device_user_count
        return response.json(0, sqlDict)
    else:
        own_permission = ModelService.check_perm(userID=userID, permID=30)
        if own_permission is not True:
            return response.json(404)
        qs = Device_User.objects.all().order_by('-data_joined')
        res = CommonService.qs_to_dict(qs)
        return response.json(0, res)


class setUserValidView(View):
    @method_decorator(csrf_exempt)
    def dispatch(self, *args, **kwargs):
        return super(setUserValidView, self).dispatch(*args, **kwargs)

    def post(self, request, *args, **kwargs):
        request.encoding = 'utf-8'
        request_dict = request.POST
        return self.setUserValid(request_dict)

    def get(self, request, *args, **kwargs):
        request.encoding = 'utf-8'
        request_dict = request.GET
        return self.setUserValid(request_dict)

    def setUserValid(self, request_dict):
        token = request_dict.get('token', None)
        eUserID = request_dict.get('userID', None)
        isValid = request_dict.get('isValid', None)
        rid = request_dict.get('rid', None)
        response = ResponseObject()
        tko = TokenObject(token)
        response.lang = tko.lang
        if tko.code != 0:
            return response.json(tko.code)
        superID = tko.userID
        own_perm = ModelService.check_perm(userID=superID, permID=50)
        if own_perm is True or superID != None and superID != eUserID:
            if rid == None:
                return self.UserValidUpdate(superID, eUserID, isValid, response)
            else:
                return self.UserValidUpdatePC(superID, eUserID, isValid, rid, response)
        else:
            return response.json(444, 'superID or userID')

    def UserValidUpdatePC(self, superID, eUserID, isValid, rid, response):
        super = Device_User.objects.filter(userID=superID)
        eUser = Device_User.objects.filter(userID=eUserID)
        if not super.exists() or not eUser.exists():
            return response.json(104)
        own_permission = ModelService.check_perm(userID=superID, permID=50)
        if own_permission is True:
            try:
                eUser.update(user_isValid=isValid)
                device_user_query_set = Device_User.objects.get(userID=eUserID)
                if device_user_query_set.role.all():
                    device_user_query_set.role.set([rid])
                else:
                    role_user_query_set = Role.objects.get(rid=rid)
                    device_user_query_set.role.add(role_user_query_set)
            except Exception as e:
                errorInfo = traceback.format_exc()
                print('更新数据库错误:%s' % errorInfo)
                return response.json(177, repr(e))
            else:
                return response.json(0)
        else:
            return response.json(404)

    def UserValidUpdate(self, superID, eUserID, isValid, response):
        super = Device_User.objects.filter(userID=superID)
        eUser = Device_User.objects.filter(userID=eUserID)
        if not super.exists():
            return response.json(104)
        if not eUser.exists():
            return response.json(104)
        if super[0].is_superuser != 100 or super[0].is_superuser == eUser[0].is_superuser:
            return response.json(404)
        try:
            eUser.update(user_isValid=isValid)
        except Exception as e:
            errorInfo = traceback.format_exc()
            print('更新数据库错误: %s' % errorInfo)
            return response.json(177, repr(e))
        return response.json(0)


@csrf_exempt
def success(request):
    return HttpResponse(status=200)
