package com.tofly.xrtygis.custom.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tofly.common.oauth.exception.ToflyDeniedException;
import com.tofly.xrtygis.custom.entity.dto.ItemDto;
import com.tofly.xrtygis.custom.entity.dto.TheMapDto;
import com.tofly.xrtygis.custom.entity.marketing.*;
import com.tofly.xrtygis.custom.mapper.CustomTheMapMapper;
import com.tofly.xrtygis.custom.service.CustomTheMapService;
import com.tofly.xrtygis.custom.util.CallAPIUtil;
import com.tofly.xrtygis.custom.util.CommonMethod;
import com.tofly.xrtygis.entity.Itemtyperato;
import com.tofly.xrtygis.entity.Scadastaitem;
import com.tofly.xrtygis.entity.Scadastation;
import com.tofly.xrtygis.service.DmaregionService;
import com.tofly.xrtygis.service.ItemtyperatoService;
import com.tofly.xrtygis.service.ScadastaitemService;
import com.tofly.xrtygis.service.ScadastationService;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;

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

/**
 * 综合展示-专题图
 *
 * @author 陈浩
 * @date 2021/4/15
 */
@Service
@AllArgsConstructor
public class CustomTheMapServiceImpl implements CustomTheMapService {

    private final CustomTheMapMapper customTheMapMapper;

    private final ScadastaitemService scadastaitemService;

    private final ScadastationService scadastationService;

    private final ItemtyperatoService itemtyperatoService;

    private final DmaregionService dmaregionService;

    /**
     * 用水量专题图-获取全部片区某时间段用水量
     *
     * @param years    年份
     * @param startMon 开始月份
     * @param endMon   结束月份
     * @return list
     */
    @Override
    public Page getAllAreaWater(Page page, String years, String startMon, String endMon) {

        String[] yearArr = years.split(",");

        Map<String, Object> result = new HashMap<>();

        for (String year : yearArr) {
            WaterAreaAll waterArea = new WaterAreaAll();
            waterArea.setACTION("query");

            waterArea.setCWYF_START(year + startMon);
            waterArea.setCWYF_END(year + endMon);

            Map map = new HashMap();
            try {
                map = CallAPIUtil.callAPIUtil(waterArea, "api/Business/GetAreaUsedWater");
            } catch ( Exception e ) {
                e.printStackTrace();
            }
            if (map.get("data") != null) {
                List<AreaUseWaterVo> date = JSONObject.parseArray(map.get("data").toString(), AreaUseWaterVo.class);
                result.put(waterArea.getCWYF_START() + "-" + waterArea.getCWYF_END(), date);
            } else {
                result.put(waterArea.getCWYF_START() + "-" + waterArea.getCWYF_END(), null);
            }
        }
        List<Map> pageList = new ArrayList<>();
        pageList.add(result);
        return CommonMethod.listToPage(page, pageList);
    }

    /**
     * 获取同期水量
     *
     * @param page      page
     * @param startyear 开始年份
     * @param endYear   结束年份
     * @param month     月份
     * @return page
     */
    @Override
    public Page areaComparison(Page page, String startyear, String endYear, String month) {

        List<List> result = new ArrayList();

        WaterArea waterArea = new WaterArea();
        waterArea.setACTION("query");
        waterArea.setCWYF_START(startyear + month);
        waterArea.setCWYF_END(endYear + month);

        CommonParam param = new CommonParam();
        param.setACTION("query");
        //首先查询出所有片区的信息
        Map map = new HashMap();
        try {
            map = CallAPIUtil.callAPIUtil(param, "api/Business/MeterReadingAreas");
        } catch ( Exception e ) {
            e.printStackTrace();
        }
        List<AreaInfoDto> data = JSONObject.parseArray(map.get("data").toString(), AreaInfoDto.class);

        if (data.isEmpty()) {
            throw new ToflyDeniedException("未查询到片区数据");
        }
        //遍历，通过片区编号查询片区用水量
        for (AreaInfoDto info : data) {
            if ("1".equals(info.getYXBZ().toString())) {
                waterArea.setCBPQ(info.getCBPQ_BM().toString());
                Map useWater = new HashMap();
                try {
                    useWater = CallAPIUtil.callAPIUtil(waterArea, "api/Business/GetAreaUsedWater");
                } catch ( Exception e ) {
                    e.printStackTrace();
                }
                List<AreaUseWaterVo> areaUseWater = JSONObject.parseArray(useWater.get("data").toString(), AreaUseWaterVo.class);

                if (areaUseWater.size() == 0) {
                    continue;
                }
                //过滤符合条件每年month月的数据存入list
                List<AreaUseWaterVo> collect = areaUseWater.stream().filter(auw -> auw.getCWYF().substring(4, 6).equals(month)).collect(Collectors.toList());
                result.add(collect);
            }
        }
        return CommonMethod.listToPage(page, result);
    }


