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

import cn.iocoder.yudao.framework.security.core.LoginUser;
import cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils;
import cn.iocoder.yudao.module.mes.controller.admin.ticketresults.enums.JobResultEnum;
import cn.iocoder.yudao.module.mes.dal.dataobject.ticketmanagement.TicketManagementDO;
import cn.iocoder.yudao.module.mes.dal.mysql.ticketmanagement.TicketManagementMapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
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.time.LocalDateTime;
import java.util.*;
import cn.iocoder.yudao.module.mes.controller.admin.ticketresults.vo.*;
import cn.iocoder.yudao.module.mes.dal.dataobject.ticketresults.TicketResultsDO;
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.ticketresults.TicketResultsMapper;

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 TicketResultsServiceImpl implements TicketResultsService {

    @Resource
    private TicketResultsMapper ticketResultsMapper;

    @Resource
    @Lazy
    private TicketManagementMapper ticketManagementMapper;


    @Override
    public Long createTicketResults(TicketResultsSaveReqVO createReqVO) {
        // 插入
        TicketResultsDO ticketResults = BeanUtils.toBean(createReqVO, TicketResultsDO.class);
        ticketResultsMapper.insert(ticketResults);
        // 返回
        return ticketResults.getId();
    }

    @Override
    public void updateTicketResults(TicketResultsSaveReqVO updateReqVO) {
        // 校验存在
        validateTicketResultsExists(updateReqVO.getId());
        // 更新
        TicketResultsDO updateObj = BeanUtils.toBean(updateReqVO, TicketResultsDO.class);
        ticketResultsMapper.updateById(updateObj);
    }

    @Override
    public void deleteTicketResults(Long id) {
        // 校验存在
        validateTicketResultsExists(id);
        // 删除
        ticketResultsMapper.deleteById(id);
    }

    private void validateTicketResultsExists(Long id) {
        if (ticketResultsMapper.selectById(id) == null) {
            throw exception(TICKET_RESULTS_NOT_EXISTS);
        }
    }

    @Override
    public TicketResultsDO getTicketResults(Long id) {
        return ticketResultsMapper.selectById(id);
    }

    @Override
    public PageResult<TicketResultsDO> getTicketResultsPage(TicketResultsPageReqVO pageReqVO) {
        return ticketResultsMapper.selectPage(pageReqVO);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void batchUpdateTicketResults(List<TicketResultsSaveReqVO> updateReqVOList) {
        if (CollectionUtils.isEmpty(updateReqVOList)) {
            return;
        }

        // 1. 数据验证
        validateBatchUpdateData(updateReqVOList);

        // 2. 批量更新
        List<TicketResultsDO> updateList = new ArrayList<>();
        LocalDateTime now = LocalDateTime.now();

        for (TicketResultsSaveReqVO vo : updateReqVOList) {
            // 转换为DO
            TicketResultsDO updateDO = BeanUtils.toBean(vo, TicketResultsDO.class);
            updateDO.setUpdateTime(now);
            updateList.add(updateDO);
        }

        // 3. 执行批量更新
        ticketResultsMapper.updateBatch(updateList);

        //4. 判断是否全部已检验
        handleInspectionResult(updateReqVOList);


    }

    /**
     * 验证批量更新数据
     */
    private void validateBatchUpdateData(List<TicketResultsSaveReqVO> updateReqVOList) {
        if (CollectionUtils.isEmpty(updateReqVOList)) {
            return;
        }

        Set<Long> idSet = new HashSet<>();

        for (int i = 0; i < updateReqVOList.size(); i++) {
            TicketResultsSaveReqVO vo = updateReqVOList.get(i);

            // 验证ID不能为空
            if (vo.getId() == null) {
                throw exception(TICKET_RESULTS_ID_NOT_NULL);
            }

            idSet.add(vo.getId());

            // 调用单个验证逻辑
            validateTicketResultsExists(vo.getId());
        }
    }


    /**
     * 处理检验结果
     */
    private void handleInspectionResult(List<TicketResultsSaveReqVO> updateReqVOList) {
        if (CollectionUtils.isEmpty(updateReqVOList)) {
            return;
        }

        // 检查是否有未填写的
        boolean hasPending = updateReqVOList.stream()
                .anyMatch(vo -> vo.getInspectionResult() == null || vo.getInspectionResult().equals(JobResultEnum.PENDING.getCode()));

        if (hasPending) {
            return;
        }
        TicketManagementDO ticketManagementDO = ticketManagementMapper.selectById(updateReqVOList.get(0).getManagementId());
        if (ticketManagementDO == null ){
            throw exception(TICKET_MANAGEMENT_NOT_EXISTS);
        }
        ticketManagementDO.setTaskTime(LocalDateTime.now());
        //设置为已完成
        ticketManagementDO.setJobStatus("1");
        // 检查是否有不通过的
        boolean hasFail = updateReqVOList.stream()
                .anyMatch(vo -> vo.getInspectionResult() != null && vo.getInspectionResult().equals(JobResultEnum.FAIL.getCode()));
        if (hasFail) {
            ticketManagementDO.setJobResult(JobResultEnum.FAIL.getCode());

        } else {
            ticketManagementDO.setJobResult(JobResultEnum.PASS.getCode());
        }
        LoginUser loginUser = SecurityFrameworkUtils.getLoginUser();
        ticketManagementDO.setOperator(String.valueOf(loginUser.getId()));

        ticketManagementMapper.updateById(ticketManagementDO);

    }

}