package com.aucma.dms.service.impl;

import com.aucma.common.constant.DmsConstants;
import com.aucma.common.core.domain.model.LoginUser;
import com.aucma.common.exception.ServiceException;
import com.aucma.common.utils.DateUtils;
import com.aucma.common.utils.SecurityUtils;
import com.aucma.common.utils.StringUtils;
import com.aucma.dms.domain.*;
import com.aucma.dms.domain.vo.DmsBillsInspectInstanceScanVo;
import com.aucma.dms.mapper.*;
import com.aucma.dms.service.IDmsBillsInspectInstanceService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 巡检工单Service业务层处理
 *
 * @author Open Platform
 * @date 2024-01-23
 */
@Service
public class DmsBillsInspectInstanceServiceImpl implements IDmsBillsInspectInstanceService {
    private static final Logger log = LoggerFactory.getLogger(DmsBillsInspectInstanceServiceImpl.class);

    @Autowired
    private DmsBillsInspectInstanceMapper dmsBillsInspectInstanceMapper;
    @Autowired
    private DmsPlanInspectMapper dmsPlanInspectMapper;
    @Autowired
    private DmsBillsInspectInstanceActivityMapper dmsBillsInspectInstanceActivityMapper;
    @Autowired
    private DmsRepairInstanceMapper dmsRepairInstanceMapper;
    @Autowired
    private DmsInspectInstanceDetailMapper dmsInspectInstanceDetailMapper;
    @Autowired
    private DmsInspectInstanceDetailProjectMapper dmsInspectInstanceDetailProjectMapper;
    @Autowired
    private DmsInspectInstanceDetailProjectMapper dmsInspectInstanceDetailPrjectMapper;
    @Autowired
    private DmsInspectRouteDetailMapper dmsInspectRouteDetailMapper;
    @Autowired
    private DmsInspectProjectDeviceMapper dmsInspectProjectDeviceMapper;
/*    @Autowired
    private RemoteSysCommonService remoteSysCommonService;*/

    /**
     * 查询巡检工单
     *
     * @param inspectInstanceId 巡检工单主键
     * @return 巡检工单
     */
    @Override
    public DmsBillsInspectInstance selectDmsBillsInspectInstanceByInspectInstanceId(Long inspectInstanceId) {
        return dmsBillsInspectInstanceMapper.selectDmsBillsInspectInstanceByInspectInstanceId(inspectInstanceId);
    }

    /**
     * 查询巡检工单列表
     *
     * @param dmsBillsInspectInstance 巡检工单
     * @return 巡检工单
     */
    @Override
    public List<DmsBillsInspectInstance> selectDmsBillsInspectInstanceList(DmsBillsInspectInstance dmsBillsInspectInstance) {
        return dmsBillsInspectInstanceMapper.selectDmsBillsInspectInstanceList(dmsBillsInspectInstance);
    }

    @Override
    public List<DmsBillsInspectInstance> selectPoint() {
        return dmsBillsInspectInstanceMapper.selectPoint();
    }

    @Override
    public List<DmsBillsInspectInstance> selectInspection() {
        return dmsBillsInspectInstanceMapper.selectInspection();
    }

