package com.hw.dms.service.impl;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

import com.hw.common.core.constant.DmsConstants;
import com.hw.common.core.constant.SecurityConstants;
import com.hw.common.core.constant.WfConstants;
import com.hw.common.core.exception.ServiceException;
import com.hw.common.core.utils.DateUtils;
import com.hw.common.core.utils.uuid.Seq;
import com.hw.common.security.utils.SecurityUtils;
import com.hw.dms.domain.*;
import com.hw.dms.mapper.DmsBillsMaintDetailMapper;
import com.hw.dms.mapper.DmsMaintInstanceActivityMapper;
import com.hw.dms.mapper.DmsPlanMaintMapper;
import com.hw.system.api.RemoteSysCommonService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.hw.dms.mapper.DmsBillsMaintInstanceMapper;
import com.hw.dms.service.IDmsBillsMaintInstanceService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 保养工单Service业务层处理
 *
 * @author Open Platform
 * @date 2024-02-29
 */
@Service
public class DmsBillsMaintInstanceServiceImpl implements IDmsBillsMaintInstanceService {
    @Autowired
    private DmsBillsMaintInstanceMapper dmsBillsMaintInstanceMapper;
    @Autowired
    private DmsPlanMaintMapper dmsPlanMaintMapper;
    @Autowired
    private DmsMaintInstanceActivityMapper dmsMaintInstanceActivityMapper;
    @Autowired
    private DmsBillsMaintDetailMapper dmsBillsMaintDetailMapper;

    @Autowired
    private RemoteSysCommonService remoteSysCommonService;

    /**
     * 查询保养工单
     *
     * @param maintInstanceId 保养工单主键
     * @return 保养工单
     */
    @Override
    public DmsBillsMaintInstance selectDmsBillsMaintInstanceByMaintInstanceId(Long maintInstanceId) {
        return dmsBillsMaintInstanceMapper.selectDmsBillsMaintInstanceByMaintInstanceId(maintInstanceId);
    }

    /**
     * 查询保养工单列表
     *
     * @param dmsBillsMaintInstance 保养工单
     * @return 保养工单
     */
    @Override
    public List<DmsBillsMaintInstance> selectDmsBillsMaintInstanceList(DmsBillsMaintInstance dmsBillsMaintInstance) {
        return dmsBillsMaintInstanceMapper.selectDmsBillsMaintInstanceList(dmsBillsMaintInstance);
    }

    /**
     * 新增保养工单
     *
     * @param planMaintCode 保养计划编号
     * @return 结果
     */
    @Override
    @Transactional
    public int insertDmsBillsMaintInstance(String planMaintCode) {
        String planMaintCodeS = planMaintCode.replaceAll("\"", "");
        DmsPlanMaint dmsPlanMaint = dmsPlanMaintMapper.selectDmsPlanMaintJoinByPlanMaintCode(planMaintCodeS);
        List<DmsPlanMaintDetail> planMaintDetails = dmsPlanMaint.getDmsPlanMaintDetailList();
        if (planMaintDetails == null || planMaintDetails.isEmpty()) {
            return 0;
        }

        DmsBillsMaintInstance dmsBillsMaintInstance = new DmsBillsMaintInstance();

        dmsBillsMaintInstance.setCreateTime(DateUtils.getNowDate());
        dmsBillsMaintInstance.setPlanBeginTime(dmsPlanMaint.getMaintTime());
        dmsBillsMaintInstance.setPlanMaintId(dmsPlanMaint.getPlanMaintId());
        dmsBillsMaintInstance.setBillsMaintCode(Seq.getId(Seq.maintInstanceSeqType, Seq.maintInstanceCode));
        dmsBillsMaintInstance.setMaintStatus(DmsConstants.DMS_BILLS_MAINT_INSTANCE_STATUS_TO_MAINT);
        dmsBillsMaintInstance.setMaintGroup(dmsPlanMaint.getMaintGroup());
        dmsBillsMaintInstance.setMaintSupervisor(dmsPlanMaint.getMaintSupervisor());
        dmsBillsMaintInstance.setMaintLevel(dmsPlanMaint.getMaintLevel());

        Date lubeTime = dmsPlanMaint.getMaintTime();
        Long timeLimit = dmsPlanMaint.getTimeLimit();
        dmsBillsMaintInstance.setIsFlag(1l);
        dmsBillsMaintInstance.setWfProcessId(103l);
        dmsBillsMaintInstance.setPlanEndTime(new Date(lubeTime.getTime() + timeLimit * 1000l));
        int i = dmsBillsMaintInstanceMapper.insertDmsBillsMaintInstance(dmsBillsMaintInstance);

        batchInsertDmsBillsMaintDetail(dmsPlanMaint, dmsBillsMaintInstance.getMaintInstanceId());
        return i;
    }

