package cn.cecep.talroad.service.impl.effective;

import cn.cecep.talroad.common.core.exception.BussinessException;
import cn.cecep.talroad.common.security.utils.SecurityUtils;
import cn.cecep.talroad.domain.PCodeAreaInfo;
import cn.cecep.talroad.domain.effective.PCodeRegion;
import cn.cecep.talroad.domain.vo.ControlVo;
import cn.cecep.talroad.domain.vo.PCodeStationVo;
import cn.cecep.talroad.mapper.PCodAreaInfoMapper;
import cn.cecep.talroad.mapper.effective.PCodeRegionMapper;
import cn.cecep.talroad.mapper.effective.SEnvgasPollutantMapper;
import cn.cecep.talroad.service.effective.IPCodAreaInfoService;
import cn.cecep.talroad.util.effective.JavaBeanUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

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

import static cn.cecep.talroad.util.effective.DateUtil.*;


/**
 * <p>
 * 自定义区域表
 * 服务实现类
 * </p>
 *
 * @author author
 * @since 2022-07-13
 */
@Service
public class PCodAreaInfoServiceImpl extends ServiceImpl<PCodAreaInfoMapper, PCodeAreaInfo> implements IPCodAreaInfoService {
    @Autowired
    private PCodAreaInfoMapper pCodAreaInfoMapper;
    @Autowired
    private PCodeRegionMapper pCodeRegionMapper;
    @Autowired
    private PCodeRegionMapper sEnvgasRegionMapper;
    @Autowired
    private SEnvgasPollutantMapper sEnvgasPollutantMapper;
    @Override
    public List<ControlVo> findStationPullDataList() {
        String regionCode = SecurityUtils.getLoginUser().getSysUser().getRegionCode();
        List<String> list = Lists.newArrayList();
        list.add(regionCode);
        //获取所属那些站点
        List<ControlVo> controlVoList = pCodAreaInfoMapper.findDataPollution(list, "1", "2");
        //如果 当前没有数据 设置默认值 为国控 省控 市控  微站 都可以看到
        if (CollectionUtils.isEmpty(controlVoList)) {
            controlVoList = pCodAreaInfoMapper.findDataPollution(Arrays.asList(new String[]{"999999"}), "1", "2");
        }
        if (!CollectionUtils.isEmpty(controlVoList)) {
            //获取区域站点
            List<String> levelCodeList = controlVoList.stream().distinct().map(ControlVo::getLevelCode).collect(Collectors.toList());
            //获取区域
            List<PCodeStationVo> areaList = sEnvgasRegionMapper.findStationPullDataList(regionCode, levelCodeList);
            if (!CollectionUtils.isEmpty(areaList)) {
                Map<Integer, List<PCodeStationVo>> collect = areaList.stream().collect(Collectors.groupingBy(PCodeStationVo::getStationLevel));
                //取出编码id
                for (ControlVo controlVo : controlVoList) {
                    List<PCodeStationVo> listData =Lists.newArrayList();
                    for (Integer integer : collect.keySet()) {
                        if (Objects.nonNull(integer) && controlVo.getLevelCode().equals(integer.toString())) {
                            List<PCodeStationVo> pCodeStationVos = collect.get(integer);
                            if(!CollectionUtils.isEmpty(pCodeStationVos)) {
                                listData.addAll(pCodeStationVos);
                            }
                        }
                    }
                    controlVo.setChildren(listData);
                }
            }
        }
        return controlVoList;
    }

    @Override
    public List<Map<String, Object>> findJurisdictionData() {
        String regionCode = SecurityUtils.getLoginUser().getSysUser().getRegionCode();
        return pCodAreaInfoMapper.findJurisdictionData(regionCode);
    }

    /**
     * @Method 因子
     * @Author wyg
     * @Version  1.0
     * @Description * @param null
     * @Return
     * @Exception
     * @Date 2023/6/14 10:21
     */
    @Override
    public List<Map<String,Object>> selectBySixApiParam(String type, String property) {
        List<String> maps = new ArrayList<>();
        //property 1小时 2日均 3月均  a05025 O3_8H   a05024 O₃
        if ("1".equals(property)) {
            String[] mapsList = {"aqi", "a21026", "a21004", "a21005", "a34002", "a34004", "a05024"};
            maps.addAll(Arrays.asList(mapsList));
        } else if ("2".equals(property)) {
            String[] mapsList = {"aqi", "a21026", "a21004", "a21005", "a34002", "a34004", "a05025"};
            maps.addAll(Arrays.asList(mapsList));
        } else if ("3".equals(property)) {
            String[] mapsList = {"aqi", "a21026", "a21004", "a21005", "a34002", "a34004", "a05025"};
            maps.addAll(Arrays.asList(mapsList));
        } else {
            // 类型 1：区域 2：站点
            if ("1".equals(type)) {
                String[] mapsList = {"aqi", "a21026", "a21004", "a21005", "a34002", "a34004", "a05024"};
                maps.addAll(Arrays.asList(mapsList));
            } else if ("2".equals(type)) {
                String[] mapsList = {"aqi", "a21026", "a21004", "a21005", "a34002", "a34004", "a05024"};
                maps.addAll(Arrays.asList(mapsList));
            }
        }
        return sEnvgasPollutantMapper.selectBySixApiParam(maps);
    }