    /**
     * 新增巡检工单
     *
     * @param dmsBillsInspectInstance 巡检工单
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insertDmsBillsInspectInstance(DmsBillsInspectInstance dmsBillsInspectInstance) {
        LoginUser user = SecurityUtils.getLoginUser();
        // 已废弃审批流功能 - 以下代码已注释
        // Long aLong = dmsRepairInstanceMapper.selectWfProcessActivityId(105l);
        // if (dmsBillsInspectInstance.getInspectType().equals("1")) {
        //     dmsBillsInspectInstance.setWfProcessId(105l);
        // } else if (dmsBillsInspectInstance.getInspectType().equals("2")) {
        //     dmsBillsInspectInstance.setWfProcessId(104l);
        // }
        dmsBillsInspectInstance.setCreateTime(DateUtils.getNowDate());
        dmsBillsInspectInstance.setIsFlag("1");
        dmsBillsInspectInstance.setInspectStatus(DmsConstants.DMS_BILLS_INSPECT_INSTANCE_INSPECT_STATUS_TO_INSPECT);
        dmsBillsInspectInstance.setCreateBy(SecurityUtils.getLoginUser()==null ? SecurityUtils.getUserId() :SecurityUtils.getLoginUser().getUser().getUserId());
        int i;
        try {
            // 4) 插入主工单：
            //    若并发场景下命中唯一约束，则视为“已生成”，返回 0。
            i = dmsBillsInspectInstanceMapper.insertDmsBillsInspectInstance(dmsBillsInspectInstance);
        } catch (DuplicateKeyException e) {
            log.debug("巡检工单触发唯一约束(重复生成)，跳过 | planInspectId={}, billsInspectCode={}",
                    dmsBillsInspectInstance.getPlanInspectId(), dmsBillsInspectInstance.getBillsInspectCode());
            return 0;
        } catch (DataIntegrityViolationException e) {
            if (isOracleUniqueViolation(e)) {
                log.debug("巡检工单触发 ORA-00001(重复生成)，跳过 | planInspectId={}, billsInspectCode={}",
                        dmsBillsInspectInstance.getPlanInspectId(), dmsBillsInspectInstance.getBillsInspectCode());
                return 0;
            }
            throw e;
        }
        log.info("新增巡检工单 | inspectInstanceId={}, billsInspectCode={}, inspectRouteId={}, inspectType={}",
                dmsBillsInspectInstance.getInspectInstanceId(), dmsBillsInspectInstance.getBillsInspectCode(),
                dmsBillsInspectInstance.getInspectRouteId(), dmsBillsInspectInstance.getInspectType());
//        List<DmsBillsInspectInstance> dmsBillsInspectInstances = dmsBillsInspectInstanceMapper.selectDmsBillsInspectInstanceList(dmsBillsInspectInstance);
        //新建第一步工单实例节点
        DmsBillsInspectInstanceActivity dmsBillsInspectInstanceActivity = new DmsBillsInspectInstanceActivity();
        dmsBillsInspectInstanceActivity.setInspectInstanceId(dmsBillsInspectInstance.getInspectInstanceId());
        dmsBillsInspectInstanceActivity.setInspectRouteId(dmsBillsInspectInstance.getInspectRouteId());
        dmsBillsInspectInstanceActivity.setDeviceAmount(dmsBillsInspectInstance.getDeviceAmount());
        dmsBillsInspectInstanceActivity.setPerformer(dmsBillsInspectInstance.getPerformer());
        dmsBillsInspectInstanceActivity.setProcessStepOrder(1l);
        // 已废弃审批流功能
        // dmsBillsInspectInstanceActivity.setProcessActivityId(aLong);
        dmsBillsInspectInstanceActivityMapper.insertDmsBillsInspectInstanceActivity(dmsBillsInspectInstanceActivity);

        //新建点巡检工单明细
        DmsInspectRouteDetail queryInspectRouteDetail = new DmsInspectRouteDetail();
        queryInspectRouteDetail.setInspectRouteId(dmsBillsInspectInstance.getInspectRouteId());
        List<DmsInspectRouteDetail> dmsInspectRouteDetails = dmsInspectRouteDetailMapper.selectDmsInspectRouteDetailList(queryInspectRouteDetail);
        for(DmsInspectRouteDetail dmsInspectRouteDetail:dmsInspectRouteDetails){
            DmsInspectInstanceDetail dmsInspectInstanceDetail = new DmsInspectInstanceDetail();
            Long deviceId = dmsInspectRouteDetail.getDeviceId();
            dmsInspectInstanceDetail.setInspectInstanceId(dmsBillsInspectInstance.getInspectInstanceId());
            dmsInspectInstanceDetail.setLineStep(dmsInspectRouteDetail.getLineStep());
            dmsInspectInstanceDetail.setDeviceId(deviceId);
            dmsInspectInstanceDetail.setInstanceDetailStatus("1");
            dmsInspectInstanceDetail.setInspectStandard(dmsInspectRouteDetail.getInspectStandard());
            dmsInspectInstanceDetail.setInspectStatus("0");
            dmsInspectInstanceDetailMapper.insertDmsInspectInstanceDetail(dmsInspectInstanceDetail);
            Long projectId = resolveProjectIdByInspectStandard(dmsInspectRouteDetail.getInspectStandard());
            DmsInspectProjectDevice queryInspectProjectDevice = new DmsInspectProjectDevice();
            queryInspectProjectDevice.setTargetType("2");
            queryInspectProjectDevice.setTargetId(deviceId);
            List<DmsInspectProjectDevice> dmsInspectProjectDevices = dmsInspectProjectDeviceMapper.selectDmsInspectProjectDeviceList(queryInspectProjectDevice);
//            for(DmsInspectProjectDevice dmsInspectProjectDevice:dmsInspectProjectDevices){
                if (projectId != null) {
                    DmsInspectInstanceDetailProject dmsInspectInstanceDetailProject = new DmsInspectInstanceDetailProject();
                    dmsInspectInstanceDetailProject.setInstanceDetailId(dmsInspectInstanceDetail.getInstanceDetailId());
                    dmsInspectInstanceDetailProject.setInspectProjectId(projectId);
                    dmsInspectInstanceDetailProject.setCreateTime(new Date());
                    dmsInspectInstanceDetailProjectMapper.insertDmsInspectInstanceDetailProject(dmsInspectInstanceDetailProject);
                } else {
                    log.warn("未找到巡检标准对应的项目ID，跳过创建项目记录 | inspectStandard={}, deviceId={}, inspectRouteId={}",
                            dmsInspectRouteDetail.getInspectStandard(), deviceId, dmsBillsInspectInstance.getInspectRouteId());
                }
//            }

        }

        return i;
    }

    private boolean isOracleUniqueViolation(Throwable e) {
        Throwable cursor = e;
        while (cursor != null) {
            String msg = cursor.getMessage();
            // ORA-00001 = unique constraint violated
            // 逐层检查 cause，兼容不同异常包装层（Spring/MyBatis/JDBC）。
            if (msg != null && msg.contains("ORA-00001")) {
                return true;
            }
            cursor = cursor.getCause();
        }
        return false;
    }

    private Long resolveProjectIdByInspectStandard(String inspectStandard) {
        if (inspectStandard == null || inspectStandard.trim().isEmpty()) {
            return null;
        }
        return dmsInspectInstanceDetailMapper.selectProjectId(inspectStandard);
    }

    /**
     * 修改巡检工单
     *
     * @param dmsBillsInspectInstance 巡检工单
     * @return 结果
     */
    @Override
    public int updateDmsBillsInspectInstance(DmsBillsInspectInstance dmsBillsInspectInstance) {
        dmsBillsInspectInstance.setUpdateTime(DateUtils.getNowDate());
        return dmsBillsInspectInstanceMapper.updateDmsBillsInspectInstance(dmsBillsInspectInstance);
    }