    /**
     * 水压水质专题图相关
     *
     * @param tycd  归集id
     * @param start 开始时间
     * @param end   结束时间
     * @return list
     */
    @Override
    public Map<Long, List<Double>> viewWaterTheMap(String tycd, String start, String end) {

        //查询对应指标类型指标编号和测站id
        List<Scadastaitem> scadastaitems = scadastaitemService.list(Wrappers.<Scadastaitem>lambdaQuery()
                .isNotNull(Scadastaitem::getStationId)
                .eq(Scadastaitem::getTycd, tycd).eq(Scadastaitem::getState, "1")
                .select(Scadastaitem::getId));

        Map<Long, List<Double>> map = new HashMap<>();

        if (!scadastaitems.isEmpty()) {
            //收集指标id
            List<Long> idList = scadastaitems.stream()
                    .map(Scadastaitem::getId).distinct().collect(Collectors.toList());

            //查询对应指标所有数据
            List<ItemDto> data = customTheMapMapper.viewItemInfo(tycd, start, end);
            if (!data.isEmpty()) {
                //根据指标id进行分组
                Map<Long, List<ItemDto>> collect = data.stream().collect(Collectors.groupingBy(ItemDto::getItid));
                idList.forEach(id -> {
                    //如果分组后key包含id
                    if (collect.containsKey(id)) {
                        //取当前value根据时间排序，收集值
                        List<Double> itvalue = collect.get(id)
                                .stream().sorted(Comparator.comparing(ItemDto::getTime))
                                .map(ItemDto::getItval).collect(Collectors.toList());
                        map.put(id, itvalue);
                    }
                });
            }

        }
        return map;
    }

    /**
     * 查询测站信息
     *
     * @param tycd@return list
     */
    @Override
    public List<TheMapDto> viewStationInfo(String tycd, String start, String end) {
        //查询对应类型的指标信息
        List<Scadastaitem> staitem = scadastaitemService.list(Wrappers.<Scadastaitem>lambdaQuery()
                .eq(Scadastaitem::getState, 1)
                .eq(Scadastaitem::getTycd, tycd)
                .isNotNull(Scadastaitem::getStationId).select(Scadastaitem::getStationId, Scadastaitem::getId));

        List<TheMapDto> theMap = new ArrayList<>();

        if (!staitem.isEmpty()) {
            //根据测站id进行分组
            Map<Long, List<Scadastaitem>> listMap = staitem.stream()
                    .sorted(Comparator.comparing(Scadastaitem::getId))
                    .collect(Collectors.groupingBy(Scadastaitem::getStationId));
            //取测站id用于遍历
            List<Long> stationIds = staitem.stream().map(Scadastaitem::getStationId).distinct().collect(Collectors.toList());

            //查询归集频率
            Itemtyperato frequency = itemtyperatoService.getOne(Wrappers.<Itemtyperato>lambdaQuery()
                    .eq(Itemtyperato::getTycd, tycd));

            for (Long stationId : stationIds) {
                Scadastation station = scadastationService.getById(stationId);
                if (station != null) {
                    //取指标id
                    List<Long> itid = listMap.get(stationId).stream().map(Scadastaitem::getId).collect(Collectors.toList());

                    TheMapDto dto = new TheMapDto();
                    dto.setStationid(stationId);
                    dto.setLttd(station.getLttd());
                    dto.setLgtd(station.getLgtd());
                    dto.setSpacing(frequency.getRato());
                    dto.setItemId(itid);
                    dto.setPipeSid(station.getPipeSid());
                    //查询指标编号
                    List<String> itcdList = scadastaitemService.list(Wrappers.<Scadastaitem>lambdaQuery()
                                    .eq(Scadastaitem::getState, 1)
                                    .in(Scadastaitem::getId, itid))
                            .stream().map(Scadastaitem::getItcd).collect(Collectors.toList());

                    dto.setStartTime(customTheMapMapper.getStartTime(itcdList, start, end));

                    theMap.add(dto);
                }
            }
        }


        return theMap;
    }

    /**
     * @param level 等级
     * @param year  年份
     * @param month 月份
     * @return map
     */
    @Override
    public Map<Long, Object> getAreaWater(String level, String year, String month) {
        List<Map> partitions = customTheMapMapper.getPartition(level);
        String[] years = year.split(",");
        List<String> collect = Arrays.stream(month.split(",")).sorted().collect(Collectors.toList());
        if (collect.size() < 2) {
            collect.add(collect.get(0));
        }
        Map<Long, Object> result = new HashMap<>();

        StringBuilder sb;
        for (Map p : partitions) {
            sb = new StringBuilder();
            for (int i = 0; i < years.length; i++) {
                String sql = " select cwyf, sum(ysl) ysl\n" +
                        "        from TF_YWPN_DMAUSERTABLE_W a,\n" +
                        "             TF_YWPN_DMAUSERWATER_W b\n" +
                        "        where a.yhbh = b.yhbh\n" +
                        "          and CWYF between '" + years[i] + collect.get(0) + "' and '" + years[i] + collect.get(1) + "'\n" +
                        "          and instr(dma_ids,'" + p.get("dmaGid").toString() + "') > 0\n" +
                        "        group by cwyf ";

                if (i == years.length - 1) {
                    sb.append(sql);
                } else {
                    sb.append(sql).append(" union all ");
                }
            }
            result.put(Long.parseLong(p.get("id").toString()), customTheMapMapper.getAllUseWater(sb.toString()));
        }
        return result;
    }
}
