package com.aucma.dms.service.impl;

import com.aucma.common.constant.DmsConstants;
import com.aucma.common.exception.ServiceException;
import com.aucma.common.utils.DateUtils;
import com.aucma.common.utils.SecurityUtils;
import com.aucma.common.utils.uuid.Seq;
import com.aucma.dms.domain.*;
import com.aucma.dms.mapper.*;
import com.aucma.dms.service.IDmsBillsMaintInstanceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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

/**
 * 保养工单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 DmsBillsMaintDetailProjectMapper dmsBillsMaintDetailProjectMapper;

/*    @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);
        DmsMaintInstanceActivity dmsMaintInstanceActivity = new DmsMaintInstanceActivity();
        dmsMaintInstanceActivity.setMaintInstanceId(dmsBillsMaintInstance.getMaintInstanceId());
        dmsMaintInstanceActivity.setProcessStepOrder(1L);
        int i1 = dmsMaintInstanceActivityMapper.insertDmsMaintInstanceActivity(dmsMaintInstanceActivity);
        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);
            dmsBillsMaintDetail.setMaintStatus(1L);
            billsMaintDetails.add(dmsBillsMaintDetail);
        });

        dmsBillsMaintInstanceMapper.batchDmsBillsMaintDetail(billsMaintDetails);
        ArrayList<DmsBillsMaintDetailProject> list1 = new ArrayList<>();
        List<DmsBillsMaintDetail> list = dmsBillsMaintDetailMapper.selectDetailList(maintInstanceId);
        for (DmsBillsMaintDetail detail : list) {
            List<DmsBaseMaintProject> projects = dmsBillsMaintDetailMapper.selectPrjectIds(detail.getStationId());
            for (DmsBaseMaintProject project : projects) {
                DmsBillsMaintDetailProject project1 = new DmsBillsMaintDetailProject();
                project1.setBillsMaintDetailId(detail.getBillsMaintDetailId());
//                DmsBaseMaintStation station = dmsBillsMaintDetailMapper.selectMainStation(detail.getStationId());
                project1.setMaintProjectId(project.getMaintProjectId());
                project1.setMaintProjectName(project.getMaintProjectName());
                project1.setMaintProjectDesc(project.getMaintProjectDesc());
                project1.setMaintProjectStatus("2");
                list1.add(project1);
            }

        }
        dmsBillsMaintInstanceMapper.batchDmsProject(list1);
    }

    @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);
        }
        Long maintLevel = newestBillsMaintInstance.getMaintLevel();
        if (maintLevel == 1) {
            newestBillsMaintInstance.setMaintLevelName("日常保养");
        }
        return newestBillsMaintInstance;
    }


    /**
     * 开始保养
     *
     * @param dmsBillsMaintDetail 保养工单明细
     * @return DmsBillsMaintDetail
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public DmsBillsMaintDetail 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.getLoginUser() == null ?
                SecurityUtils.getUsername() : SecurityUtils.getLoginUser().getUser().getNickName() ;
//        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(SecurityUtils.getUserId());
            dmsBillsMaintInstanceMapper.updateDmsBillsMaintInstance(dmsBillsMaintInstance);

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

            dmsBillsMaintDetailMapper.updateDmsBillsMaintDetail(dmsBillsMaintDetail);

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

        DmsBillsMaintDetailProject queryBillsMaintDetailProject = new DmsBillsMaintDetailProject();
        queryBillsMaintDetailProject.setBillsMaintDetailId(dmsBillsMaintDetail.getBillsMaintDetailId());
        List<DmsBillsMaintDetailProject> dmsBillsMaintDetailProjects = dmsBillsMaintDetailProjectMapper.selectDmsBillsMaintDetailProjectList(queryBillsMaintDetailProject);
        dmsBillsMaintDetail.setDmsBillsMaintDetailProjectList(dmsBillsMaintDetailProjects);
        return dmsBillsMaintDetail;
    }


    /**
     * 完成保养
     *
     * @param dmsBillsMaintDetail 保养工单明细
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int completeMaint(DmsBillsMaintDetail dmsBillsMaintDetail) {
        List<DmsBillsMaintDetailProject> dmsBillsMaintDetailProjects = dmsBillsMaintDetail.getDmsBillsMaintDetailProjectList();
        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.getLoginUser() == null ?
                SecurityUtils.getUsername() : SecurityUtils.getLoginUser().getUser().getNickName();

        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(SecurityUtils.getUserId());
            dmsBillsMaintInstanceMapper.updateDmsBillsMaintInstance(dmsBillsMaintInstance);
        }

        //更新保养工单明细项目信息
        for (DmsBillsMaintDetailProject dmsBillsMaintDetailProject : dmsBillsMaintDetailProjects) {
            dmsBillsMaintDetailProject.setMaintProjectStatus(DmsConstants.DMS_MAINT_PROJECT_STATUS_COMPLETE);
            dmsBillsMaintDetailProject.setCreateTime(currentDate);
            dmsBillsMaintDetail.setCreateBy(SecurityUtils.getUserId());
            dmsBillsMaintDetailProjectMapper.updateDmsBillsMaintDetailProject(dmsBillsMaintDetailProject);
        }

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

        dmsBillsMaintDetailMapper.updateDmsBillsMaintDetail(dmsBillsMaintDetail);


        return 1;
    }

}
