package org.jeecg.module.custom.ocr.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.jeecg.module.custom.ocr.api.entity.FormRecord;
import org.jeecg.module.custom.ocr.api.thread.TaskQueue;
import org.jeecg.module.custom.ocr.controller.dto.AddTaskRequest;
import org.jeecg.module.custom.ocr.controller.dto.TaskDTO;
import org.jeecg.module.custom.ocr.dataDao.TaskMapper;
import org.jeecg.module.custom.ocr.dataobject.Task;
import org.jeecg.module.custom.ocr.service.TaskService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service("taskServiceImpl")
public class TaskServiceImpl implements TaskService {

    @Autowired
    private TaskMapper taskMapper;

    @Transactional
    @Override
    public void save(AddTaskRequest request) {
        // 处理所有 records 的字段模糊映射
        if (request.getData() != null && request.getData().getRecords() != null) {
            for (TaskDTO taskDTO : request.getData().getRecords()) {
                mapSimilarFields(taskDTO, taskDTO.getDynamicFields());
            }
        }
        Task task = toTask(request);
        FormRecord formRecord = toFormRecord(request);
        // 任务落库
        task.setId(null);
        taskMapper.save(task);

        formRecord.setTaskId(task.getId());
        // 图片任务 将图片下载并更新imgHash到ocr_picture库中
        TaskQueue.pictureImgToLocalPushData(formRecord);
    }

    @Transactional
    @Override
    public void deleteTask(Long taskNo) {
        taskMapper.deleteByTaskNo(taskNo);
    }

    @Override
    public Task getById(Long id) {
        return this.taskMapper.selectById(String.valueOf(id));
    }

    @Transactional
    @Override
    public void updateById(Task task) {
        this.taskMapper.updateById(task);
    }

    @Override
    public void deleteTasks(List<Long> taskNos) {
//        taskMapper.deleteByTaskNos(taskNos);
    }

    private Task toTask(AddTaskRequest request) {
        Task task = new Task();

        // 设置 AddTaskRequest 中的顶级字段
        task.setTenantCode(request.getTenantCode());
        task.setAccessKey(request.getAccessKey());
        task.setTimestamp(request.getTimestamp());
        task.setSignature(request.getSignature());

        // 处理 AddTaskData 中的 records 列表
        if (request.getData() != null && request.getData().getRecords() != null && !request.getData().getRecords().isEmpty()) {
            // 取第一条 TaskDTO 记录（如果需要处理多条记录，可改为循环）
            TaskDTO taskDTO = request.getData().getRecords().get(0);

            // 映射 TaskDTO 到 Task
            task.setTenantNo(taskDTO.getTenantNo());
            task.setTaskNo(taskDTO.getTaskNo());
            task.setAccountNo(taskDTO.getAccountNo());
            task.setAccountName(taskDTO.getAccountName());
            task.setProjectNo(taskDTO.getProjectNo());
            task.setProjectName(taskDTO.getProjectName());
            task.setTaskFormNo(taskDTO.getTaskFormNo());
            task.setPlanNo(taskDTO.getPlanNo());
            task.setPlanName(taskDTO.getPlanName());
            task.setPlanChildNo(taskDTO.getPlanChildNo());
            task.setPlanChildName(taskDTO.getPlanChildName());
            task.setTaskId(taskDTO.getTaskId());
            task.setTaskName(taskDTO.getTaskName());
            task.setUserNo(taskDTO.getUserNo());
            task.setUserName(taskDTO.getUserName());
            task.setSubmitTime(taskDTO.getSubmitTime());
            task.setLocalImageUrl(taskDTO.getLocalImageUrl());
            task.setImgHash(taskDTO.getImgHash());
            task.setImageUrl(taskDTO.getImageUrl());
            task.setImageNo(taskDTO.getImageNo());

            // 将 Map<String, Object> 转换为 JSON 字符串
            try {
                ObjectMapper objectMapper = new ObjectMapper();
                String dynamicFieldsJson = objectMapper.writeValueAsString(taskDTO.getDynamicFields());
                task.setDynamicFields(dynamicFieldsJson);
            } catch (Exception e) {
                // 处理序列化异常，可根据业务需求抛出或记录日志
                throw new RuntimeException("Failed to serialize dynamicFields", e);
            }
        }

        return task;
    }

