package com.hw.dms.service.impl;

import java.nio.file.Files;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.hw.common.core.constant.DmsConstants;
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.DmsFaultInstanceActivity;
import com.hw.dms.domain.DmsInstanceFile;
import com.hw.dms.domain.vo.DmsBillsFaultInstanceScanVo;
import com.hw.dms.mapper.DmsFaultInstanceActivityMapper;
import com.hw.dms.mapper.DmsInstanceFileMapper;
import com.hw.system.api.domain.SysFile;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.hw.dms.mapper.DmsBillsFaultInstanceMapper;
import com.hw.dms.domain.DmsBillsFaultInstance;
import com.hw.dms.service.IDmsBillsFaultInstanceService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 报修工单Service业务层处理
 *
 * @author Open Platform
 * @date 2024-01-23
 */
@Service
public class DmsBillsFaultInstanceServiceImpl implements IDmsBillsFaultInstanceService {
    @Autowired
    private DmsBillsFaultInstanceMapper dmsBillsFaultInstanceMapper;
    @Autowired
    private DmsFaultInstanceActivityMapper dmsFaultInstanceActivityMapper;
    @Autowired
    private DmsInstanceFileMapper dmsInstanceFileMapper;


    /**
     * 查询报修工单
     *
     * @param repairInstanceId 报修工单主键
     * @return 报修工单
     */
    @Override
    public DmsBillsFaultInstance selectDmsBillsFaultInstanceByRepairInstanceId(Long repairInstanceId) {
//        DmsFaultInstanceActivity dmsFaultInstanceActivity = dmsFaultInstanceActivityMapper.selectDmsFaultInstanceActivityByRepairIdMin(repairInstanceId);
//        DmsBillsFaultInstance dmsBillsFaultInstance = dmsBillsFaultInstanceMapper.selectDmsBillsFaultInstanceByRepairInstanceId(repairInstanceId);
        DmsBillsFaultInstance dmsBillsFaultInstance = dmsBillsFaultInstanceMapper.selectFaultInstanceJoinFirstAndDeviceById(repairInstanceId);
        DmsInstanceFile queryInstanceFile = new DmsInstanceFile();
        queryInstanceFile.setTargetType(DmsConstants.DMS_INSTANCE_FILE_TARGET_TYPE_FAULT_INSTANCE_ACTIVITY);
        queryInstanceFile.setTargetId(dmsBillsFaultInstance.getInstanceActivityId());
        List<DmsInstanceFile> dmsInstanceFiles = dmsInstanceFileMapper.selectDmsInstanceFileList(queryInstanceFile);

        for (DmsInstanceFile dmsInstanceFile : dmsInstanceFiles){
            dmsInstanceFile.setUrl(dmsInstanceFile.getFilePath());
        }
        dmsBillsFaultInstance.setDmsInstanceFiles(dmsInstanceFiles);


//        dmsBillsFaultInstance.setFaultType(dmsFaultInstanceActivity.getFaultType());
//        dmsBillsFaultInstance.setFaultDescription(dmsFaultInstanceActivity.getFaultDescription());
//        dmsBillsFaultInstance.setDesignOperations(dmsFaultInstanceActivity.getDesignOperations());
//        dmsBillsFaultInstance.setDeviceId(dmsFaultInstanceActivity.getDeviceId());
//        dmsBillsFaultInstance.setRepairType(dmsFaultInstanceActivity.getRepairType());

        return dmsBillsFaultInstance;
    }

    /**
     * 查询报修工单列表
     *
     * @param dmsBillsFaultInstance 报修工单
     * @return 报修工单
     */
    @Override
    public List<DmsBillsFaultInstance> selectDmsBillsFaultInstanceList(DmsBillsFaultInstance dmsBillsFaultInstance) {

        return dmsBillsFaultInstanceMapper.selectDmsBillsFaultInstanceList(dmsBillsFaultInstance);
    }