    /**
     * 批量删除巡检工单
     *
     * @param inspectInstanceIds 需要删除的巡检工单主键
     * @return 结果
     */
    @Override
    public int deleteDmsBillsInspectInstanceByInspectInstanceIds(Long[] inspectInstanceIds) {
        return dmsBillsInspectInstanceMapper.deleteDmsBillsInspectInstanceByInspectInstanceIds(inspectInstanceIds);
    }

    /**
     * 删除巡检工单信息
     *
     * @param inspectInstanceId 巡检工单主键
     * @return 结果
     */
    @Override
    public int deleteDmsBillsInspectInstanceByInspectInstanceId(Long inspectInstanceId) {
        return dmsBillsInspectInstanceMapper.deleteDmsBillsInspectInstanceByInspectInstanceId(inspectInstanceId);
    }

    @Override
    public int insertDmsBillsInspectInstancePDA(DmsBillsInspectInstance dmsBillsInspectInstance) {
        // 已废弃审批流功能 - 以下代码已注释
        // Long along = null;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHH");
        // if (dmsBillsInspectInstance.getInspectType().equals("1")) {
        //     dmsBillsInspectInstance.setWfProcessId(105l);
        //     along = remoteSysCommonService.selectProcessActivityIdByWfProcessId(SecurityConstants.INNER, 105l);
        // } else if (dmsBillsInspectInstance.getInspectType().equals("2")) {
        //     dmsBillsInspectInstance.setWfProcessId(104l);
        //     along = remoteSysCommonService.selectProcessActivityIdByWfProcessId(SecurityConstants.INNER, 104l);
        // }
        dmsBillsInspectInstance.setBillsInspectCode(sdf.format(DateUtils.getNowDate()));
        dmsBillsInspectInstance.setInspectStatus("1");
        dmsBillsInspectInstance.setIsFlag("1");
        //创建点巡检工单实例节点第一步
        int i = dmsBillsInspectInstanceMapper.insertDmsBillsInspectInstance(dmsBillsInspectInstance);

        DmsBillsInspectInstanceActivity dmsBillsInspectInstanceActivity = new DmsBillsInspectInstanceActivity();
        dmsBillsInspectInstanceActivity.setInspectInstanceId(dmsBillsInspectInstance.getInspectInstanceId());
        dmsBillsInspectInstanceActivity.setProcessStepOrder(1l);
        // 已废弃审批流功能
        // dmsBillsInspectInstanceActivity.setProcessActivityId(along);
        dmsBillsInspectInstanceActivity.setInspectRouteId(dmsBillsInspectInstance.getInspectRouteId());
        dmsBillsInspectInstanceActivity.setDeviceAmount(dmsBillsInspectInstance.getDeviceAmount());
        dmsBillsInspectInstanceActivity.setPerformer(dmsBillsInspectInstance.getPerformer());
        dmsBillsInspectInstanceActivity.setProcessHandleStatus("1");
        dmsBillsInspectInstanceActivityMapper.insertDmsBillsInspectInstanceActivity(dmsBillsInspectInstanceActivity);
        return 0;
    }


