#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import traceback

import simplejson as json
from django.core.files.storage import FileSystemStorage
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.config import BASE_DIR
from Ansjer.config import SERVER_DOMAIN
from Model.models import Role, Device_User, UserOauth2Model, UserExModel
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


# http://192.168.136.40:8077/account/showUserMore?token=test
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'
        token = request.POST.get('token', None)

        return self.ValidationError(token)

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

        return self.ValidationError(token)

    def ValidationError(self, token):
        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(104)
        return self.showUserMore(userID, response)

    def showUserMore(self, userID, response):
        User = Device_User.objects.filter(userID=userID)
        if not User.exists():
            return response.json(104)
        sqlDict = CommonService.qs_to_dict(User)
        for k, v in enumerate(sqlDict["datas"]):
            sqlDict['datas'][k]['fields'].pop('password')
            userIconPath = sqlDict['datas'][k]['fields']['userIconPath']
            if userIconPath:
                if userIconPath.find('static/') != -1:
                    userIconPath = userIconPath.replace('static/', '').replace('\\', '/')
                    userIconUrl = SERVER_DOMAIN + 'account/getAvatar/' + userIconPath
                    sqlDict['datas'][k]['fields']['userIconUrl'] = userIconUrl
            if len(v['fields']['role']):
                roleName = ModelService.getRole(rid=v['fields']['role'][0])
                sqlDict["datas"][k]['fields']['rolename'] = roleName
        # 增加oauth2关联数据
        ua_qs = UserOauth2Model.objects.filter(userID_id=userID).values_list('authType',flat=True)
        sqlDict["oauth2"] = list(ua_qs)
        return response.json(0, sqlDict)


# http://192.168.136.40:8077/account/perfectUserInfo?token=test&content={"NickName":"333"}
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)
        if userIcon != None:
            location = 'static/User/Images/' + userID + '/'
            fss = FileSystemStorage(location=location)
            if fss.exists(userIcon.name):
                fss.delete(userIcon.name)
            filename = fss.save(userIcon.name, userIcon)
            # userIconUrl = fss.url(filename)
            userIconPath = fss.path(filename).replace('\\', '/')
        else:
            userIconPath = None
        if userContent != None:
            dataValid = json.loads(userContent)
            if 'userID' and 'password' and 'is_superuser' in dataValid.keys():
                return response.json(444)
        if userIconPath == None and userContent == None:
            return response.json(444)
        elif userIconPath == None and userContent != None:
            return self.perfectUserInfoUpdate(userID, response, userContent=userContent)
        elif userIconPath != None and userContent == None:
            return self.perfectUserInfoUpdate(userID, response, userIconPath=userIconPath)
        else:
            return self.perfectUserInfoUpdate(userID, response, userIconPath=userIconPath,
                                              userContent=userContent)

    def perfectUserInfoUpdate(slef, userID, response, *args,
                              **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)
        if userIconPath is not None:
            userIconPath = userIconPath[userIconPath.find('static/'):]
            userIconUrl = SERVER_DOMAIN + 'account/getAvatar/' + userIconPath[7:]
        if userContent != None:
            try:
                UserData = json.loads(userContent)
            except Exception as e:
                return response.json(444, repr(e))
        try:
            if userIconPath is not None and userContent is not None:
                User.update(userIconPath=userIconPath, userIconUrl=userIconUrl, **UserData)
            elif userIconPath is None and userContent is not None:
                User.update(**UserData)
            elif userIconPath is not None and userContent is None:
                User.update(userIconPath=userIconPath, userIconUrl=userIconUrl)
        except Exception as e:
            errorInfo = traceback.format_exc()
            print('修改设备信息错误: %s ' % errorInfo)
            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']
                if userIconPath:
                    if userIconPath.find('static/') != -1:
                        userIconPath = userIconPath.replace('static/', '').replace('\\', '/')
                        userIconUrl = SERVER_DOMAIN + 'account/getAvatar/' + userIconPath
                        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 = 'gb2312'
        filePath = kwargs.get('filePath', '')
        filePath.encode(encoding='gb2312', errors='strict')
        return self.getAvatar(filePath)

    def getAvatar(self, filePath):
        response = ResponseObject()
        if filePath == '' or filePath == None:
            return response.json(800)
        fullPath = os.path.join(BASE_DIR, "static", filePath).replace('\\', '/')
        defaultPath = os.path.join(BASE_DIR, "static", "User/default.png").replace('\\', '/')
        if os.path.isfile(fullPath):
            try:
                Imagedata = open(fullPath, 'rb').read()
            except Exception as e:
                return response.json(906, repr(e))
            else:
                return HttpResponse(Imagedata, content_type="image/jpeg")
        else:
            print('----------------')
            print(defaultPath)
            print('----------------')
            try:
                Imagedata = open(defaultPath, 'rb').read()
            except Exception as e:
                return response.json(906, repr(e))
            else:
                return HttpResponse(Imagedata, content_type="image/jpeg")
            # return response.json(907)


@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)
