from hub import methods, Global

import os

# save_dir = r'C:\logs'  # sri内网测试环境


async def code3001(**sources):
    """
    查询驾驶人员操作记录列表
    """
    # --- check ---
    if not sources.get('page'):
        return dict(code=1, details=f"something is wrong.")
    elif not sources.get('size'):
        return dict(code=2, details=f"something is wrong.")

    # --- get log_file_uuid_list ---
    log_file_list = methods.get_file_path_list(Global.save_dir)
    log_file_name_list = [i.split('\\')[-1] for i in log_file_list]
    log_file_uuid_list = [i.split('.')[0] for i in log_file_name_list]
    methods.debug_log('code3000.22:', f"#log_file_uuid_list: {log_file_uuid_list}")

    # --- fill d2 ---
    d2 = dict()
    """
    VehicleInfo: 车辆信息表
    VehicleInfo.pid: 车牌号
    VehicleInfo.type: 车型号
    VehicleInfo.host_address: 工控机地址
    VehicleInfo.rtk_address: rtk地址
    VehicleInfo.cpe_address: cpe地址
    VehicleInfo.release_at: 出厂时期
    VehicleInfo.state: 当前状态 (1:离线 2:在线空闲 3: 现场驾驶中 4: 远程驾驶中)
    VehicleInfo.permit_state: 遥操状态 (0:允许 1:禁用)
    VehicleInfo.update_at: 更新时间
    """
    for item in Global.mdb.get_all('VehicleInfo'):
        ipv4 = int(f"{item.get('host_address').replace('.', '')}")
        d2[ipv4] = item.get('pid')

    cockpit_name_dict = {
        '': '1号舱',
        '': '2号舱',
    }

    # --- fill d1 ---
    """
    UserWorkRecordList: 用户操作记录
    UserWorkRecordList.uuid: 记录标识
    UserWorkRecordList.user_uuid: 用户标识
    UserWorkRecordList.start_at: 操作开始时间
    UserWorkRecordList.end_at: 操作结束时间
    UserWorkRecordList.cockpit_id: 舱端id
    UserWorkRecordList.vehicle_id: 车端id
    """
    d1 = list()
    page = sources.get('page', 1)
    size = sources.get('size', 10)
    for item in Global.mdb.get_all('UserWorkRecordList', sort_field=[('start_at', -1)]):
        # --- check ---
        uuid = str(item.get('_id'))
        if uuid not in log_file_uuid_list:
            continue

        # --- update ---
        item['uuid'] = uuid
        item['start_time_at'] = item.get('start_at')
        item['end_time_at'] = item.get('end_at')

        # --- update driver_name ---
        item['driver_name'] = item.get('user_uuid')
        if len('67174cf9cd36d7a6def99cae') == len(item.get('user_uuid')):
            item['driver_name'] = Global.mdb.get_one_by_id('UserInfo', item.get('user_uuid')).get('name')

        # --- update pid ---
        item['pid'] = item.get('vehicle_id')
        if int(item.get('vehicle_id')) in d2:
            item['pid'] = d2.get(int(item.get('vehicle_id')))

        # --- update cockpit_name ---
        item['cockpit_name'] = item.get('cockpit_id')

        # --- update --
        del item['_id']
        del item['user_uuid']
        del item['start_at']
        del item['end_at']
        del item['cockpit_id']
        del item['vehicle_id']
        d1.append(item)

    return dict(code=0, data=d1[(page - 1) * size: page * size], total=len(d1), page=page, size=size)


async def code3002(**sources):
    """
    下载指定驾驶人员操作日志
    """
    # --- check ---
    if not sources.get('uuid'):
        return dict(code=1, details=f"not found uuid.[url中缺少uuid参数]")
    
    # --- get file_path ---
    # log_uuid = '671754598302fc6fd344819f'
    log_uuid = sources.get('uuid')
    file_path = os.path.join(Global.save_dir, f"{log_uuid}.log")

    # --- get file_name ---
    methods.debug_log('code3000.code3002|145:', f"#log_uuid: {log_uuid}")
    item = Global.mdb.get_one_by_id('UserWorkRecordList', log_uuid)
    start_at = methods.ts_to_string(item.get('start_at'), '%Y%m%d%H%M%S')
    end_at = methods.ts_to_string(item.get('end_at'), '%Y%m%d%H%M%S')
    file_name = f"{start_at}-{end_at}.log"
    return {'code': 0, 'file_path': file_path, 'file_name': file_name}