package com.njcn.supervision.service.user.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.njcn.bpm.api.BpmProcessFeignClient;
import com.njcn.bpm.enums.BpmTaskStatusEnum;
import com.njcn.bpm.pojo.dto.BpmInstanceInfo;
import com.njcn.bpm.pojo.dto.BpmProcessInstanceCreateReqDTO;
import com.njcn.common.pojo.enums.common.DataStateEnum;
import com.njcn.common.pojo.exception.BusinessException;
import com.njcn.supervision.enums.SupervisionKeyEnum;
import com.njcn.supervision.mapper.user.UserReportPOMapper;
import com.njcn.supervision.pojo.param.user.UserReportParam;
import com.njcn.supervision.pojo.po.device.SupervisionTempLineDebugPO;
import com.njcn.supervision.pojo.po.device.SupervisionTempLineReport;
import com.njcn.supervision.pojo.po.device.SupervisionTempLineRunTestPO;
import com.njcn.supervision.pojo.po.user.*;
import com.njcn.supervision.service.device.ISupervisionTempLineRunTestService;
import com.njcn.supervision.service.device.SupervisionTempLineDebugPOService;
import com.njcn.supervision.service.device.SupervisionTempLineReportService;
import com.njcn.supervision.service.user.*;
import com.njcn.supervision.utils.InstanceUtil;
import com.njcn.web.utils.RequestUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;


/**
 * <p>
 * 用户档案信息表	 服务实现类
 * </p>
 *
 * @author wr
 * @since 2024-06-26
 */
@Service
@RequiredArgsConstructor
public class UserReportDeleteServiceImpl extends ServiceImpl<UserReportPOMapper, UserReportPO> implements IUserReportDeleteService {

    private final UserReportProjectPOService userReportProjectPOService;
    private final UserReportSubstationPOService userReportSubstationPOService;
    private final UserReportSensitivePOService userReportSensitivePOService;
    private final BpmProcessFeignClient bpmProcessFeignClient;
    private final SupervisionTempLineReportService lineReportService;
    private final SupervisionTempLineDebugPOService lineDebugService;
    private final ISupervisionTempLineRunTestService lineRunTestService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateProcessStatus(String businessId, Integer status) {
        if (Objects.equals(status, BpmTaskStatusEnum.RUNNING.getStatus())) {

            /*
             * 1。删除常态化用户所有信息（）
             * 2.删除绑定监测点信息（根据常态化用户信息找到监测点）
             * 3.删除试运行信息，
             */
            //电网工程类用户额外数据
            userReportProjectPOService.update(new LambdaUpdateWrapper<UserReportProjectPO>()
                    .set(UserReportProjectPO::getState, status)
                    .eq(UserReportProjectPO::getId, businessId));
            //非线性负荷用户 & 新能源发电站用户
            userReportSubstationPOService.update(new LambdaUpdateWrapper<UserReportSubstationPO>()
                    .set(UserReportSubstationPO::getState, 0)
                    .eq(UserReportSubstationPO::getId, businessId));
            // 敏感及重要用户
            userReportSensitivePOService.update(new LambdaUpdateWrapper<UserReportSensitivePO>()
                    .set(UserReportSensitivePO::getState, 0)
                    .eq(UserReportSensitivePO::getId, businessId));
            this.update(new LambdaUpdateWrapper<UserReportPO>()
                    .set(UserReportPO::getState, 0)
                    .eq(UserReportPO::getId, businessId));
            //删除监测点绑定信息
            List<SupervisionTempLineReport> lineList = lineReportService.list(new LambdaQueryWrapper<SupervisionTempLineReport>()
                    .eq(SupervisionTempLineReport::getState, 0)
                    .eq(SupervisionTempLineReport::getUserId, businessId));
            if (CollUtil.isNotEmpty(lineList)) {
                List<String> lineIds = lineList.stream().map(SupervisionTempLineReport::getId).collect(Collectors.toList());
                //删除监测点绑定信息
                lineReportService.update(new LambdaUpdateWrapper<SupervisionTempLineReport>()
                        .set(SupervisionTempLineReport::getState, 0)
                        .eq(SupervisionTempLineReport::getUserId, businessId));
                //删除监测点联调
                lineDebugService.update(new LambdaUpdateWrapper<SupervisionTempLineDebugPO>()
                        .set(SupervisionTempLineDebugPO::getState, 0)
                        .in(SupervisionTempLineDebugPO::getId, lineIds));
                //删除试运行信息
                lineRunTestService.update(new LambdaUpdateWrapper<SupervisionTempLineRunTestPO>()
                        .set(SupervisionTempLineRunTestPO::getState, 0)
                        .in(SupervisionTempLineRunTestPO::getId, lineIds));
            }
            //远程删除监测点信息和监测点详细信息
//            translateClient.terminalSyncDeleteFly(businessId);
        }
        this.lambdaUpdate().set(UserReportPO::getStatus, status).eq(UserReportPO::getId, businessId).update();
    }

