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

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.njcn.common.pojo.enums.common.DataStateEnum;
import com.njcn.common.pojo.enums.response.CommonResponseEnum;
import com.njcn.common.pojo.exception.BusinessException;
import com.njcn.supervision.enums.ProblemTypeEnum;
import com.njcn.supervision.mapper.device.SupervisionTempLineDebugPOMapper;
import com.njcn.supervision.pojo.param.device.SupervisionTempLineDebugParam;
import com.njcn.supervision.pojo.param.leaflet.WarningAddParam;
import com.njcn.supervision.pojo.vo.device.SupervisionDevMainReportVO;
import com.njcn.supervision.pojo.vo.device.SupervisionTempLineDebugVO;
import com.njcn.supervision.pojo.vo.device.SupervisionTempLineRunTestVO;
import com.njcn.supervision.service.device.ISupervisionTempLineRunTestService;
import com.njcn.supervision.service.leaflet.ILineRunTestProblemService;
import com.njcn.supervision.service.leaflet.IWarningLeafletService;
import com.njcn.user.api.DeptFeignClient;
import com.njcn.user.api.UserFeignClient;
import com.njcn.web.factory.PageFactory;
import com.njcn.web.utils.RequestUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

/**
 * @Description: 试运行评估问题 服务实现类
 * @Author: wr
 * @Date: 2024/7/3 9:44
 */
@Service
@RequiredArgsConstructor
public class LineRunTestProblemServiceImpl implements ILineRunTestProblemService {


    private final UserFeignClient userFeignClient;
    private final DeptFeignClient deptFeignClient;
    private final SupervisionTempLineDebugPOMapper lineDebugPOMapper;
    private final IWarningLeafletService warningLeafletService;
    private final ISupervisionTempLineRunTestService lineRunTestService;

    @Override
    public Page<SupervisionTempLineDebugVO> pageProblem(SupervisionTempLineDebugParam.SupervisionTempLineDebugQuery supervisionTempLineDebugQuery) {
        QueryWrapper<SupervisionDevMainReportVO> queryWrapper = new QueryWrapper<>();
        List<String> colleaguesIds = userFeignClient.getColleaguesIdByUserId(RequestUtil.getUserIndex()).getData();
        queryWrapper.in("supervision_temp_line_debug.Create_By", colleaguesIds)
                .eq("supervision_temp_line_debug.state", DataStateEnum.ENABLE.getCode());
        if (StrUtil.isNotBlank(supervisionTempLineDebugQuery.getOrgNo())) {
            /*获取直接下属子单位*/
            List<String> data = deptFeignClient.getDepSonIdtByDeptId(supervisionTempLineDebugQuery.getOrgNo()).getData();
            queryWrapper.in("supervision_temp_line_report.org_id", data);
        }
        //添加上时间范围，如果不是只查询已处理的，时间筛选无效
        if (Objects.nonNull(supervisionTempLineDebugQuery.getSearchBeginTime())&& StringUtils.equals(supervisionTempLineDebugQuery.getDealState(),"1")){
            //添加上时间范围
            queryWrapper.between("supervision_temp_line_run_test_warning.Create_Time",
                    DateUtil.beginOfDay(DateUtil.parse(supervisionTempLineDebugQuery.getSearchBeginTime())),
                    DateUtil.endOfDay(DateUtil.parse(supervisionTempLineDebugQuery.getSearchEndTime())));
        }
        queryWrapper.eq(StringUtils.equals(supervisionTempLineDebugQuery.getDealState(),"0"),"supervision_temp_line_run_test_warning.deal_state",0);
//        queryWrapper.between("supervision_temp_line_run_test_warning.create_time",
//                DateUtil.beginOfDay(DateUtil.parse(supervisionTempLineDebugQuery.getSearchBeginTime())),
//                DateUtil.endOfDay(DateUtil.parse(supervisionTempLineDebugQuery.getSearchEndTime())));
        queryWrapper.orderByDesc("supervision_temp_line_run_test_warning.create_time");
        return lineDebugPOMapper.pageProblem(new Page<>(PageFactory.getPageNum(supervisionTempLineDebugQuery), PageFactory.getPageSize(supervisionTempLineDebugQuery)), queryWrapper);
    }

    @Override
    public void initiateWarningLeaflet(WarningAddParam.Extend warningAddParam) {
        SupervisionTempLineRunTestVO runTestById = lineRunTestService.getRunTestById(warningAddParam.getId());
        if (ObjectUtil.isNull(runTestById)) {
            throw new BusinessException(CommonResponseEnum.FAIL, "无法查询到该信息,请检查信息是否存在!");
        }
        //组装告警单
        String complainteDetail = assembleWarningDetail(runTestById);
        /*
         * 1、预告警单名称，此处暂时用用户名+投诉
         * 2、预告警编号暂时随机by yxb
         * 3、问题类型：1：技术监督管理；2：在线监测超标问题；3：用户投诉；4：现场测试超标，此处是现场测试超标
         * 4、对应问题源id，用于查询详细数据
         * 5、单子类型：1：预警单；2：告警单
         * 6、问题详细描述
         * */
        warningLeafletService.createLeaflet(
                complainteDetail,
                runTestById.getOrgId(),
                IdWorker.get32UUID(),
                warningAddParam.getProblemId(),
                ProblemTypeEnum.SITE_TEST.getCode(),
                warningAddParam.getType(),
                warningAddParam.getIssueDetail(),
                warningAddParam.getReformAdvice(),
                null
        );
    }

    private String assembleWarningDetail(SupervisionTempLineRunTestVO byId) {
        return byId.getPowerSubstationName()
                .concat("_")
                .concat(byId.getMonitoringTerminalName())
                .concat("_")
                .concat(byId.getConnectedBus())
                .concat("_")
                .concat(byId.getLineName())
                .concat("试运行评估问题");
    }
}