    public void batchInsertDmsBillsMaintDetail(DmsPlanMaint dmsPlanMaint, Long maintInstanceId) {
        List<DmsPlanMaintDetail> planMaintDetails = dmsPlanMaint.getDmsPlanMaintDetailList();
        List<DmsBillsMaintDetail> billsMaintDetails = new ArrayList<>();
        planMaintDetails.forEach(planMaintDetail -> {
            DmsBillsMaintDetail dmsBillsMaintDetail = new DmsBillsMaintDetail();
            dmsBillsMaintDetail.setMaintInstanceId(maintInstanceId);
            dmsBillsMaintDetail.setDeviceId(planMaintDetail.getDeviceId());
            dmsBillsMaintDetail.setStationId(planMaintDetail.getMaintStationId());
            dmsBillsMaintDetail.setMaintStandardId(planMaintDetail.getMaintStandardId());
            dmsBillsMaintDetail.setIsFlag(1L);
            billsMaintDetails.add(dmsBillsMaintDetail);
        });

        dmsBillsMaintInstanceMapper.batchDmsBillsMaintDetail(billsMaintDetails);
    }

    @Override
    public int updateDmsBillsMaintInstance(DmsBillsMaintInstance dmsBillsMaintInstance) {
        dmsBillsMaintInstance.setUpdateTime(DateUtils.getNowDate());
        return dmsBillsMaintInstanceMapper.updateDmsBillsMaintInstance(dmsBillsMaintInstance);
    }

    /**
     * 批量删除保养工单
     *
     * @param maintInstanceIds 需要删除的保养工单主键
     * @return 结果
     */
    @Override
    public int deleteDmsBillsMaintInstanceByMaintInstanceIds(Long[] maintInstanceIds) {
        return dmsBillsMaintInstanceMapper.deleteDmsBillsMaintInstanceByMaintInstanceIds(maintInstanceIds);
    }

    /**
     * 删除保养工单信息
     *
     * @param maintInstanceId 保养工单主键
     * @return 结果
     */
    @Override
    public int deleteDmsBillsMaintInstanceByMaintInstanceId(Long maintInstanceId) {
        return dmsBillsMaintInstanceMapper.deleteDmsBillsMaintInstanceByMaintInstanceId(maintInstanceId);
    }

    @Override
    public int insertDmsBillsMaintInstancePDA(DmsBillsMaintInstance dmsBillsMaintInstance) {
        Long aLong = remoteSysCommonService.selectProcessActivityIdByWfProcessId(SecurityConstants.INNER, 103l);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHH");
        dmsBillsMaintInstance.setWfProcessId(103l);
        dmsBillsMaintInstance.setBillsMaintCode(sdf.format(DateUtils.getNowDate()));
        dmsBillsMaintInstance.setMaintStatus(1l);
        dmsBillsMaintInstance.setIsFlag(1l);
        int i = dmsBillsMaintInstanceMapper.insertDmsBillsMaintInstance(dmsBillsMaintInstance);
        //创建保养工单实例节点第一步
        DmsMaintInstanceActivity dmsMaintInstanceActivity = new DmsMaintInstanceActivity();
        dmsMaintInstanceActivity.setMaintInstanceId(dmsBillsMaintInstance.getMaintInstanceId());
        dmsMaintInstanceActivity.setProcessActivityId(aLong);
        dmsMaintInstanceActivity.setMaintGroup(dmsBillsMaintInstance.getMaintGroup());
        dmsMaintInstanceActivity.setMaintLevel(dmsBillsMaintInstance.getMaintLevel());
        dmsMaintInstanceActivity.setMaintSupervisor(dmsBillsMaintInstance.getMaintSupervisor());
        dmsMaintInstanceActivity.setProcessStepOrder(1l);
        dmsMaintInstanceActivity.setProcessHandleStatus("1");
        dmsMaintInstanceActivityMapper.insertDmsMaintInstanceActivity(dmsMaintInstanceActivity);
        return i;
    }