    /**
     * 获取最新一条未完成的巡检工单
     *
     * @param dmsBillsInspectInstance
     * @return
     */
    @Override
    public DmsBillsInspectInstance getNewestBillsInspectInstance(DmsBillsInspectInstance dmsBillsInspectInstance) {
        dmsBillsInspectInstance.setInspectStatusStr(DmsConstants.DMS_BILLS_INSPECT_INSTANCE_INSPECT_STATUS_TO_INSPECT + "," + DmsConstants.DMS_BILLS_INSPECT_INSTANCE_INSPECT_STATUS_INSPECTING);
        DmsBillsInspectInstance newestBillsInspectInstance = dmsBillsInspectInstanceMapper.selectNewestDmsBillsInspectInstance(dmsBillsInspectInstance);
        if (newestBillsInspectInstance != null) {
            DmsInspectInstanceDetail queryInspectInstanceDetail = new DmsInspectInstanceDetail();
            queryInspectInstanceDetail.setInspectInstanceId(newestBillsInspectInstance.getInspectInstanceId());
            List<DmsInspectInstanceDetail> inspectInstanceDetails = dmsInspectInstanceDetailMapper.selectDmsInspectInstanceDetailJoinList(queryInspectInstanceDetail);
            newestBillsInspectInstance.setDmsInspectInstanceDetailList(inspectInstanceDetails);
        }
        newestBillsInspectInstance.setBillsInspectCode(newestBillsInspectInstance.getPlanInspectCode());
        return newestBillsInspectInstance;
    }


    /**
     * 扫描设备验证并获取巡检项目信息
     *
     * @param dmsBillsInspectInstanceScanVo
     * @return
     */
    @Override
    public DmsInspectInstanceDetail scanInspectInstanceDetail(DmsBillsInspectInstanceScanVo dmsBillsInspectInstanceScanVo) {
        DmsInspectInstanceDetail dmsInspectInstanceDetail = dmsInspectInstanceDetailMapper.selectDmsInspectInstanceDetailByUI(dmsBillsInspectInstanceScanVo.getInspectInstanceId(),
                dmsBillsInspectInstanceScanVo.getDeviceCode());
        if (dmsInspectInstanceDetail == null) {
            throw new ServiceException("无此设备的检查工单");
        }
        Long deviceId = dmsInspectInstanceDetail.getDeviceId();
        DmsInspectInstanceDetailProject queryInspectInstanceDetailProject = new DmsInspectInstanceDetailProject();
        queryInspectInstanceDetailProject.setDeviceId(deviceId);
        Long projectId = resolveProjectIdByInspectStandard(dmsInspectInstanceDetail.getInspectStandard());
        if (projectId == null) {
            log.warn("巡检标准为空或未配置项目，返回空项目列表 | inspectInstanceId={}, instanceDetailId={}, inspectStandard={}",
                    dmsBillsInspectInstanceScanVo.getInspectInstanceId(), dmsInspectInstanceDetail.getInstanceDetailId(),
                    dmsInspectInstanceDetail.getInspectStandard());
            dmsInspectInstanceDetail.setDmsInspectInstanceDetailProjectList(new ArrayList<>());
            return dmsInspectInstanceDetail;
        }
        queryInspectInstanceDetailProject.setInspectProjectId(projectId);
        queryInspectInstanceDetailProject.setInstanceDetailId(dmsInspectInstanceDetail.getInstanceDetailId());
        List<DmsInspectInstanceDetailProject> dmsInspectInstanceDetailProjects = dmsInspectInstanceDetailPrjectMapper.selectDmsInspectInstanceDetailProjectJoinList(queryInspectInstanceDetailProject);

        dmsInspectInstanceDetail.setDmsInspectInstanceDetailProjectList(dmsInspectInstanceDetailProjects);
        DmsBillsInspectInstance dmsBillsInspectInstance = new DmsBillsInspectInstance();

        dmsBillsInspectInstance.setInspectInstanceId(dmsBillsInspectInstanceScanVo.getInspectInstanceId());
        dmsBillsInspectInstance.setRealBeginTime(new Date());
//        dmsBillsInspectInstance.setInspectStatus("2");
        int i = dmsBillsInspectInstanceMapper.updateDmsBillsInspectInstance(dmsBillsInspectInstance);
        return dmsInspectInstanceDetail;

    }


