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

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.njcn.common.pojo.exception.BusinessException;
import com.njcn.supervision.mapper.plan.SupervisionPlanPOMapper;
import com.njcn.supervision.mapper.plan.SupervisionProblemPOMapper;
import com.njcn.supervision.pojo.param.plan.SupervisopnProblemParam;
import com.njcn.supervision.pojo.po.plan.SupervisionPlanPO;
import com.njcn.supervision.pojo.po.plan.SupervisionProblemPO;
import com.njcn.supervision.service.plan.SupervisionProblemPOService;
import com.njcn.user.api.DeptFeignClient;
import com.njcn.user.pojo.vo.PvTerminalTreeVO;
import com.njcn.web.factory.PageFactory;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * Description:
 * Date: 2024/5/20  19:50【需求编号】
 *
 * @author clam
 * @version V1.0.0
 */
@Service
@RequiredArgsConstructor
public class SupervisionProblemPOServiceImpl extends ServiceImpl<SupervisionProblemPOMapper, SupervisionProblemPO> implements SupervisionProblemPOService {


    private final SupervisionPlanPOMapper supervisionPlanPOMapper;

    private final DeptFeignClient deptFeignClient;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addProblem(SupervisopnProblemParam supvProblemParam) {
        checkParam(supvProblemParam.getPlanId(), supvProblemParam.getDiscoveryTime());
        SupervisionProblemPO supvProblem = new SupervisionProblemPO();
        BeanUtil.copyProperties(supvProblemParam, supvProblem);
        supvProblem.setPlanRectificationTime(LocalDateTimeUtil.parse(supvProblemParam.getPlanRectificationTime(), DatePattern.NORM_DATETIME_PATTERN));
        if (StrUtil.isNotBlank(supvProblemParam.getRectificationTime())) {
            supvProblem.setRectificationTime(LocalDateTimeUtil.parse(supvProblemParam.getRectificationTime(), DatePattern.NORM_DATETIME_PATTERN));
        }
        this.save(supvProblem);
    }

    @Override
    public Page<SupervisionProblemPO> pageProblem(SupervisopnProblemParam supvProblemParam) {


        LambdaQueryWrapper<SupervisionProblemPO> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(SupervisionProblemPO::getPlanId, supvProblemParam.getPlanId());
        Page<SupervisionProblemPO> page = this.page(new Page<>(PageFactory.getPageNum(supvProblemParam), PageFactory.getPageSize(supvProblemParam)), lambdaQueryWrapper);

        List<PvTerminalTreeVO> deptList = deptFeignClient.allDeptList().getData();
        Map<String, PvTerminalTreeVO> mapCode = deptList.stream().collect(Collectors.toMap(PvTerminalTreeVO::getCode, Function.identity()));

        for (SupervisionProblemPO item : page.getRecords()) {
            if (mapCode.containsKey(item.getDutyOrgId())) {
                item.setDutyOrgName(mapCode.get(item.getDutyOrgId()).getName());
            }

//            DictData stamped_report = dicDataFeignClient.getDicDataByCode("Stamped_Report").getData();
//            List<SupvFile> supvFileList = supvFileMapper.selectList(new LambdaQueryWrapper<SupvFile>().eq(SupvFile::getBusiId, item.getProblemId()).eq(SupvFile::getType, 1));
//            if (CollUtil.isNotEmpty(supvFileList)) {
//                for(SupvFile supvFile:supvFileList){
//                    if(supvFile.getAttachmentType().equals(stamped_report.getId())){
//                        item.setAttachmentName(supvFile.getAttachmentName());
//                    }else {
//                        item.setAttachmentNameTwo(supvFile.getAttachmentName());
//                    }
//
//                }
//            }

        }
        return page;
    }

    /**
     * 判断是否存在时间范围内
     */
    public void checkParam(String id, String time) {
        if (StrUtil.isNotBlank(time)) {
            SupervisionPlanPO supvPlan = supervisionPlanPOMapper.selectById(id);
            if (ObjectUtil.isNotNull(supvPlan)) {
                //判断时间范围
                if (ObjectUtil.isAllNotEmpty(supvPlan.getEffectStartTime(), supvPlan.getEffectEndTime()) ||
                        ObjectUtil.isAllNotEmpty(supvPlan.getEffectStartTime(), supvPlan.getReportIssueTime())
                ) {
                    //实施开始时间
                    DateTime effectStartTime = DateUtil.parse(DateUtil.formatLocalDateTime(supvPlan.getEffectStartTime()), "yyyy-MM-dd HH:mm:ss");
                    //问题发现时间
                    DateTime problemOcTime = DateUtil.parse(time, "yyyy-MM-dd HH:mm:ss");
                    boolean fly = false;
                    if (ObjectUtil.isNotNull(supvPlan.getEffectEndTime())) {
                        //实施结束时间
                        DateTime effectEndTime = DateUtil.parse(DateUtil.formatLocalDateTime(supvPlan.getEffectEndTime()), "yyyy-MM-dd HH:mm:ss");
                        if (DateUtil.isIn(problemOcTime, effectStartTime, effectEndTime)) {
                            fly = true;
                        }
                    }
                    if (ObjectUtil.isNotNull(supvPlan.getReportIssueTime())) {
                        //报告出具时间
                        DateTime reportIssueTime = DateUtil.parse(DateUtil.formatLocalDateTime(supvPlan.getReportIssueTime()), "yyyy-MM-dd HH:mm:ss");
                        if (DateUtil.isIn(problemOcTime, effectStartTime, reportIssueTime)) {
                            fly = true;
                        }
                    }
                    if (!fly) {
                        throw new BusinessException("问题发现时时间，不在实施开始时间到（实施结束时间/报告出具时间）范围内");

                    }
                }
            }
        }

    }
}
