// DataSyncTask.java - 数据同步任务
package cn.iocoder.yudao.module.mes.controller.admin.taskmanagement.scheduled.coretask;

import cn.iocoder.yudao.module.iot.controller.admin.device.enums.TaskTypeEnum;
import cn.iocoder.yudao.module.iot.controller.admin.device.scheduled.core.Task;
import cn.iocoder.yudao.module.mes.dal.dataobject.deviceledger.DeviceLedgerDO;
import cn.iocoder.yudao.module.mes.dal.dataobject.dvsubject.DvSubjectDO;
import cn.iocoder.yudao.module.mes.dal.dataobject.subjectplan.SubjectPlanDO;
import cn.iocoder.yudao.module.mes.dal.dataobject.taskmanagement.TaskManagementDO;
import cn.iocoder.yudao.module.mes.dal.dataobject.ticketmanagement.TicketManagementDO;
import cn.iocoder.yudao.module.mes.dal.dataobject.ticketresults.TicketResultsDO;
import cn.iocoder.yudao.module.mes.dal.mysql.deviceledger.DeviceLedgerMapper;
import cn.iocoder.yudao.module.mes.dal.mysql.dvsubject.DvSubjectMapper;
import cn.iocoder.yudao.module.mes.dal.mysql.subjectplan.SubjectPlanMapper;
import cn.iocoder.yudao.module.mes.dal.mysql.taskmanagement.TaskManagementMapper;
import cn.iocoder.yudao.module.mes.dal.mysql.ticketmanagement.TicketManagementMapper;
import cn.iocoder.yudao.module.mes.dal.mysql.ticketresults.TicketResultsMapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Random;
import java.util.stream.Collectors;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;

@Component
public class GenerateWorkOrderTask implements Task {
    private static final Logger logger = LoggerFactory.getLogger(GenerateWorkOrderTask.class);

    @Resource
    private TaskManagementMapper taskManagementMapper;

    @Resource
    private DeviceLedgerMapper deviceLedgerMapper;

    @Resource
    private TicketManagementMapper ticketManagementMapper;

    @Resource
    private SubjectPlanMapper subjectPlanMapper;

    @Resource
    private DvSubjectMapper dvSubjectMapper;

    @Resource
    private TicketResultsMapper ticketResultsMapper;


    @Override
    public String getTaskType() {
        return TaskTypeEnum.WORK_ORDER.getCode();
    }

    @Override
    public void execute(Long taskId, String taskParam) {
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String currentTime = sdf.format(new Date());

            logger.info("执行数据同步任务，任务ID: {}, 参数: {}, 时间: {}",
                    taskId, taskParam, currentTime);

            // 解析同步参数
            // 格式示例: "source:target" 或 "table:condition"
            generateWorkOrder(taskId);

        } catch (Exception e) {
            logger.error("执行数据同步任务异常，任务ID: {}", taskId, e);
        }
    }

    private void generateWorkOrder(Long taskId) {

        logger.info("开始同步数据，id: {}", taskId);
        Long id = taskId -2000000L;
        logger.info("处理后id：{} ", id );

        //检验数据是否存在
        taskManagementMapper.selectById(id);
        TaskManagementDO taskManagementDO = taskManagementMapper.selectById(id);
        if (taskManagementDO == null){
                return;
        }

        // 将逗号分隔的字符串转换为Long类型的List
        List<Long> idList = Arrays.stream(taskManagementDO.getDeviceList().split(","))
                .map(String::trim) // 去除可能存在的空格
                .map(Long::valueOf)
                .collect(Collectors.toList());

        for (Long deviceId : idList) {
            TicketManagementDO ticketManagementDO = new TicketManagementDO();
            DeviceLedgerDO deviceLedgerDO = deviceLedgerMapper.selectById(deviceId);
            ticketManagementDO.setTaskId(taskManagementDO.getId());
            ticketManagementDO.setPlanNo(generatePrefixedOrderNo());
            ticketManagementDO.setPlanId(taskManagementDO.getProjectForm());
            ticketManagementDO.setDeviceName(deviceLedgerDO.getDeviceName());
            ticketManagementDO.setPlanType(taskManagementDO.getTaskType());
            ticketManagementDO.setConfigName(taskManagementDO.getName());
            ticketManagementDO.setTaskEndTime(taskManagementDO.getEndDate().atStartOfDay());
            // TODO 默认为内置管理员Id
            ticketManagementDO.setCreator("1");
            ticketManagementDO.setUpdater("1");
            ticketManagementMapper.insert(ticketManagementDO);

            List<SubjectPlanDO> subjectPlanDOList = subjectPlanMapper.selectList(Wrappers.<SubjectPlanDO>lambdaQuery().eq(SubjectPlanDO::getPlanId, ticketManagementDO.getPlanId()));
            for (SubjectPlanDO subjectPlanDO : subjectPlanDOList) {
                DvSubjectDO dvSubjectDO = dvSubjectMapper.selectById(subjectPlanDO.getSubjectId());

                TicketResultsDO ticketResultsDO = new TicketResultsDO();
                ticketResultsDO.setInspectionItemName(dvSubjectDO.getSubjectName());
                ticketResultsDO.setInspectionMethod(dvSubjectDO.getInspectionMethod());
                ticketResultsDO.setJudgmentCriteria(dvSubjectDO.getJudgmentCriteria());
                ticketResultsDO.setManagementId(ticketManagementDO.getId());
                ticketResultsDO.setDeviceId(deviceId);
                // TODO 默认为内置管理员Id
                ticketResultsDO.setCreator("1");
                ticketResultsDO.setUpdater("1");
                ticketResultsMapper.insert(ticketResultsDO);
            }

        }
    }

    /**
     * 带前缀的时间戳单号
     */
    public static String generatePrefixedOrderNo() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        String date = sdf.format(new Date());
        String randomNum = String.format("%06d", new Random().nextInt(1000000));
        return "E" + date + randomNum;
    }

}