package com.hw.dms.service.impl;

import com.hw.common.core.constant.DmsConstants;
import com.hw.common.core.constant.QmsConstants;
import com.hw.common.core.constant.SecurityConstants;
import com.hw.common.core.exception.ServiceException;
import com.hw.common.core.utils.DateUtils;
import com.hw.common.core.utils.StringUtils;
import com.hw.common.security.utils.SecurityUtils;
import com.hw.dms.domain.DmsBillsInspectInstance;
import com.hw.dms.domain.DmsBillsInspectInstanceActivity;
import com.hw.dms.domain.DmsInspectInstanceDetail;
import com.hw.dms.domain.DmsInspectInstanceDetailProject;
import com.hw.dms.domain.vo.DmsBillsInspectInstanceScanVo;
import com.hw.dms.mapper.*;
import com.hw.dms.service.IDmsBillsInspectInstanceService;
import com.hw.system.api.RemoteSysCommonService;
import com.hw.system.api.model.LoginUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
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 {
    @Autowired
    private DmsBillsInspectInstanceMapper dmsBillsInspectInstanceMapper;
    @Autowired
    private DmsBillsInspectInstanceActivityMapper dmsBillsInspectInstanceActivityMapper;
    @Autowired
    private DmsRepairInstanceMapper dmsRepairInstanceMapper;
    @Autowired
    private DmsInspectInstanceDetailMapper dmsInspectInstanceDetailMapper;
    @Autowired
    private DmsInspectInstanceDetailProjectMapper dmsInspectInstanceDetailProjectMapper;
    @Autowired
    private DmsInspectInstanceDetailProjectMapper dmsInspectInstanceDetailPrjectMapper;
    @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
    public int insertDmsBillsInspectInstance(DmsBillsInspectInstance dmsBillsInspectInstance) {
        LoginUser user = SecurityUtils.getLoginUser();
        //写死105，也可根据传入对象的wfprocessid作为传参。
        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(user.getUsername());
        int i = dmsBillsInspectInstanceMapper.insertDmsBillsInspectInstance(dmsBillsInspectInstance);
        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);
        return i;
    }

    /**
     * 修改巡检工单
     *
     * @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);
        }

        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);
        List<DmsInspectInstanceDetailProject> dmsInspectInstanceDetailProjects = dmsInspectInstanceDetailPrjectMapper.selectDmsInspectInstanceDetailProjectJoinList(queryInspectInstanceDetailProject);

        dmsInspectInstanceDetail.setDmsInspectInstanceDetailProjectList(dmsInspectInstanceDetailProjects);

        return dmsInspectInstanceDetail;

    }


    /**
     * 更新点巡检工单明细
     *
     * @param dmsInspectInstanceDetail 点巡检工单明细
     * @return 结果
     */
    @Transactional
    @Override
    public int updateDmsInspectInstanceDetail(DmsInspectInstanceDetail dmsInspectInstanceDetail) {
        String userName = SecurityUtils.getUsername();
        Date currentDate = new Date();
        dmsInspectInstanceDetail.setUpdateTime(currentDate);
        dmsInspectInstanceDetail.setUpdateBy(userName);

        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);
            }
        }

    }

}