    /**
     * 新增报修工单
     *
     * @param dmsBillsFaultInstance 报修工单
     * @return 结果
     */
    @Transactional
    @Override
    public int insertDmsBillsFaultInstance(DmsBillsFaultInstance dmsBillsFaultInstance) {
        Date curretnDate = new Date();
        String userName = SecurityUtils.getUsername();
        dmsBillsFaultInstance.setWfProcessId(WfConstants.WF_BILLS_FAULT_INSTANCE_PROCESS_ID);
        dmsBillsFaultInstance.setApplyUser(userName);
        dmsBillsFaultInstance.setApplyTime(curretnDate);
        dmsBillsFaultInstance.setCreateTime(curretnDate);
        dmsBillsFaultInstance.setCreateBy(userName);
        dmsBillsFaultInstance.setBillsFaultCode(Seq.getId(Seq.dmsBillsFaultInstanceSeqType, Seq.dmsBillsFaultInstanceSeqCode));
        dmsBillsFaultInstance.setBillsStatus(DmsConstants.DMS_BILLS_FAULT_INSTANCE_STATUS_TO_REPAIR);
        dmsBillsFaultInstance.setInstanceType(DmsConstants.DMS_BILLS_FAULT_INSTANCE_TYPE_MAUAL);

        int rows = dmsBillsFaultInstanceMapper.insertDmsBillsFaultInstance(dmsBillsFaultInstance);

        DmsFaultInstanceActivity dmsFaultInstanceActivity = new DmsFaultInstanceActivity();
        dmsFaultInstanceActivity.setRepairInstanceId(dmsBillsFaultInstance.getRepairInstanceId());
        dmsFaultInstanceActivity.setProcessActivityId(WfConstants.WF_BILLS_FAULT_INSTANCE_PROCESS_ACTIVITY_FIRST_ID);
        dmsFaultInstanceActivity.setFaultType(dmsBillsFaultInstance.getFaultType());
        dmsFaultInstanceActivity.setFaultDescription(dmsBillsFaultInstance.getFaultDescription());
        dmsFaultInstanceActivity.setDesignOperations(dmsBillsFaultInstance.getDesignOperations());
        dmsFaultInstanceActivity.setDeviceId(dmsBillsFaultInstance.getDeviceId());
        dmsFaultInstanceActivity.setRepairType(dmsBillsFaultInstance.getRepairType());
        if (dmsBillsFaultInstance.getOutsrcId() != null) {
            dmsFaultInstanceActivity.setOutsrcId(dmsBillsFaultInstance.getOutsrcId());
        }
        dmsFaultInstanceActivity.setProcessHandleStatus(DmsConstants.DMS_BILLS_FAULT_INSTANCE_ACTIVITY_HANDLE_STATUS_TO_PICK);
        dmsFaultInstanceActivity.setProcessStepOrder(1l);
        dmsFaultInstanceActivityMapper.insertDmsFaultInstanceActivity(dmsFaultInstanceActivity);

        //存储图片
        List<String> fileUrls = dmsBillsFaultInstance.getFileUrls();
        batchInsertInstanceFiles(fileUrls, dmsFaultInstanceActivity.getInstanceActivityId());

        return rows;
    }

    /**
     * 修改报修工单
     *
     * @param dmsBillsFaultInstance 报修工单
     * @return 结果
     */
    @Override
    public int updateDmsBillsFaultInstance(DmsBillsFaultInstance dmsBillsFaultInstance) {

        dmsBillsFaultInstance.setUpdateTime(DateUtils.getNowDate());
        dmsInstanceFileMapper.deleteDmsInstanceFileByUpdate(dmsBillsFaultInstance.getRepairInstanceId());
        int i = dmsBillsFaultInstanceMapper.updateDmsBillsFaultInstance(dmsBillsFaultInstance);
        //存储图片
        List<String> fileUrls = dmsBillsFaultInstance.getFileUrls();
        batchInsertInstanceFiles(fileUrls, dmsBillsFaultInstance.getInstanceActivityId());
        return i;
    }

    /**
     * 批量删除报修工单
     *
     * @param repairInstanceIds 需要删除的报修工单主键
     * @return 结果
     */
    @Override
    public int deleteDmsBillsFaultInstanceByRepairInstanceIds(Long[] repairInstanceIds) {
        return dmsBillsFaultInstanceMapper.deleteDmsBillsFaultInstanceByRepairInstanceIds(repairInstanceIds);
    }