  /**
   * @Method 时间区域
   * @Author wyg
   * @Date 2023/6/14 10:21
   */
    @Override
    public Map findTimeDataList(String startTime, String endTime, String type, String factorCode, String regionCode) {
        List<String> timeList = Lists.newArrayList();
        List<String> noTimeList = Lists.newArrayList();
        if ("1".equals(type)) {
            startTime = startTime.replace("%20", " ");
            endTime = endTime.replace("%20", " ");
            //小时
            Date startTimeDate = stringToDate(startTime, "yyyy-MM-dd HH");
            Date endTimeDate = stringToDate(endTime, "yyyy-MM-dd HH");
            timeList = getAllHours(startTimeDate, endTimeDate, "yyyy-MM-dd HH:00:00");
            if (timeList.size() > 24) {
                throw new BussinessException("小时不能超过24小时，请重新选择!");
            }
        } else if ("2".equals(type)) {
            Date startTimeDate = stringToDate(startTime, "yyyy-MM-dd");
            Date endTimeDate = stringToDate(endTime, "yyyy-MM-dd");
            timeList = getAllDays(startTimeDate, endTimeDate);
            if (timeList.size() > 32) {
                throw new BussinessException("天不能超过31天，请重新选择!");
            }
        } else if ("3".equals(type)) {
            Date startTimeDate = stringToDate(startTime + "-01", "yyyy-MM-dd");
            Date endTimeDate = stringToDate(endTime + "-01", "yyyy-MM-dd");
            timeList = getAllMonths(startTimeDate, endTimeDate);
            if (timeList.size() > 13) {
                throw new BussinessException("月不能超过12个月，请重新选择!");
            }
        }
        Map<String, Object> map = new HashMap<>();
        map.put("allTimeList", timeList);
        map.put("noTimeList", noTimeList);
        map.put("valueTimeList", timeList);
        return map;
    }

    /**
     * @Method 时间分布特征-插值图/渲染图-区域范围
     * @Author wyg
     * @Date 2023/6/14 10:21
     */
    @Override
    public List<Map<String,Object>> findCoverageData() {
        String regionCode = SecurityUtils.getLoginUser().getSysUser().getRegionCode();
//      市级账号-xx省、xx市；区县账号-xx市、xx区（以街镇数据进行插值
        List<Map<String,Object>> pCodeRegions =Lists.newArrayList();
        PCodeRegion pCode = pCodeRegionMapper.selectOne(new QueryWrapper<PCodeRegion>().eq("region_code", regionCode).eq("delete_flag", "0"));
        Map<String, Object> regionInfo = JavaBeanUtils.beanToMap(pCode);
        Map<String, BigDecimal> regionMapConfig = pCodeRegionMapper.selectMapConig(regionCode);
        if (Objects.nonNull(regionMapConfig)) {
            regionInfo.putAll(regionMapConfig);
        }

        PCodeRegion pCodeRegion = pCodeRegionMapper.selectOne(new QueryWrapper<PCodeRegion>().eq("region_code", pCode.getParentCode()).eq("delete_flag", "0"));
        Map<String, Object> parentInfo = JavaBeanUtils.beanToMap(pCodeRegion);
        Map<String, BigDecimal> parentMapConfig = pCodeRegionMapper.selectMapConig(pCodeRegion.getRegionCode());
        if (Objects.nonNull(parentMapConfig)) {
            parentInfo.putAll(parentMapConfig);
        }

        PCodeRegion top = pCodeRegionMapper.selectOne(new QueryWrapper<PCodeRegion>().eq("region_code", pCodeRegion.getParentCode()).eq("delete_flag", "0"));
        if (top != null) {
            Map<String, Object> map = JavaBeanUtils.beanToMap(top);
            Map<String, BigDecimal> config = pCodeRegionMapper.selectMapConig(top.getRegionCode());
            if (Objects.nonNull(config)) {
                map.putAll(config);
            }
            pCodeRegions.add(map);
        }
        pCodeRegions.add(parentInfo);
        pCodeRegions.add(regionInfo);
        return pCodeRegions;
    }
}
