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

import org.jeecg.module.custom.ocr.controller.dto.DuplicateTaskData;
import org.jeecg.module.custom.ocr.controller.dto.DuplicateTaskRequest;
import org.jeecg.module.custom.ocr.dataDao.DuplicateTaskMapper;
import org.jeecg.module.custom.ocr.dataobject.DuplicateTask;
import org.jeecg.module.custom.ocr.service.DuplicateTaskService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class DuplicateTaskServiceImpl implements DuplicateTaskService {

    @Autowired
    private DuplicateTaskMapper duplicateTaskMapper;

    @Override
    public void save(DuplicateTaskRequest request) {
        DuplicateTask task = toDuplicateTask(request);
        duplicateTaskMapper.save(task);
    }

    @Override
    public void updateCompletedById(Long id) {
        duplicateTaskMapper.updateCompletedById(id, 1L);
    }

    @Override
    public List<DuplicateTask> getAllUnCompletedTask() {
        return duplicateTaskMapper.getAllUnCompletedTask();
    }

    private DuplicateTask toDuplicateTask(DuplicateTaskRequest request) {
        DuplicateTask task = new DuplicateTask();

        // 映射顶级字段
        task.setTenantCode(request.getTenantCode());
        task.setAccessKey(request.getAccessKey());
        task.setTimestamp(request.getTimestamp());
        task.setSignature(request.getSignature());

        // 映射 DuplicateTaskData 中的字段
        if (request.getData() != null) {
            DuplicateTaskData data = request.getData();
            task.setAccountNo(data.getAccountNo());
            task.setTenantNo(data.getTenantNo());
            task.setRequestId(data.getRequestId());
            task.setQueryConfig(data.getQueryConfig());

            // 将 List<Long> taskNos 转换为逗号分隔的字符串
            if (data.getTaskNos() != null && !data.getTaskNos().isEmpty()) {
                String taskNosString = data.getTaskNos().stream()
                        .map(String::valueOf)
                        .collect(Collectors.joining(","));
                task.setTaskNos(taskNosString);
            }
        }

        // 设置默认值
        task.setMaxSimilarityScore(null); // 未提供，设为 null
        task.setCompleted(false); // 默认未完成

        return task;
    }
}
