import json
import threading
import datetime
import time

from bson import utc

from Model.models import EquipmentLogModel
from Service.CommonService import CommonService
from Service.MiscellService import MiscellService
from Service.TemplateService import TemplateService


def add_access_log(request, status_code):
    # 增加多进程 异步
    asy = threading.Thread(target=addLog, args=(request, status_code))
    asy.start()


def addLog(request, status_code):
    request_path = request.path.strip().strip('/')
    if 'equipment' in request.path:
        global request_dict
        try:
            if request.method == 'GET':
                request_dict = request.GET
            elif request.method == 'POST':
                request_dict = request.POST
            # api_list = TemplateService.log_api()
            print('status_code:', status_code)
            api_list = [
                'equipment/add',
                'equipment/delete',
                'equipment/flowUpdate',
                'v3/equipment/add',
                'v3/equipment/modify',
            ]
            # 接口中文化
            jiekou = {
                'equipment/add': 'v1添加设备',
                'equipment/delete': 'v1删除设备',
                'equipment/flowUpdate': '更新设备的版本信息',
                'v3/equipment/add': 'v3添加设备信息',
                'v3/equipment/modify': 'v3编辑设备信息'
            }
            if request_path in api_list:
                user = MiscellService.get_access_name(request_dict=request_dict)
                clientIP = CommonService.get_ip_address(request)
                # now_time = datetime.datetime.utcnow().replace(tzinfo=utc).astimezone(utc)
                nowtime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
                beijing = datetime.timezone(datetime.timedelta(hours=8))
                utc = datetime.timezone.utc  # 获取 UTC 的时区对象
                beijing_time = datetime.datetime.utcnow().replace(tzinfo=utc).astimezone(beijing)  # 强制转换加上 UTC 时区。此处敲黑板，需要特别注意。
                # content:从前端获取到的参数数据,对获取到的数据进行处理
                content = json.dumps(request_dict)
                d = eval(content)
                if 'uid' not in d:
                    d['uid'] = ''
                if 'NickName' not in d:
                    d['NickName'] = ''
                if 'equipmentid' not in d:
                    d['equipmentid'] = ''
                if 'UID' in d:
                    d['uid'] = d['UID']
                if 'id' in d:
                    d['equipmentid'] = d['id']
                password = request_dict.get('userPwd', None)
                if password is not None:
                    request_dict = dict(request_dict)
                    request_dict.pop('userPwd')
                if user != '':
                    user = user
                else:
                    print('空')
                    user = '空'
                # 数据拼接
                caozuo = '用户账号为：[' + user + ']' + '在' + str(beijing_time) + '进行' + str(jiekou[request_path])
                # + ',' + '设备uid或主键id为：' + str(d['uid']) + str(d['equipmentid'])
                print('request_dict:', d)
                add_data = {
                    'user': user,
                    'uid': d['uid'],
                    'equipmentid': d['equipmentid'],
                    'NickName': d['NickName'],
                    'ip': clientIP,
                    'time': beijing_time,
                    'url': request.path,
                    'operatingcontent': caozuo,
                }
                print('操作数据：', add_data)
                # 设备日志添加
                EquipmentLogModel.objects.create(**add_data)
        except Exception as e:
            print(repr(e))
            pass
