package cn.iocoder.yudao.module.mes.service.moldtaskmanagement;

import cn.iocoder.yudao.module.common.dal.dataobject.mold.MoldDO;
import cn.iocoder.yudao.module.common.dal.mysql.mold.MoldMapper;
import cn.iocoder.yudao.module.mes.dal.dataobject.moldsubject.MoldSubjectDO;
import cn.iocoder.yudao.module.mes.dal.dataobject.moldplanmaintenance.MoldPlanMaintenanceDO;
import cn.iocoder.yudao.module.mes.dal.dataobject.subjectmoldplan.SubjectMoldPlanDO;
import cn.iocoder.yudao.module.common.dal.dataobject.moldticketmanagement.MoldTicketManagementDO;
import cn.iocoder.yudao.module.common.dal.dataobject.moldticketresults.MoldTicketResultsDO;
import cn.iocoder.yudao.module.common.dal.dataobject.mold.MoldDO;
import cn.iocoder.yudao.module.mes.dal.mysql.moldsubject.MoldSubjectMapper;
import cn.iocoder.yudao.module.mes.dal.mysql.moldplanmaintenance.MoldPlanMaintenanceMapper;
import cn.iocoder.yudao.module.mes.dal.mysql.subjectmoldplan.SubjectMoldPlanMapper;
import cn.iocoder.yudao.module.common.dal.mysql.moldticketmanagement.MoldTicketManagementMapper;
import cn.iocoder.yudao.module.common.dal.mysql.moldticketresults.MoldTicketResultsMapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

import cn.iocoder.yudao.module.mes.controller.admin.moldtaskmanagement.vo.*;
import cn.iocoder.yudao.module.mes.dal.dataobject.moldtaskmanagement.MoldTaskManagementDO;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.pojo.PageParam;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;

import cn.iocoder.yudao.module.mes.dal.mysql.moldtaskmanagement.MoldTaskManagementMapper;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.mes.enums.ErrorCodeConstants.*;

import org.springframework.util.CollectionUtils;
import lombok.extern.slf4j.Slf4j;

/**
 * 设备类型 Service 实现类
 *
 * @author 内蒙必硕
 */
@Service
@Slf4j
@Validated
public class MoldTaskManagementServiceImpl implements MoldTaskManagementService {

    @Resource
    private MoldTaskManagementMapper moldtaskManagementMapper;

    @Resource
    private MoldTicketManagementMapper moldticketManagementMapper;

    @Resource
    private MoldTicketResultsMapper moldticketResultsMapper;

    @Resource
    private MoldMapper moldMapper;

    @Resource
    private MoldPlanMaintenanceMapper moldplanMaintenanceMapper;

    @Resource
    private SubjectMoldPlanMapper subjectmoldPlanMapper;


    @Resource
    private MoldSubjectMapper moldSubjectMapper;

    @Override
    public Long createMoldTaskManagement(MoldTaskManagementSaveReqVO createReqVO) {
        // 插入
        MoldTaskManagementDO moldtaskManagement = BeanUtils.toBean(createReqVO, MoldTaskManagementDO.class);
        moldtaskManagementMapper.insert(moldtaskManagement);
        // 返回
        return moldtaskManagement.getId();
    }

    @Override
    public void updateMoldTaskManagement(MoldTaskManagementSaveReqVO updateReqVO) {
        // 校验存在
        validateMoldTaskManagementExists(updateReqVO.getId());
        // 更新
        MoldTaskManagementDO updateObj = BeanUtils.toBean(updateReqVO, MoldTaskManagementDO.class);
        moldtaskManagementMapper.updateById(updateObj);
    }

    @Override
    public void deleteMoldTaskManagement(List<Long> idList ) {
        for (Long id : idList) {
            // 校验存在
            validateMoldTaskManagementExists(id);
        }
        // 删除
        moldtaskManagementMapper.deleteByIds(idList);
    }

    private void validateMoldTaskManagementExists(Long id) {
        if (moldtaskManagementMapper.selectById(id) == null) {
            throw exception(TASK_MANAGEMENT_NOT_EXISTS);
        }
    }