    /**
     * 删除报修工单信息
     *
     * @param repairInstanceId 报修工单主键
     * @return 结果
     */
    @Override
    public int deleteDmsBillsFaultInstanceByRepairInstanceId(Long repairInstanceId) {
        return dmsBillsFaultInstanceMapper.deleteDmsBillsFaultInstanceByRepairInstanceId(repairInstanceId);
    }

    /**
     * pda-新增报修工单
     */
    public int insertDmsBillsFaultInstancePDA(DmsBillsFaultInstance dmsBillsFaultInstance) {
        //根据报修流程查询工单流程节点id
        Long aLong = dmsBillsFaultInstanceMapper.selectProcessActivityId(102l);
        int i = dmsBillsFaultInstanceMapper.insertDmsBillsFaultInstance(dmsBillsFaultInstance);
        DmsFaultInstanceActivity dmsFaultInstanceActivity = new DmsFaultInstanceActivity();
        //生成故障报修工单实例节点第一步
        dmsFaultInstanceActivity.setRepairInstanceId(dmsBillsFaultInstance.getRepairInstanceId());
        dmsFaultInstanceActivity.setFaultType(dmsBillsFaultInstance.getFaultType());
        dmsFaultInstanceActivity.setFaultDescription(dmsBillsFaultInstance.getFaultDescription());
        dmsFaultInstanceActivity.setDesignOperations(dmsBillsFaultInstance.getDesignOperations());
        dmsFaultInstanceActivity.setDeviceId(dmsBillsFaultInstance.getDeviceId());
        dmsFaultInstanceActivity.setRepairType(dmsBillsFaultInstance.getRepairType());
        dmsFaultInstanceActivity.setOutsrcId(dmsBillsFaultInstance.getOutsrcId());
        dmsFaultInstanceActivity.setProcessActivityId(aLong);
        dmsFaultInstanceActivity.setProcessStepOrder(1l);
        dmsFaultInstanceActivity.setCreateTime(DateUtils.getNowDate());
        dmsFaultInstanceActivityMapper.insertDmsFaultInstanceActivity(dmsFaultInstanceActivity);
        return i;
    }


    /**
     * 查询报修工单列表，Join 设备
     *
     * @param dmsBillsFaultInstance 报修工单
     * @return 报修工单
     */
    @Override
    public List<DmsBillsFaultInstance> selectDmsBillsFaultInstanceJoinList(DmsBillsFaultInstance dmsBillsFaultInstance) {

        return dmsBillsFaultInstanceMapper.selectDmsBillsFaultInstanceJoinList(dmsBillsFaultInstance);
    }


    /**
     * 获取故障报修工单明细，提供给维修使用
     *
     * @param repairInstanceId
     * @return
     */
    @Override
    public DmsBillsFaultInstance getDmsBillsFaultInstance4Repair(Long repairInstanceId) {
        DmsBillsFaultInstance dmsBillsFaultInstance = dmsBillsFaultInstanceMapper.selectFaultInstanceJoinActivityByRepairInstanceId(repairInstanceId);
        List<DmsFaultInstanceActivity> dmsBillsFaultInstanceActivityList = dmsBillsFaultInstance.getDmsFaultInstanceActivityList();
        DmsFaultInstanceActivity firstStepActivity = dmsBillsFaultInstanceActivityList.get(0);
        DmsFaultInstanceActivity dmsFaultInstanceActivity;
        if (dmsBillsFaultInstanceActivityList.size() == 1) {
            dmsFaultInstanceActivity = firstStepActivity;
        } else {
            dmsFaultInstanceActivity = dmsBillsFaultInstanceActivityList.get(1);
            dmsBillsFaultInstance.setInstanceActivityId(dmsFaultInstanceActivity.getInstanceActivityId());
        }
        dmsBillsFaultInstance.setFaultType(dmsFaultInstanceActivity.getFaultType());
        dmsBillsFaultInstance.setFaultDescription(firstStepActivity.getFaultDescription());
        dmsBillsFaultInstance.setDesignOperations(dmsFaultInstanceActivity.getDesignOperations());
        dmsBillsFaultInstance.setDeviceId(dmsFaultInstanceActivity.getDeviceId());
        dmsBillsFaultInstance.setRepairType(dmsFaultInstanceActivity.getRepairType());
        dmsBillsFaultInstance.setOutsrcId(dmsFaultInstanceActivity.getOutsrcId());
        dmsBillsFaultInstance.setProcessHandleResolution(dmsFaultInstanceActivity.getProcessHandleResolution());

        dmsBillsFaultInstance.setDmsFaultInstanceActivityList(null);

        DmsInstanceFile queryInstanceFile = new DmsInstanceFile();
        queryInstanceFile.setTargetType(DmsConstants.DMS_INSTANCE_FILE_TARGET_TYPE_FAULT_INSTANCE_ACTIVITY);
        queryInstanceFile.setTargetId(firstStepActivity.getInstanceActivityId());
        List<DmsInstanceFile> dmsInstanceFiles = dmsInstanceFileMapper.selectDmsInstanceFileList(queryInstanceFile);
        dmsBillsFaultInstance.setDmsInstanceFiles(dmsInstanceFiles);

        return dmsBillsFaultInstance;
    }