    /**
     * 获取最新一条未完成的保养工单
     *
     * @param dmsBillsMaintInstance
     * @return
     */
    @Override
    public DmsBillsMaintInstance getNewestBillsMaintInstance(DmsBillsMaintInstance dmsBillsMaintInstance) {
        dmsBillsMaintInstance.setMaintStatusStr(DmsConstants.DMS_BILLS_MAINT_INSTANCE_STATUS_TO_MAINT
                + "," + DmsConstants.DMS_BILLS_MAINT_INSTANCE_STATUS_MAINTING);
        DmsBillsMaintInstance newestBillsMaintInstance = dmsBillsMaintInstanceMapper
                .selectNewestDmsBillsMaintInstance(dmsBillsMaintInstance);
        if (newestBillsMaintInstance != null) {
            DmsBillsMaintDetail queryBillsMaintDetail = new DmsBillsMaintDetail();
            queryBillsMaintDetail.setMaintInstanceId(newestBillsMaintInstance.getMaintInstanceId());
            List<DmsBillsMaintDetail> dmsBillsMaintDetails = dmsBillsMaintDetailMapper.selectDmsBillsMaintDetailJoinList(queryBillsMaintDetail);
            newestBillsMaintInstance.setDmsBillsMaintDetailList(dmsBillsMaintDetails);
        }

        return newestBillsMaintInstance;
    }