    /**
     * 更新点巡检工单明细
     *
     * @param dmsInspectInstanceDetail 点巡检工单明细
     * @return 结果
     */
    @Transactional
    @Override
    public int updateDmsInspectInstanceDetail(DmsInspectInstanceDetail dmsInspectInstanceDetail) {
        DmsRecordInspect dmsRecordInspect = dmsBillsInspectInstanceMapper.selectRecord(dmsInspectInstanceDetail.getInstanceDetailId());

        List<DmsRecordInspect> recordInspect = dmsBillsInspectInstanceMapper.selectRecordByInstainceId(dmsRecordInspect.getInspectInstanceId());
//        if (recordInspect!=null&&recordInspect.size()>0){
//            dmsRecordInspect.setInspectStatus(2l);
//        }else {
//            dmsRecordInspect.setInspectStatus(3l);
//        }
        dmsRecordInspect.setInspectStatus(3l);
        int i1 = dmsBillsInspectInstanceMapper.insertRecord(dmsRecordInspect);
        int count = dmsBillsInspectInstanceMapper.selectUnCompletedInstance(dmsRecordInspect.getInspectInstanceId());
//        int count1 = dmsBillsInspectInstanceMapper.selectAllInstance(dmsRecordInspect.getInspectInstanceId());
        DmsBillsInspectInstance dmsBillsInspectInstance = new DmsBillsInspectInstance();
        if (count==0||count==1){
            dmsBillsInspectInstance.setInspectStatus("3");
        }else{
            dmsBillsInspectInstance.setInspectStatus("2");
        }
        dmsBillsInspectInstance.setInspectInstanceId(dmsInspectInstanceDetail.getInspectInstanceId());
        dmsBillsInspectInstance.setRealEndTime(new Date());
        int i = dmsBillsInspectInstanceMapper.updateDmsBillsInspectInstance(dmsBillsInspectInstance);
        String userName = SecurityUtils.getLoginUser()==null ? SecurityUtils.getUsername() :SecurityUtils.getLoginUser().getUser().getNickName();
        Date currentDate = new Date();
        dmsInspectInstanceDetail.setUpdateTime(currentDate);
        dmsInspectInstanceDetail.setUpdateBy(SecurityUtils.getUserId());

        DmsInspectInstanceDetail returnInspectInstanceDetail = handleDmsInspectInstanceDetailProject(dmsInspectInstanceDetail);
        if (returnInspectInstanceDetail != null) {
            dmsInspectInstanceDetail.setInspectStatus(returnInspectInstanceDetail.getInspectStatus());
            dmsInspectInstanceDetail.setInstanceDetailStatus(returnInspectInstanceDetail.getInstanceDetailStatus());
            dmsInspectInstanceDetail.setDmsInspectInstanceDetailProjectList(returnInspectInstanceDetail.getDmsInspectInstanceDetailProjectList());
            batchUpdateDmsInspectInstanceDetailProject(dmsInspectInstanceDetail);
        }


        return dmsInspectInstanceDetailMapper.updateDmsInspectInstanceDetail(dmsInspectInstanceDetail);
    }

