package org.jeecg.modules.toolCheck.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.jeecg.modules.api.model.ToolCheckResultDTO;
import org.jeecg.modules.tool.entity.Tool;
import org.jeecg.modules.tool.mapper.ToolMapper;
import org.jeecg.modules.toolCheck.entity.ToolCheck;
import org.jeecg.modules.toolCheck.mapper.ToolCheckMapper;
import org.jeecg.modules.toolCheck.service.IToolCheckService;
import org.jeecg.modules.toolSheet.entity.ToolSheet;
import org.jeecg.modules.toolSheet.mapper.ToolSheetMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

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

/**
 * @Description: 工具委外检定
 * @Author: jeecg-boot
 * @Date:   2025-03-25
 * @Version: V1.0
 */
@Service
public class ToolCheckServiceImpl extends ServiceImpl<ToolCheckMapper, ToolCheck> implements IToolCheckService {

    @Autowired
    private ToolSheetMapper toolSheetMapper;
    @Autowired
    private ToolMapper toolMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean save(ToolCheck toolCheck) {
        //送检时将相应工具状态修改
        ToolSheet toolSheet = toolSheetMapper.selectById(toolCheck.getToolId());
        if (toolSheet == null) {
            throw new RuntimeException("工具不存在！");
        }
        // 已送检状态校验（防重复操作）
        if (toolSheet.getStatus() == 3) {
            throw new RuntimeException("工具已在送检中，请勿重复操作");
        }
        toolSheet.setStatus(3);
        toolSheet.setNum(0);
        toolSheetMapper.updateById(toolSheet);
        return super.save(toolCheck);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void editToolCheck(ToolCheck toolCheck) {
        //相应工具状态修改
        ToolSheet toolSheet = toolSheetMapper.selectById(toolCheck.getToolId());
        if (toolSheet == null) {
            throw new RuntimeException("工具不存在！");
        }
        toolSheet.setStatus(0);
        toolSheet.setNum(1);
        toolSheetMapper.updateById(toolSheet);
        baseMapper.updateById(toolCheck);
    }

    @Override
    public ToolCheckResultDTO queryToolSheetCheckList() {
        ToolCheckResultDTO result = new ToolCheckResultDTO();
        // 1 查询需要检定的工具
        List<Tool> checkTools = toolMapper.selectList(new LambdaQueryWrapper<Tool>()
                .select(Tool::getId, Tool::getCheckCycle).eq(Tool::getCheckRequire, "1"));
        if (CollectionUtil.isEmpty(checkTools)) {
            return result;
        }

        // 2 toolId -> cycle
        Map<String, Integer> toolCycleMap = new HashMap<>(checkTools.size());
        for (Tool tool : checkTools) {
            toolCycleMap.put(tool.getId(), tool.getCheckCycle());
        }

        // 3 查询工具台账
        List<ToolSheet> toolSheets = toolSheetMapper.selectList(
                new LambdaQueryWrapper<ToolSheet>()
                        .in(ToolSheet::getToolId, toolCycleMap.keySet())
                        .select(ToolSheet::getId,ToolSheet::getToolId,ToolSheet::getCode,ToolSheet::getModel,ToolSheet::getLastCheckDate));

        if (CollectionUtil.isEmpty(toolSheets)) {
            return result;
        }

        Date now = new Date();
        List<ToolSheet> overdueList = result.getOverdue();
        List<ToolSheet> warningList = result.getWarning();

        for (ToolSheet sheet : toolSheets) {
            Integer cycle = toolCycleMap.get(sheet.getToolId());
            if (cycle == null) {
                continue;
            }

            Date lastCheckDate = sheet.getLastCheckDate();
            // 从未检定
            if (lastCheckDate == null) {
                overdueList.add(sheet);
                continue;
            }
            long elapsedDays = DateUtil.betweenDay(lastCheckDate, now, true);
            // 已超期
            if (elapsedDays > (cycle - 1)) {
                overdueList.add(sheet);
                continue;
            }
            // 剩余天数
            long remainDays = cycle - elapsedDays;
            if (remainDays <= 30) {
                warningList.add(sheet);
            }
        }
        return result;
    }

}