    /**
     * 开始保养
     *
     * @param dmsBillsMaintDetail 保养工单明细
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int startMaint(DmsBillsMaintDetail dmsBillsMaintDetail) {
        DmsBillsMaintInstance dmsBillsMaintInstance = dmsBillsMaintInstanceMapper.
                selectDmsBillsMaintInstanceByMaintInstanceId(dmsBillsMaintDetail.getMaintInstanceId());
        Long maintStatus = dmsBillsMaintInstance.getMaintStatus() == null ?
                DmsConstants.DMS_BILLS_MAINT_INSTANCE_STATUS_TO_MAINT : dmsBillsMaintInstance.getMaintStatus();
        if (maintStatus.equals(DmsConstants.DMS_BILLS_MAINT_INSTANCE_STATUS_COMPLETE)) {//保养完成
            throw new ServiceException("已经保养完成");
        }

        Date currentDate = new Date();
        String userName = SecurityUtils.getUsername();

        if (maintStatus.equals(DmsConstants.DMS_BILLS_MAINT_INSTANCE_STATUS_TO_MAINT)) {//待保养
            dmsBillsMaintInstance.setMaintStatus(DmsConstants.DMS_BILLS_MAINT_INSTANCE_STATUS_MAINTING);
            dmsBillsMaintInstance.setRealBeginTime(currentDate);
            dmsBillsMaintInstance.setUpdateTime(currentDate);
            dmsBillsMaintInstance.setUpdateBy(userName);
            dmsBillsMaintInstanceMapper.updateDmsBillsMaintInstance(dmsBillsMaintInstance);

            dmsBillsMaintDetail.setBeginTime(currentDate);
            dmsBillsMaintDetail.setUpdateBy(userName);
            dmsBillsMaintDetail.setUpdateTime(currentDate);
            dmsBillsMaintDetail.setMaintStatus(DmsConstants.DMS_BILLS_MAINT_INSTANCE_STATUS_MAINTING);

            dmsBillsMaintDetailMapper.updateDmsBillsMaintDetail(dmsBillsMaintDetail);

        } else {//保养中
            dmsBillsMaintDetail.setUpdateBy(userName);
            dmsBillsMaintDetail.setUpdateTime(currentDate);
            dmsBillsMaintDetailMapper.updateDmsBillsMaintDetail(dmsBillsMaintDetail);
        }

        return 1;
    }


    /**
     * 完成保养
     *
     * @param dmsBillsMaintDetail 保养工单明细
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int completeMaint(DmsBillsMaintDetail dmsBillsMaintDetail) {
        Long maintInstanceId = dmsBillsMaintDetail.getMaintInstanceId();
        DmsBillsMaintInstance dmsBillsMaintInstance = dmsBillsMaintInstanceMapper.
                selectDmsBillsMaintInstanceByMaintInstanceId(maintInstanceId);
        Long maintStatus = dmsBillsMaintInstance.getMaintStatus() == null ?
                DmsConstants.DMS_BILLS_MAINT_INSTANCE_STATUS_TO_MAINT : dmsBillsMaintInstance.getMaintStatus();
        if (maintStatus.equals(DmsConstants.DMS_BILLS_MAINT_INSTANCE_STATUS_COMPLETE)) {//保养完成
            throw new ServiceException("已经保养完成");
        }

        if (maintStatus.equals(DmsConstants.DMS_BILLS_MAINT_INSTANCE_STATUS_TO_MAINT)) {//待保养
            throw new ServiceException("请先执行开始保养");
        }

        Date currentDate = new Date();
        String userName = SecurityUtils.getUsername();

        DmsBillsMaintDetail queryMaintDetail = new DmsBillsMaintDetail();
        queryMaintDetail.setMaintInstanceId(maintInstanceId);
        List<DmsBillsMaintDetail> maintDetails = dmsBillsMaintDetailMapper.selectDmsBillsMaintDetailList(queryMaintDetail);

        /**获取未完成的保养明细，并且需要排除当前提交完成的保养明细*/
        List<DmsBillsMaintDetail> inCompleteMaintDetails = maintDetails.stream().
                filter(maintDetail -> !maintDetail.getBillsMaintDetailId().equals(dmsBillsMaintDetail.getBillsMaintDetailId())
                        && (maintDetail.getMaintStatus() == null || maintDetail.getMaintStatus().equals("")
                        || maintDetail.getMaintStatus().equals(DmsConstants.DMS_BILLS_MAINT_INSTANCE_STATUS_TO_MAINT)
                        || maintDetail.getMaintStatus().equals(DmsConstants.DMS_BILLS_MAINT_INSTANCE_STATUS_MAINTING))).collect(Collectors.toList());

        /**如果已经没有未完成的，则需要将工单修改成已完成，并更新结束时间*/
        if (inCompleteMaintDetails == null || inCompleteMaintDetails.isEmpty()) {
            dmsBillsMaintInstance.setMaintStatus(DmsConstants.DMS_BILLS_MAINT_INSTANCE_STATUS_COMPLETE);
            dmsBillsMaintInstance.setRealEndTime(currentDate);
            dmsBillsMaintInstance.setUpdateTime(currentDate);
            dmsBillsMaintInstance.setUpdateBy(userName);
            dmsBillsMaintInstanceMapper.updateDmsBillsMaintInstance(dmsBillsMaintInstance);
        }

        dmsBillsMaintDetail.setEndTime(currentDate);
        dmsBillsMaintDetail.setUpdateBy(userName);
        dmsBillsMaintDetail.setUpdateTime(currentDate);
        dmsBillsMaintDetail.setMaintStatus(DmsConstants.DMS_BILLS_MAINT_INSTANCE_STATUS_COMPLETE);

        dmsBillsMaintDetailMapper.updateDmsBillsMaintDetail(dmsBillsMaintDetail);


        return 1;
    }

}