    /**
     * 更新点巡检工单明细项目信息
     *
     * @param dmsInspectInstanceDetail 点巡检工单明细
     */
    public DmsInspectInstanceDetail handleDmsInspectInstanceDetailProject(DmsInspectInstanceDetail dmsInspectInstanceDetail) {
        String instanceDetailStatus = DmsConstants.DMS_INSPECT_INSTANCE_DETAIL_STATUS_FINISH;
        String inspectStatus = DmsConstants.DMS_INSPECT_INSTANCE_DETAIL_INSPECT_STATUS_PASS;//质检结果检验状态
        List<DmsInspectInstanceDetailProject> inspectInstanceDetailProjectList = dmsInspectInstanceDetail.getDmsInspectInstanceDetailProjectList();
        if (StringUtils.isNotNull(inspectInstanceDetailProjectList)) {
            DmsInspectInstanceDetail returnInspectInstanceDetail = new DmsInspectInstanceDetail();
            List<DmsInspectInstanceDetailProject> toUpdatedList = new ArrayList<>();
            for (DmsInspectInstanceDetailProject inspectInstanceDetailProject : inspectInstanceDetailProjectList) {
                String inspectProjectProperty = inspectInstanceDetailProject.getInspectProjectProperty();
                if (inspectProjectProperty.equals(DmsConstants.DMS_INSPECT_INSTANCE_PROJECT_PROPERTY_QUALITATIVE)) {//如果是定性
                    String inspectProjectStatus = inspectInstanceDetailProject.getInspectProjectStatus();
                    if (inspectProjectStatus != null) {
                        if (inspectProjectStatus.equals(DmsConstants.DMS_INSPECT_INSTANCE_DETAIL_PROJECT_STATUS_FAIL)) {
                            inspectStatus = DmsConstants.DMS_INSPECT_INSTANCE_DETAIL_INSPECT_STATUS_FAIL;
                        }
                    } else {
                        instanceDetailStatus = DmsConstants.DMS_INSPECT_INSTANCE_DETAIL_STATUS_INSPECTING;
                    }
                } else {//如果是定量
                    BigDecimal inspectProjectResult = inspectInstanceDetailProject.getInspectProjectResult();
                    if (inspectProjectResult != null) {
                        BigDecimal standardValue = inspectInstanceDetailProject.getDefValue();
                        BigDecimal upperDiff = inspectInstanceDetailProject.getUpLimit();
                        BigDecimal downDiff = inspectInstanceDetailProject.getLowLimit();

                        if (upperDiff == null) {//如果没设置上差值，则标准值为上差值
                            upperDiff = standardValue;
                        } else if (downDiff == null) {//如果没设置下差值，则标准值为下差值
                            downDiff = standardValue;
                        }
                        if (inspectProjectResult.compareTo(downDiff) >= 0 && inspectProjectResult.compareTo(upperDiff) <= 0) {
                            inspectInstanceDetailProject.setInspectProjectStatus(DmsConstants.DMS_INSPECT_INSTANCE_DETAIL_PROJECT_STATUS_PASS);
                        } else {
                            inspectInstanceDetailProject.setInspectProjectStatus(DmsConstants.DMS_INSPECT_INSTANCE_DETAIL_PROJECT_STATUS_FAIL);
                            inspectStatus = DmsConstants.DMS_INSPECT_INSTANCE_DETAIL_INSPECT_STATUS_FAIL;
                        }

                    } else {
                        instanceDetailStatus = DmsConstants.DMS_INSPECT_INSTANCE_DETAIL_STATUS_INSPECTING;
                    }
                }

                toUpdatedList.add(inspectInstanceDetailProject);
            }

            returnInspectInstanceDetail.setInspectStatus(inspectStatus);
            returnInspectInstanceDetail.setInstanceDetailStatus(instanceDetailStatus);
            returnInspectInstanceDetail.setDmsInspectInstanceDetailProjectList(toUpdatedList);

            return returnInspectInstanceDetail;
        }


        return null;
    }

    /**
     * 批量更新点巡检工单明细项目信息(事务，需要用public，不能用private)
     */
    public void batchUpdateDmsInspectInstanceDetailProject(DmsInspectInstanceDetail dmsInspectInstanceDetail) {
        List<DmsInspectInstanceDetailProject> inspectInstanceDetailProjects = dmsInspectInstanceDetail.getDmsInspectInstanceDetailProjectList();
        for (DmsInspectInstanceDetailProject dmsInspectInstanceDetailProject : inspectInstanceDetailProjects) {
            if (dmsInspectInstanceDetailProject.getInstanceDetailProjectId() == null) {
                dmsInspectInstanceDetailProject.setInstanceDetailId(dmsInspectInstanceDetail.getInstanceDetailId());
                dmsInspectInstanceDetailProjectMapper.insertDmsInspectInstanceDetailProject(dmsInspectInstanceDetailProject);
            } else {
                dmsInspectInstanceDetailProjectMapper.updateDmsInspectInstanceDetailProject(dmsInspectInstanceDetailProject);
            }
        }

    }