    private FormRecord toFormRecord(AddTaskRequest request) {
        FormRecord formRecord = new FormRecord();

        // 处理 AddTaskData 中的 records 列表
        if (request.getData() != null && request.getData().getRecords() != null && !request.getData().getRecords().isEmpty()) {
            // 取第一条 TaskDTO 记录
            TaskDTO taskDTO = request.getData().getRecords().get(0);

            // 映射 TaskDTO 到 FormRecord
            formRecord.setTenantNo(taskDTO.getTenantNo());
            formRecord.setTenantName(request.getTenantCode()); // 假设 tenantName 使用 tenantCode，需确认
            formRecord.setAccountNo(taskDTO.getAccountNo());
            formRecord.setAccountName(taskDTO.getAccountName());
            formRecord.setProjectNo(taskDTO.getProjectNo());
            formRecord.setProjectName(taskDTO.getProjectName());
            formRecord.setTaskFormNo(taskDTO.getTaskFormNo());
            formRecord.setPlanNo(taskDTO.getPlanNo());
            formRecord.setPlanName(taskDTO.getPlanName());
            formRecord.setPlanChildNo(taskDTO.getPlanChildNo());
            formRecord.setPlanChildName(taskDTO.getPlanChildName());
            formRecord.setTaskId(taskDTO.getTaskId());
            formRecord.setTaskName(taskDTO.getTaskName());
            formRecord.setUserNo(taskDTO.getUserNo());
            formRecord.setUserName(taskDTO.getUserName());
            formRecord.setSubmitTime(taskDTO.getSubmitTime());
            formRecord.setLocalImageUrl(taskDTO.getLocalImageUrl());
            formRecord.setImgHash(taskDTO.getImgHash());
            formRecord.setImageUrl(taskDTO.getImageUrl());
            formRecord.setImageNo(taskDTO.getImageNo());
            formRecord.setDynamicFields(taskDTO.getDynamicFields());
        }

        return formRecord;
    }

    /**
     * 通用字段模糊映射，将dynamicFields中的如LivePhoto1等自动赋值到TaskDTO同名字段（忽略大小写和数字后缀），支持LivePhoto类型自动转换
     */
    private void mapSimilarFields(Object target, java.util.Map<String, Object> dynamicFields) {
        if (dynamicFields == null || dynamicFields.isEmpty()) return;
        java.lang.reflect.Field[] fields = target.getClass().getDeclaredFields();
        for (java.lang.reflect.Field field : fields) {
            String fieldName = field.getName();
            for (String key : dynamicFields.keySet()) {
                // 忽略大小写和数字后缀
                String keyBase = key.replaceAll("\\d+$", "").toLowerCase();
                if (keyBase.equals(fieldName.toLowerCase())) {
                    field.setAccessible(true);
                    Object value = dynamicFields.get(key);
                    try {
                        // LivePhoto类型自动转换
                        if (field.getType().getName().endsWith("LivePhoto")) {
                            if (value instanceof java.util.Map) {
                                com.fasterxml.jackson.databind.ObjectMapper mapper = new com.fasterxml.jackson.databind.ObjectMapper();
                                Object livePhotoObj = mapper.convertValue(value, field.getType());
                                field.set(target, livePhotoObj);
                            } else if (value instanceof java.util.List && !((java.util.List<?>) value).isEmpty()) {
                                com.fasterxml.jackson.databind.ObjectMapper mapper = new com.fasterxml.jackson.databind.ObjectMapper();
                                Object livePhotoObj = mapper.convertValue(((java.util.List<?>) value).get(0), field.getType());
                                field.set(target, livePhotoObj);
                            }
                        } else {
                            field.set(target, value);
                        }
                    } catch (Exception e) {
                        // 可加日志
                    }
                    break;
                }
            }
        }
    }
}