    @Override
    public BpmInstanceInfo getInstanceInfo(String businessId) {
        BpmInstanceInfo bpmInstanceInfo = new BpmInstanceInfo();
        UserReportPO byId = this.getById(businessId);
        if (Objects.nonNull(byId)) {
            bpmInstanceInfo.setHistoryInstanceId(byId.getHistoryInstanceId());
            bpmInstanceInfo.setInstanceSign(byId.getProjectName() + "信息删除");
            return bpmInstanceInfo;
        }
        return null;
    }

    /**
     * 该流程不需要了 by 吴瑞
     */
    @Override
    @Deprecated
    public Set<String> getAllRejectInstanceIds() {
        return new HashSet<>();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String addEditor(UserReportParam userReportParam) {
        UserReportPO po = this.getById(userReportParam.getId());
        if (ObjUtil.isNull(po)) {
            throw new BusinessException("当前信息不存在,请确认信息是否存在");
        }
        //处理历史流程id列表
        String historyInstanceIds = InstanceUtil.dealHistoryId(po.getProcessInstanceId(), po.getHistoryInstanceId());
        // 发起 BPM 流程
        Map<String, Object> processInstanceVariables = new HashMap<>(16);
        BpmProcessInstanceCreateReqDTO bpmProcessInstanceCreateReqDTO = new BpmProcessInstanceCreateReqDTO();
        bpmProcessInstanceCreateReqDTO.setProcessDefinitionKey(SupervisionKeyEnum.USER_REPORT_DELETE.getKey());
        bpmProcessInstanceCreateReqDTO.setBusinessKey(userReportParam.getId());
        bpmProcessInstanceCreateReqDTO.setStartUserSelectAssignees(userReportParam.getStartUserSelectAssignees());
        bpmProcessInstanceCreateReqDTO.setVariables(processInstanceVariables);
        String processInstanceId = bpmProcessFeignClient.createProcessInstance(RequestUtil.getUserIndex(), bpmProcessInstanceCreateReqDTO).getData();
        // 将工作流的编号，更新到流程单中
        po.setProcessInstanceId(processInstanceId);
        po.setStatus(BpmTaskStatusEnum.RUNNING.getStatus());
        po.setState(DataStateEnum.ENABLE.getCode());
        //保存历史流程id列表
        po.setHistoryInstanceId(historyInstanceIds);
        if (this.updateById(po)) {
            return userReportParam.getId();
        }
        return "失败";
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String resend(UserReportParam userReportParam) {
        UserReportPO po = this.getById(userReportParam.getId());
        if (ObjUtil.isNull(po)) {
            throw new BusinessException("当前信息不存在,请确认信息是否存在");
        } else {
            if (Objects.equals(po.getStatus(), BpmTaskStatusEnum.APPROVE.getStatus())) {
                throw new BusinessException("当前流程以完成审批,无法重新发起");
            }
        }
        //处理历史流程id列表
        String historyInstanceIds = InstanceUtil.dealHistoryId(po.getProcessInstanceId(), po.getHistoryInstanceId());
        // 发起 BPM 流程
        Map<String, Object> processInstanceVariables = new HashMap<>(16);
        BpmProcessInstanceCreateReqDTO bpmProcessInstanceCreateReqDTO = new BpmProcessInstanceCreateReqDTO();
        bpmProcessInstanceCreateReqDTO.setProcessDefinitionKey(SupervisionKeyEnum.USER_REPORT_DELETE.getKey());
        bpmProcessInstanceCreateReqDTO.setBusinessKey(userReportParam.getId());
        bpmProcessInstanceCreateReqDTO.setStartUserSelectAssignees(userReportParam.getStartUserSelectAssignees());
        bpmProcessInstanceCreateReqDTO.setVariables(processInstanceVariables);
        String processInstanceId = bpmProcessFeignClient.createProcessInstance(RequestUtil.getUserIndex(), bpmProcessInstanceCreateReqDTO).getData();
        // 将工作流的编号，更新到流程单中
        po.setProcessInstanceId(processInstanceId);
        po.setStatus(BpmTaskStatusEnum.RUNNING.getStatus());
        po.setState(DataStateEnum.ENABLE.getCode());
        //保存历史流程id列表
        po.setHistoryInstanceId(historyInstanceIds);
        if (this.updateById(po)) {
            return userReportParam.getId();
        }
        return "失败";
    }

}