    /**
     * 定时任务专用：创建已完成状态的巡检工单（含明细），路线所有设备默认正常
     * 不依赖SecurityUtils，适合在定时任务上下文中调用
     */
    @Override
    // @Transactional(rollbackFor = Exception.class)
    @Transactional(propagation = Propagation.REQUIRES_NEW, rollbackFor = Exception.class)
    public int insertCompletedInspectInstance(DmsBillsInspectInstance dmsBillsInspectInstance) {
        Long planInspectId = dmsBillsInspectInstance.getPlanInspectId();
        if (planInspectId != null) {
            // 1) 先锁计划行（FOR UPDATE）：
            //    将同一计划的并发任务串行化，避免同时进入插入阶段。
            Long lockedId = dmsPlanInspectMapper.lockPlanById(planInspectId);
            if (lockedId == null) {
                log.warn("巡检计划不存在，跳过工单生成 | planInspectId={}", planInspectId);
                return 0;
            }
            // 2) 再做当天查重（应用层幂等）：
            //    这里返回已生成则直接跳过。
            int existCount = dmsBillsInspectInstanceMapper.countByPlanIdAndToday(planInspectId);
            if (existCount > 0) {
                log.debug("巡检计划今天已生成工单，跳过 | planInspectId={}", planInspectId);
                return 0;
            }
        }

        // 3) 统一使用 DB 时间作为“当天”基准，减少应用机/DB 机时钟偏差带来的跨天误判。
        Date now = dmsBillsInspectInstanceMapper.selectDbNow();
        if (now == null) {
            // 理论兜底：DB 时间查询异常时退回应用时间，避免任务中断。
            now = new Date();
        }
        log.info("开始创建已完成巡检工单 | billsInspectCode={}, planInspectId={}, inspectRouteId={}, inspectType={}",
                dmsBillsInspectInstance.getBillsInspectCode(), dmsBillsInspectInstance.getPlanInspectId(),
                dmsBillsInspectInstance.getInspectRouteId(), dmsBillsInspectInstance.getInspectType());

        // 1. 设置工单为已完成状态
        dmsBillsInspectInstance.setCreateTime(now);
        dmsBillsInspectInstance.setIsFlag("1");
        dmsBillsInspectInstance.setInspectStatus(DmsConstants.DMS_BILLS_INSPECT_INSTANCE_INSPECT_STATUS_FINISH); // 3=已完成
        dmsBillsInspectInstance.setPlanBeginTime(now);
        dmsBillsInspectInstance.setPlanEndTime(now);
        dmsBillsInspectInstance.setRealBeginTime(now);
        dmsBillsInspectInstance.setRealEndTime(now);
        if (dmsBillsInspectInstance.getCreateBy() == null) {
            dmsBillsInspectInstance.setCreateBy(-1L);
        }

        int i;
        try {
            i = dmsBillsInspectInstanceMapper.insertDmsBillsInspectInstance(dmsBillsInspectInstance);
        } catch (DuplicateKeyException e) {
            log.debug("巡检工单触发唯一约束(重复生成)，跳过 | planInspectId={}, billsInspectCode={}",
                    dmsBillsInspectInstance.getPlanInspectId(), dmsBillsInspectInstance.getBillsInspectCode());
            return 0;
        } catch (DataIntegrityViolationException e) {
            if (isOracleUniqueViolation(e)) {
                log.debug("巡检工单触发 ORA-00001(重复生成)，跳过 | planInspectId={}, billsInspectCode={}",
                        dmsBillsInspectInstance.getPlanInspectId(), dmsBillsInspectInstance.getBillsInspectCode());
                return 0;
            }
            throw e;
        }

        // 5) 创建工单活动节点（第一步）
        DmsBillsInspectInstanceActivity activity = new DmsBillsInspectInstanceActivity();
        activity.setInspectInstanceId(dmsBillsInspectInstance.getInspectInstanceId());
        activity.setInspectRouteId(dmsBillsInspectInstance.getInspectRouteId());
        activity.setDeviceAmount(dmsBillsInspectInstance.getDeviceAmount());
        activity.setPerformer(dmsBillsInspectInstance.getPerformer());
        activity.setProcessStepOrder(1L);
        activity.setProcessHandleStatus("3"); // 已完成
        dmsBillsInspectInstanceActivityMapper.insertDmsBillsInspectInstanceActivity(activity);

        // 6) 创建巡检工单明细：路线上的设备默认“已完成 + 合格”。
        if (dmsBillsInspectInstance.getInspectRouteId() != null) {
            DmsInspectRouteDetail queryRouteDetail = new DmsInspectRouteDetail();
            queryRouteDetail.setInspectRouteId(dmsBillsInspectInstance.getInspectRouteId());
            List<DmsInspectRouteDetail> routeDetails = dmsInspectRouteDetailMapper.selectDmsInspectRouteDetailList(queryRouteDetail);
            if (routeDetails == null || routeDetails.isEmpty()) {
                log.error("定时任务创建已完成巡检工单: 巡检路线无设备明细 | inspectRouteId={}, billsInspectCode={}, planInspectId={}",
                        dmsBillsInspectInstance.getInspectRouteId(), dmsBillsInspectInstance.getBillsInspectCode(),
                        dmsBillsInspectInstance.getPlanInspectId());
            }

            for (DmsInspectRouteDetail routeDetail : routeDetails) {
                DmsInspectInstanceDetail detail = new DmsInspectInstanceDetail();
                Long deviceId = routeDetail.getDeviceId();
                detail.setInspectInstanceId(dmsBillsInspectInstance.getInspectInstanceId());
                detail.setLineStep(routeDetail.getLineStep());
                detail.setDeviceId(deviceId);
                detail.setInstanceDetailStatus(DmsConstants.DMS_INSPECT_INSTANCE_DETAIL_STATUS_FINISH); // 3=已完成
                detail.setInspectStandard(routeDetail.getInspectStandard());
                detail.setInspectStatus(DmsConstants.DMS_INSPECT_INSTANCE_DETAIL_INSPECT_STATUS_PASS); // 1=正常/合格
                dmsInspectInstanceDetailMapper.insertDmsInspectInstanceDetail(detail);

                // 7) 创建明细项目记录：仅在“巡检标准 -> 项目”映射存在时落库。
                Long projectId = resolveProjectIdByInspectStandard(routeDetail.getInspectStandard());
                if (projectId != null) {
                    DmsInspectInstanceDetailProject detailProject = new DmsInspectInstanceDetailProject();
                    detailProject.setInstanceDetailId(detail.getInstanceDetailId());
                    detailProject.setInspectProjectId(projectId);
                    detailProject.setCreateTime(now);
                    detailProject.setInspectProjectStatus(DmsConstants.DMS_INSPECT_INSTANCE_DETAIL_PROJECT_STATUS_PASS); // 1=合格
                    dmsInspectInstanceDetailProjectMapper.insertDmsInspectInstanceDetailProject(detailProject);
                } else {
                    log.warn("未找到巡检标准对应的项目ID，跳过创建项目记录 | inspectStandard={}", routeDetail.getInspectStandard());
                }
            }
        }

        log.info("已完成巡检工单创建 | billsInspectCode={}, inspectInstanceId={}, inspectRouteId={}",
                dmsBillsInspectInstance.getBillsInspectCode(), dmsBillsInspectInstance.getInspectInstanceId(),
                dmsBillsInspectInstance.getInspectRouteId());

        return i;
    }