    @Override
    public MoldTaskManagementDO getMoldTaskManagement(Long id) {
        return moldtaskManagementMapper.selectById(id);
    }

//    @Override
//    public PageResult<MoldTaskManagementDO> getMoldTaskManagementPage(MoldTaskManagementPageReqVO pageReqVO) {
//
//        PageResult<MoldTaskManagementDO> moldtaskManagementDOPageResult = moldtaskManagementMapper.selectPage(pageReqVO);
//        for (MoldTaskManagementDO moldtaskManagementDO : moldtaskManagementDOPageResult.getList()) {
//            MoldPlanMaintenanceDO moldplanMaintenanceDO = moldplanMaintenanceMapper.selectById(moldtaskManagementDO.getProjectForm());
//            moldtaskManagementDO.setProjectFormName(moldplanMaintenanceDO.getPlanName());
//        }
//
//
//        return moldtaskManagementDOPageResult;
//    }
@Override
public PageResult<MoldTaskManagementDO> getMoldTaskManagementPage(MoldTaskManagementPageReqVO pageReqVO) {
    // 1. 查询分页数据
    PageResult<MoldTaskManagementDO> moldtaskManagementDOPageResult = moldtaskManagementMapper.selectPage(pageReqVO);

    // 2. 空列表直接返回，避免遍历空指针
    if (CollectionUtils.isEmpty(moldtaskManagementDOPageResult.getList())) {
        return moldtaskManagementDOPageResult;
    }

    // 3. 遍历处理每条数据，添加全量空值校验
    for (MoldTaskManagementDO moldtaskManagementDO : moldtaskManagementDOPageResult.getList()) {
        // 3.1 校验关联的维保计划ID（projectForm）非空
        Long projectFormId = moldtaskManagementDO.getProjectForm();
        if (projectFormId == null) {
            log.warn("模具任务{}的维保计划ID为空，跳过计划名称填充", moldtaskManagementDO.getId());
            moldtaskManagementDO.setProjectFormName("无维保计划"); // 兜底默认值
            continue;
        }

        // 3.2 查询维保计划
        MoldPlanMaintenanceDO moldplanMaintenanceDO = moldplanMaintenanceMapper.selectById(projectFormId);

        // 3.3 校验查询结果非空
        if (moldplanMaintenanceDO == null) {
            log.warn("模具任务{}关联的维保计划{}不存在", moldtaskManagementDO.getId(), projectFormId);
            moldtaskManagementDO.setProjectFormName("维保计划不存在"); // 兜底
        } else {
            // 3.4 正常赋值（确保planName非空，避免空字符串）
            String planName = moldplanMaintenanceDO.getPlanName();
            moldtaskManagementDO.setProjectFormName(planName == null ? "未命名维保计划" : planName);
        }
    }

    // 4. 返回处理后的结果
    return moldtaskManagementDOPageResult;
}

    @Override
    public void createMoldTicket(Long id) {

        List<MoldTicketManagementDO> moldticketManagementDOS = new ArrayList<>();

        //检验数据是否存在
        validateMoldTaskManagementExists(id);
        MoldTaskManagementDO moldtaskManagementDO = moldtaskManagementMapper.selectById(id);
        if (moldtaskManagementDO == null){
            throw exception(TASK_MANAGEMENT_NOT_EXISTS);
        }

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


        for (Long moldId : idList) {
            MoldTicketManagementDO moldticketManagementDO = new MoldTicketManagementDO();
            MoldDO moldDO = moldMapper.selectById(moldId);
            moldticketManagementDO.setTaskId(moldtaskManagementDO.getId());
            moldticketManagementDO.setPlanNo(generatePrefixedOrderNo());
            moldticketManagementDO.setPlanId(moldtaskManagementDO.getProjectForm());
            moldticketManagementDO.setMoldName(moldDO.getName());
            moldticketManagementDO.setPlanType(moldtaskManagementDO.getTaskType());
            moldticketManagementDO.setConfigName(moldtaskManagementDO.getName());
            moldticketManagementDO.setTaskEndTime(moldtaskManagementDO.getEndDate().atStartOfDay());
            moldticketManagementMapper.insert(moldticketManagementDO);

            List<MoldSubjectDO> moldSubjectDOList = new ArrayList<>();
            List<SubjectMoldPlanDO> subjectmoldPlanDOList = subjectmoldPlanMapper.selectList(Wrappers.<SubjectMoldPlanDO>lambdaQuery().eq(SubjectMoldPlanDO::getPlanId, moldticketManagementDO.getPlanId()));
            for (SubjectMoldPlanDO subjectmoldPlanDO : subjectmoldPlanDOList) {
                MoldSubjectDO moldSubjectDO = moldSubjectMapper.selectById(subjectmoldPlanDO.getSubjectId());

                MoldTicketResultsDO moldticketResultsDO = new MoldTicketResultsDO();
                moldticketResultsDO.setInspectionItemName(moldSubjectDO.getSubjectName());
                moldticketResultsDO.setInspectionMethod(moldSubjectDO.getInspectionMethod());
                moldticketResultsDO.setJudgmentCriteria(moldSubjectDO.getJudgmentCriteria());
                moldticketResultsDO.setManagementId(moldticketManagementDO.getId());
                moldticketResultsDO.setMoldId(moldId);
                moldticketResultsMapper.insert(moldticketResultsDO);
            }

        }

    }


    /**
     * 带前缀的时间戳单号
     */
    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;
    }
}