    /**
     * 修改报修工单实例节点
     *
     * @param dmsFaultInstanceActivity 报修工单实例节点
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateDmsFaultInstanceActivity(DmsFaultInstanceActivity dmsFaultInstanceActivity) {

        return dmsFaultInstanceActivityMapper.updateDmsFaultInstanceActivity(dmsFaultInstanceActivity);
    }

    /**
     * 扫描设备编码验证，验证通过后进行维修
     *
     * @param dmsBillsFaultInstanceScanVo
     */
    @Override
    public void scanDevice4Repair(DmsBillsFaultInstanceScanVo dmsBillsFaultInstanceScanVo) {
        Long count = dmsBillsFaultInstanceMapper.selectCountByRepairInstanceIdAndDeviceCode(
                dmsBillsFaultInstanceScanVo.getRepairInstanceId(), dmsBillsFaultInstanceScanVo.getDeviceCode());
        if (count <= 0) {
            throw new ServiceException("扫描验证失败");
        }
    }


    /**
     * 开始维修
     *
     * @param dmsFaultInstanceActivity 报修工单实例节点
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int startRepair(DmsFaultInstanceActivity dmsFaultInstanceActivity) {
        DmsBillsFaultInstance dmsBillsFaultInstance = dmsBillsFaultInstanceMapper
                .selectFaultInstanceJoinFirstById(dmsFaultInstanceActivity.getRepairInstanceId());//join 第一步activity
        String dmsBillsStatus = dmsBillsFaultInstance.getBillsStatus();
        if (dmsBillsStatus.equals(DmsConstants.DMS_BILLS_FAULT_INSTANCE_STATUS_FINISH)) {//维修完成
            throw new ServiceException("已经维修完成");
        }

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

        if (dmsBillsStatus.equals(DmsConstants.DMS_BILLS_FAULT_INSTANCE_STATUS_TO_REPAIR)) {//待维修
            dmsBillsFaultInstance.setBillsStatus(DmsConstants.DMS_BILLS_FAULT_INSTANCE_STATUS_REPAIRING);
            dmsBillsFaultInstance.setRealBeginTime(currentDate);
            dmsBillsFaultInstance.setUpdateTime(currentDate);
            dmsBillsFaultInstance.setUpdateBy(userName);
            dmsBillsFaultInstanceMapper.updateDmsBillsFaultInstance(dmsBillsFaultInstance);

            dmsFaultInstanceActivity.setRepairInstanceId(dmsBillsFaultInstance.getRepairInstanceId());
            dmsFaultInstanceActivity.setProcessActivityId(WfConstants.WF_BILLS_FAULT_INSTANCE_PROCESS_ACTIVITY_SECOND_ID);
            dmsFaultInstanceActivity.setDeviceId(dmsBillsFaultInstance.getDeviceId());
            dmsFaultInstanceActivity.setProcessHandleStatus(DmsConstants.DMS_BILLS_FAULT_INSTANCE_ACTIVITY_HANDLE_STATUS_EXECUTING);
            dmsFaultInstanceActivity.setProcessStepOrder(2L);
            dmsFaultInstanceActivity.setStartTime(currentDate);
            dmsFaultInstanceActivity.setHandleUserId(SecurityUtils.getUserId());
            dmsFaultInstanceActivity.setHandleBy(userName);
            dmsFaultInstanceActivity.setHandleTime(currentDate);
            dmsFaultInstanceActivity.setCreateBy(userName);
            dmsFaultInstanceActivity.setCreateTime(currentDate);

            dmsFaultInstanceActivityMapper.insertDmsFaultInstanceActivity(dmsFaultInstanceActivity);

            DmsFaultInstanceActivity firstInstanceActivity = new DmsFaultInstanceActivity();
            firstInstanceActivity.setInstanceActivityId(dmsBillsFaultInstance.getInstanceActivityId());
            firstInstanceActivity.setProcessHandleStatus(DmsConstants.DMS_BILLS_FAULT_INSTANCE_ACTIVITY_HANDLE_STATUS_FINISH);
            firstInstanceActivity.setEndTime(currentDate);

            dmsFaultInstanceActivityMapper.updateDmsFaultInstanceActivity(firstInstanceActivity);

        } else {//维修中

            dmsFaultInstanceActivityMapper.updateDmsFaultInstanceActivity(dmsFaultInstanceActivity);
        }

        return 1;
    }


    /**
     * 完成维修
     *
     * @param dmsFaultInstanceActivity 报修工单实例节点
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int completeRepair(DmsFaultInstanceActivity dmsFaultInstanceActivity) {
        DmsBillsFaultInstance dmsBillsFaultInstance = dmsBillsFaultInstanceMapper.
                selectDmsBillsFaultInstanceByRepairInstanceId(dmsFaultInstanceActivity.getRepairInstanceId());
        String dmsBillsStatus = dmsBillsFaultInstance.getBillsStatus();
        if (dmsBillsStatus.equals(DmsConstants.DMS_BILLS_FAULT_INSTANCE_STATUS_FINISH)) {//维修完成
            throw new ServiceException("已经维修完成");
        }
        if (dmsBillsStatus.equals(DmsConstants.DMS_BILLS_FAULT_INSTANCE_STATUS_TO_REPAIR)) {//待维修
            throw new ServiceException("请先开始维修");

        }

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

        dmsBillsFaultInstance.setBillsStatus(DmsConstants.DMS_BILLS_FAULT_INSTANCE_STATUS_FINISH);
        dmsBillsFaultInstance.setRealEndTime(currentDate);
        dmsBillsFaultInstance.setUpdateBy(userName);
        dmsBillsFaultInstance.setUpdateTime(currentDate);

        dmsBillsFaultInstanceMapper.updateDmsBillsFaultInstance(dmsBillsFaultInstance);

        dmsFaultInstanceActivity.setProcessHandleStatus(DmsConstants.DMS_BILLS_FAULT_INSTANCE_ACTIVITY_HANDLE_STATUS_FINISH);
        dmsFaultInstanceActivity.setEndTime(currentDate);

        dmsFaultInstanceActivityMapper.updateDmsFaultInstanceActivity(dmsFaultInstanceActivity);

        return 1;
    }


    public void batchInsertInstanceFiles(List<String> fileUrls, Long instanceActivityId) {
        if (fileUrls != null && !fileUrls.isEmpty()) {
            List<DmsInstanceFile> dmsInstanceFiles = new ArrayList<>();
            for (String fileUrl : fileUrls) {
                DmsInstanceFile dmsInstanceFile = new DmsInstanceFile();
                dmsInstanceFile.setTargetId(instanceActivityId);
                dmsInstanceFile.setTargetType(DmsConstants.DMS_INSTANCE_FILE_TARGET_TYPE_FAULT_INSTANCE_ACTIVITY);
                dmsInstanceFile.setFilePath(fileUrl);
                dmsInstanceFiles.add(dmsInstanceFile);
            }
            dmsInstanceFileMapper.batchDmsInstanceFile(dmsInstanceFiles);
        }
    }


}
