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

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.controller.admin.dashboard.vo.dashboard.EventStatisticsVO;
import cn.iocoder.yudao.module.mes.dal.dataobject.deviceledger.DeviceLedgerDO;
import cn.iocoder.yudao.module.common.controller.admin.moldticketmanagement.enums.MoldPlanTypeEnum;
import cn.iocoder.yudao.module.common.dal.dataobject.moldticketresults.MoldTicketResultsDO;
import cn.iocoder.yudao.module.common.dal.mysql.moldticketresults.MoldTicketResultsMapper;
import cn.iocoder.yudao.module.mes.dal.mysql.deviceledger.DeviceLedgerMapper;
import com.alibaba.excel.util.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.transaction.annotation.Transactional;

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

import cn.iocoder.yudao.module.common.controller.admin.moldticketmanagement.vo.*;
import cn.iocoder.yudao.module.common.dal.dataobject.moldticketmanagement.MoldTicketManagementDO;
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.common.dal.mysql.moldticketmanagement.MoldTicketManagementMapper;

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

/**
 * 项目方案关联 Service 实现类
 *
 * @author 内蒙必硕
 */
@Service
@Validated
public class MoldTicketManagementServiceImpl implements MoldTicketManagementService {

    @Resource
    private MoldTicketManagementMapper moldTicketManagementMapper;
    @Resource
    @Lazy
    private MoldMapper moldMapper;
    @Resource
    @Lazy
    private MoldTicketResultsMapper moldTicketResultsMapper;

    @Override
    public Long createMoldTicketManagement(MoldTicketManagementSaveReqVO createReqVO) {
        // 插入
        MoldTicketManagementDO moldticketManagement = BeanUtils.toBean(createReqVO, MoldTicketManagementDO.class);
        moldTicketManagementMapper.insert(moldticketManagement);
        // 返回
        return moldticketManagement.getId();
    }

    @Override
    public void updateMoldTicketManagement(MoldTicketManagementSaveReqVO updateReqVO) {
        // 校验存在
        validateMoldTicketManagementExists(updateReqVO.getId());
        // 更新
        MoldTicketManagementDO updateObj = BeanUtils.toBean(updateReqVO, MoldTicketManagementDO.class);
        moldTicketManagementMapper.updateById(updateObj);
    }

    @Override
    public void deleteMoldTicketManagement(Long id) {
        // 校验存在
        validateMoldTicketManagementExists(id);
        // 删除
        moldTicketManagementMapper.deleteById(id);
    }

    private void validateMoldTicketManagementExists(Long id) {
        if (moldTicketManagementMapper.selectById(id) == null) {
            throw exception(TICKET_MANAGEMENT_NOT_EXISTS);
        }
    }

    @Override
    public MoldTicketManagementDO getMoldTicketManagement(Long id) {
        return moldTicketManagementMapper.selectById(id);
    }

    @Override
    public PageResult<MoldTicketManagementDO> getMoldTicketManagementPage(MoldTicketManagementPageReqVO pageReqVO) {
        return moldTicketManagementMapper.selectPage(pageReqVO);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void batchUpdateJobStatus(MoldTicketManagementBatchUpdateReqVO reqVO) {
        // 1. 解析ID列表
        List<Long> idList = parseIds(reqVO.getIds());
        if (idList.isEmpty()) {
            throw exception(TICKET_MANAGEMENT_NOT_EXISTS);
        }

        // 2. 批量更新
        moldTicketManagementMapper.batchUpdateJobStatus(idList, reqVO.getJobStatus(),reqVO.getCancelReason());
    }


    @Override
    public  List<MoldTicketResultsDO> getInspectionByMoldId(Long id, String startTime, String endTime, String ids) {
        MoldDO moldDO = moldMapper.selectById(id);
        //点检列表
        List<MoldTicketResultsDO> inspectionList = moldTicketResultsMapper.findByMoldIdAndPlanType(id, MoldPlanTypeEnum.INSPECTION.getCode(),startTime,endTime,ids);
        if(CollectionUtils.isNotEmpty(inspectionList)){
            moldDO.setInspectionList(inspectionList);
        }

        return  inspectionList;
    }

    @Override
    public List<MoldTicketResultsDO> getMaintenanceByMoldId(Long id,String startTime,String endTime,String ids) {
        MoldDO moldDO = moldMapper.selectById(id);

        //保养列表
        List<MoldTicketResultsDO> inspectionList = moldTicketResultsMapper.findByMoldIdAndPlanType(id, MoldPlanTypeEnum.MAINTENANCE.getCode(),startTime,endTime,ids);
        if(CollectionUtils.isNotEmpty(inspectionList)){
            moldDO.setInspectionList(inspectionList);
        }

        return  inspectionList;
    }

    /**
     * 解析逗号分隔的ID字符串
     */
    private List<Long> parseIds(String ids) {
        if (StringUtils.isBlank(ids)) {
            return Collections.emptyList();
        }

        return Arrays.stream(ids.split(","))
                .map(String::trim)
                .filter(StringUtils::isNotBlank)
                .map(Long::valueOf)
                .distinct()
                .collect(Collectors.toList());
    }

    @Override
    public Long getBaoyangListCountByJobStatus() {
        return moldTicketManagementMapper.selectCount(Wrappers.<MoldTicketManagementDO>lambdaQuery()
                .eq(MoldTicketManagementDO::getJobStatus, 0)
                .eq(MoldTicketManagementDO::getPlanType,2));
    }

    @Override
    public Long getDianjianListCountByJobStatus() {
        return moldTicketManagementMapper.selectCount(Wrappers.<MoldTicketManagementDO>lambdaQuery()
                .eq(MoldTicketManagementDO::getJobStatus, 0)
                .eq(MoldTicketManagementDO::getPlanType,1));
    }

    @Override
    public List<MoldTicketManagementDO> getListByJobStatus() {
        return moldTicketManagementMapper.selectList(Wrappers.<MoldTicketManagementDO>lambdaQuery()
                .eq(MoldTicketManagementDO::getJobStatus, 0));
    }

    @Override
    public void selectCountMoldInspection(EventStatisticsVO eventStatisticsVO) {
        //模具点检
        int intValue = moldTicketManagementMapper.selectCount(Wrappers.<MoldTicketManagementDO>lambdaQuery()
                .eq(MoldTicketManagementDO::getPlanType, MoldPlanTypeEnum.INSPECTION.getCode())
                .eq(MoldTicketManagementDO::getJobStatus,0)).intValue();

        eventStatisticsVO.setMoldInspection(intValue);
    }

    @Override
    public void selectCountMoldMaintenance(EventStatisticsVO eventStatisticsVO) {
        //模具保养
        int intValue = moldTicketManagementMapper.selectCount(Wrappers.<MoldTicketManagementDO>lambdaQuery()
                .eq(MoldTicketManagementDO::getPlanType, MoldPlanTypeEnum.MAINTENANCE.getCode())
                .eq(MoldTicketManagementDO::getJobStatus,0)).intValue();
        eventStatisticsVO.setMoldMaintenance(intValue);
    }

    @Override
    public List<MoldTicketManagementDO> getList() {
        return moldTicketManagementMapper.selectList();
    }

}