    /**
     * 获取工单设备列表（网页版巡检执行）
     */
    @Override
    public List<DmsInspectInstanceDetail> getDeviceList(Long inspectInstanceId) {
        DmsInspectInstanceDetail query = new DmsInspectInstanceDetail();
        query.setInspectInstanceId(inspectInstanceId);
        return dmsInspectInstanceDetailMapper.selectDmsInspectInstanceDetailJoinList(query);
    }

    /**
     * 更新设备检查状态（简化版，只更新合格/不合格）
     */
    @Override
    @Transactional
    public int updateDeviceStatus(DmsInspectInstanceDetail detail) {
        // 设置时间
        detail.setUpdateTime(new Date());
        detail.setUpdateBy(SecurityUtils.getUserId());

        // 更新设备明细状态
        int result = dmsInspectInstanceDetailMapper.updateDmsInspectInstanceDetail(detail);

        // 检查是否所有设备都已检查完成，更新工单状态
        DmsInspectInstanceDetail query = new DmsInspectInstanceDetail();
        query.setInspectInstanceId(detail.getInspectInstanceId());
        List<DmsInspectInstanceDetail> details = dmsInspectInstanceDetailMapper.selectDmsInspectInstanceDetailList(query);

        int completedCount = 0;
        for (DmsInspectInstanceDetail d : details) {
            if (d.getInstanceDetailStatus() != null && d.getInstanceDetailStatus().equals("3")) {
                completedCount++;
            }
        }

        DmsBillsInspectInstance instance = new DmsBillsInspectInstance();
        instance.setInspectInstanceId(detail.getInspectInstanceId());

        if (completedCount == details.size()) {
            // 全部完成
            instance.setInspectStatus("3");
            instance.setRealEndTime(new Date());
        } else if (completedCount > 0) {
            // 巡检中
            instance.setInspectStatus("2");
            if (instance.getRealBeginTime() == null) {
                instance.setRealBeginTime(new Date());
            }
        }

        dmsBillsInspectInstanceMapper.updateDmsBillsInspectInstance(instance);

        return result;
    }

}
