package cn.cecep.talroad.controller;

import cn.cecep.talroad.common.core.exception.CommonException;
import cn.cecep.talroad.common.core.utils.DateUtils;
import cn.cecep.talroad.common.core.utils.poi.ExcelUtil;
import cn.cecep.talroad.common.core.web.controller.BasesController;
import cn.cecep.talroad.common.core.web.domain.AjaxResults;
import cn.cecep.talroad.common.log.annotation.Log;
import cn.cecep.talroad.common.log.enums.BusinessType;
import cn.cecep.talroad.common.security.annotation.RequiresPermissions;
import cn.cecep.talroad.domain.BMainEmissionOnlineMonAir;
import cn.cecep.talroad.domain.BMainEmissionOnlineMonWater;
import cn.cecep.talroad.service.IBMainEmissionOnlineMonAirService;
import cn.cecep.talroad.service.IBMainEmissionOnlineMonWaterService;
import cn.cecep.talroad.util.CustomDateUtil;
import cn.cecep.talroad.vo.BMainEmissionOnlineMonAirVo;
import cn.cecep.talroad.vo.ChartVo;
import cn.cecep.talroad.vo.query.BMainEmissionOnlineMonAirQuery;
import cn.cecep.talroad.vo.query.BMainEmissionOnlineMonWaterQuery;
import cn.hutool.core.bean.BeanUtil;
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.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Maps;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.compress.utils.Lists;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.security.InvalidParameterException;
import java.text.ParseException;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


/**
 * * 开发公司：中节能天融科技有限公司
 * 企业排放信息-在线监测排放趋势-废气Controller 控制层
 *
 * @author szhpt
 * @date 2023-01-31*/
@Api(tags = "企业排放信息-在线监测排放趋势-废气")
@RestController
@RequestMapping("/bmainEmissionOnlineMonAir")
public class BMainEmissionOnlineMonAirController extends BasesController
{
    @Autowired
    private IBMainEmissionOnlineMonAirService bMainEmissionOnlineMonAirService;

    @Autowired
    private IBMainEmissionOnlineMonWaterService bMainEmissionOnlineMonWaterService;

    /**
     * 查询企业排放信息-在线监测排放趋势-监测点列表
     */
    @ApiOperation(value = "污染类别查询监测点位")
    @GetMapping("/pullPoints")
    public AjaxResults<List<Map<String, String>>> pullPollutants(BMainEmissionOnlineMonAirQuery bMainEmissionOnlineMonAir)
    {
        List<Map<String, String>> maps = Lists.newArrayList();
        List<String> polls = Lists.newArrayList();
        if(bMainEmissionOnlineMonAir.getFacts().equals("废气")){
            List<BMainEmissionOnlineMonAir> list = bMainEmissionOnlineMonAirService.list(new QueryWrapper<BMainEmissionOnlineMonAir>().eq("factory_id", bMainEmissionOnlineMonAir.getFactoryId()).isNotNull("mon_name"));
            if(!CollectionUtils.isEmpty(list)){
                polls.addAll(list.stream().map(BMainEmissionOnlineMonAir::getMonName).distinct().collect(Collectors.toList()));
            }
        } else if (bMainEmissionOnlineMonAir.getFacts().equals("废水")){
            List<BMainEmissionOnlineMonWater> list = bMainEmissionOnlineMonWaterService.list(new QueryWrapper<BMainEmissionOnlineMonWater>().eq("factory_id", bMainEmissionOnlineMonAir.getFactoryId()).isNotNull("mon_name"));
            if(!CollectionUtils.isEmpty(list)){
                polls.addAll(list.stream().map(BMainEmissionOnlineMonWater::getMonName).distinct().collect(Collectors.toList()));
            }
        }
        if(!CollectionUtils.isEmpty(polls)){
            polls.forEach(p->{
                Map<String, String> map = Maps.newHashMap();
                map.put("label", p);
                map.put("value", p);
                maps.add(map);
            });
        }
        return AjaxResults.success(maps);
    }

    /**
     * 废气-废水-导出企业排放信息-在线监测排放趋势
     */
    @ApiOperation(value = "废气-废水-导出企业排放信息-在线监测排放趋势")
    @Log(title = "废气-废水-导出企业排放信息-在线监测排放趋势", businessType = BusinessType.EXPORT)
    @PostMapping("/chart/export")
    public void chartExport(HttpServletResponse response, @Valid @RequestBody BMainEmissionOnlineMonAirQuery bMainEmissionOnlineMonAir) throws ParseException {
        switch(bMainEmissionOnlineMonAir.getFacts()){
            case "废气":
                bMainEmissionOnlineMonAir.setSearchBeginTime(DateUtil.parse(bMainEmissionOnlineMonAir.getSearchBeginTime(), "yyyy-MM-dd HH").toString());
                bMainEmissionOnlineMonAir.setSearchEndTime(DateUtil.parse(bMainEmissionOnlineMonAir.getSearchEndTime(), "yyyy-MM-dd HH").toString());
                List<BMainEmissionOnlineMonAir> airTables = bMainEmissionOnlineMonAirService.list(BMainEmissionOnlineMonAirQuery.createLambdaQueryWrapper(bMainEmissionOnlineMonAir));
                ExcelUtil<BMainEmissionOnlineMonAir> util = new ExcelUtil<BMainEmissionOnlineMonAir>(BMainEmissionOnlineMonAir.class);
                util.exportExcel(response, airTables, "企业点位"+bMainEmissionOnlineMonAir.getMonName()+"排放信息-在线监测排放趋势-废气数据");
                break;
            case "废水":
                String searchBeginTime = DateUtil.parse(bMainEmissionOnlineMonAir.getSearchBeginTime(), "yyyy-MM-dd").toString();
                String searchEndTime = DateUtil.parse(bMainEmissionOnlineMonAir.getSearchEndTime(), "yyyy-MM-dd").toString();
                List<BMainEmissionOnlineMonWater> waterTables = bMainEmissionOnlineMonWaterService.list(BMainEmissionOnlineMonWaterQuery.createLambdaQueryWrapper(new BMainEmissionOnlineMonWaterQuery(bMainEmissionOnlineMonAir.getMonName(), searchBeginTime, searchEndTime)));
                ExcelUtil<BMainEmissionOnlineMonWater> waterUtil = new ExcelUtil<BMainEmissionOnlineMonWater>(BMainEmissionOnlineMonWater.class);
                waterUtil.exportExcel(response, waterTables, "企业点位"+bMainEmissionOnlineMonAir.getMonName()+"排放信息-在线监测排放趋势-废水数据");
                break;
        }
    }

    /**
     * 查询企业排放信息-不同污染物年度排放趋势-废气列表
     */
    @ApiOperation(value = "废气-废水-(图表+列表)查询企业排放信息-在线监测排放趋势")
    @GetMapping("/chart")
    public AjaxResults<Map<String, Object>> chart(@Valid BMainEmissionOnlineMonAirQuery bMainEmissionOnlineMonAir) throws ParseException {
        Map<String, Object> res = Maps.newHashMap();
        ChartVo chartVo = new ChartVo();
        switch(bMainEmissionOnlineMonAir.getFacts()){
            case "废气":
                bMainEmissionOnlineMonAir.setSearchBeginTime(DateUtil.parse(bMainEmissionOnlineMonAir.getSearchBeginTime(), "yyyy-MM-dd HH").toString());
                bMainEmissionOnlineMonAir.setSearchEndTime(DateUtil.parse(bMainEmissionOnlineMonAir.getSearchEndTime(), "yyyy-MM-dd HH").toString());
                List<BMainEmissionOnlineMonAir> airTables = bMainEmissionOnlineMonAirService.list(BMainEmissionOnlineMonAirQuery.createLambdaQueryWrapper(bMainEmissionOnlineMonAir));
                if(!CollectionUtils.isEmpty(airTables)){
                    chartVo.setLegendData(airTables.stream().map(BMainEmissionOnlineMonAir::getPollutionType).distinct().collect(Collectors.toList()).toArray(new Object[0]));
//                    chartVo.setXsxisData(formateDateLists(waterTables.stream().map(BMainEmissionOnlineMonWater::getMonitoningTime).distinct().collect(Collectors.toList()), "yyyy-MM-dd "));
                    chartVo.setXsxisData(airTables.stream().map(BMainEmissionOnlineMonAir::getMonitoningTime).distinct().collect(Collectors.toList()).toArray(new Object[0]));
                    Map<String, List<BMainEmissionOnlineMonAir>> airMaps = airTables.stream().collect(Collectors.groupingBy(BMainEmissionOnlineMonAir::getPollutionType));
                    List<Map<Object, Object>> seriesData = Lists.newArrayList();
                    airMaps.forEach((air, data)->{
                        Map<Object, Object> map = Maps.newHashMap();
                        map.put("name", air);
                        Map<Date, List<BMainEmissionOnlineMonAir>> timeMaps = CollectionUtils.isEmpty(data) ? Maps.newHashMap() : data.stream().collect(Collectors.groupingBy(BMainEmissionOnlineMonAir::getMonitoningTime));
                        List<Object> y = Lists.newArrayList();
                        for (Object time : chartVo.getXsxisData()) {
                            if(timeMaps.containsKey(time)){
                                y.add(timeMaps.get(time).get(0).getPollutionDischarge());
                            } else {
                                y.add("--");
                            }
                        }
                        map.put("data", y);
                        seriesData.add(map);
                    });
                    chartVo.setSeriesData(seriesData);
                    chartVo.setXsxisData(formateDateLists(airTables.stream().map(BMainEmissionOnlineMonAir::getMonitoningTime).distinct().collect(Collectors.toList()), "yyyy-MM-dd HH"));
                } else {
                    chartVo.setSeriesData(Lists.newArrayList());
                    chartVo.setXsxisData(new Object[0]);
                    chartVo.setLegendData(new Object[0]);
                }
                res.put("table", airTables);
                break;
            case "废水":
                String searchBeginTime = DateUtil.parse(bMainEmissionOnlineMonAir.getSearchBeginTime(), "yyyy-MM-dd").toString();
                String searchEndTime = DateUtil.parse(bMainEmissionOnlineMonAir.getSearchEndTime(), "yyyy-MM-dd").toString();
                List<BMainEmissionOnlineMonWater> waterTables = bMainEmissionOnlineMonWaterService.list(BMainEmissionOnlineMonWaterQuery.createLambdaQueryWrapper(new BMainEmissionOnlineMonWaterQuery(bMainEmissionOnlineMonAir.getMonName(), searchBeginTime, searchEndTime)));
                if(!CollectionUtils.isEmpty(waterTables)){
                    chartVo.setLegendData(waterTables.stream().map(BMainEmissionOnlineMonWater::getPollutionType).distinct().collect(Collectors.toList()).toArray(new Object[0]));
//                    chartVo.setXsxisData(formateDateLists(waterTables.stream().map(BMainEmissionOnlineMonWater::getMonitoningTime).distinct().collect(Collectors.toList()), "yyyy-MM-dd"));
                    chartVo.setXsxisData(waterTables.stream().map(BMainEmissionOnlineMonWater::getMonitoningTime).distinct().collect(Collectors.toList()).toArray(new Object[0]));
                    Map<String, List<BMainEmissionOnlineMonWater>> waterMaps = waterTables.stream().collect(Collectors.groupingBy(BMainEmissionOnlineMonWater::getPollutionType));
                    List<Map<Object, Object>> seriesData = Lists.newArrayList();
                    waterMaps.forEach((water, data)->{
                        Map<Object, Object> map = Maps.newHashMap();
                        map.put("name", water);
                        Map<Date, List<BMainEmissionOnlineMonWater>> timeMaps = CollectionUtils.isEmpty(data) ? Maps.newHashMap() : data.stream().collect(Collectors.groupingBy(BMainEmissionOnlineMonWater::getMonitoningTime));
                        List<Object> y = Lists.newArrayList();
                        for (Object time : chartVo.getXsxisData()) {
                            if(timeMaps.containsKey(time)){
                                y.add(timeMaps.get(time).get(0).getPollutionDischarge());
                            } else {
                                y.add("--");
                            }
                        }
                        map.put("data", y);
                        seriesData.add(map);
                    });
                    chartVo.setSeriesData(seriesData);
                    chartVo.setXsxisData(formateDateLists(waterTables.stream().map(BMainEmissionOnlineMonWater::getMonitoningTime).distinct().collect(Collectors.toList()), "yyyy-MM-dd"));
                } else {
                    chartVo.setSeriesData(Lists.newArrayList());
                    chartVo.setXsxisData(new Object[0]);
                    chartVo.setLegendData(new Object[0]);
                }
                res.put("table", waterTables);
                break;
        }
        List<String> xsxisDatas = Lists.newArrayList();
        if(bMainEmissionOnlineMonAir.getFacts().equals("废气")){
            xsxisDatas.addAll(CustomDateUtil.getAllHours(DateUtil.parse(bMainEmissionOnlineMonAir.getSearchBeginTime(), CustomDateUtil.HOUR_PATTERN), DateUtil.parse(bMainEmissionOnlineMonAir.getSearchEndTime(), CustomDateUtil.HOUR_PATTERN), CustomDateUtil.HOUR_PATTERN));
        } else if (bMainEmissionOnlineMonAir.getFacts().equals("废水")){
            xsxisDatas.addAll(CustomDateUtil.getAllDays(DateUtil.parse(bMainEmissionOnlineMonAir.getSearchBeginTime(), CustomDateUtil.DATE_PATTERN), DateUtil.parse(bMainEmissionOnlineMonAir.getSearchEndTime(), CustomDateUtil.DATE_PATTERN), CustomDateUtil.DATE_PATTERN));
        }
        // 无数据默认补全x轴
        if(chartVo.getXsxisData().length == 0){
            chartVo.setXsxisData(xsxisDatas.stream().toArray());
        }
        // 数据缺失, 补全x轴及对应数据
        if(chartVo.getXsxisData().length != xsxisDatas.size()){
            CustomDateUtil.packEcharts(chartVo, xsxisDatas);
        }
        res.put("chart", chartVo);
        return AjaxResults.success(res);
    }

    private Object[] formateDateLists(List<Date> source, String format){
        Object[] res = new Object[source.size()];
        for (int i = 0; i < source.size(); i++) {
            res[i] = DateUtils.parseDateToStr(format, source.get(i));
        }
        return res;
    }


    /**
     * 查询企业排放信息-在线监测排放趋势-废气列表
     */
    @ApiOperation(value = "查询企业排放信息-在线监测排放趋势-废气")
    @GetMapping("/list")
    public AjaxResults<IPage<BMainEmissionOnlineMonAir>> list(BMainEmissionOnlineMonAirQuery bMainEmissionOnlineMonAir) throws ParseException {
        Page<BMainEmissionOnlineMonAir> page = new Page<>(bMainEmissionOnlineMonAir.getPageNum(), bMainEmissionOnlineMonAir.getPageSize());
        IPage<BMainEmissionOnlineMonAir> list = bMainEmissionOnlineMonAirService.page(page, BMainEmissionOnlineMonAirQuery.createLambdaQueryWrapper(bMainEmissionOnlineMonAir));
        return AjaxResults.success(list);
    }


    /**
     * 导出企业排放信息-在线监测排放趋势-废气列表
     */
    @ApiOperation(value = "导出企业排放信息-在线监测排放趋势-废气")
    @Log(title = "企业排放信息-在线监测排放趋势-废气", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, BMainEmissionOnlineMonAir bMainEmissionOnlineMonAir)
    {
        List<BMainEmissionOnlineMonAir> list = bMainEmissionOnlineMonAirService.selectBMainEmissionOnlineMonAirList(bMainEmissionOnlineMonAir);
        ExcelUtil<BMainEmissionOnlineMonAir> util = new ExcelUtil<BMainEmissionOnlineMonAir>(BMainEmissionOnlineMonAir.class);
        util.exportExcel(response, list, "企业排放信息-在线监测排放趋势-废气数据");
    }

    /**
     * 获取企业排放信息-在线监测排放趋势-废气详细信息
     */
    @ApiOperation(value = "获取企业排放信息-在线监测排放趋势-废气详细信息")
    @PostMapping(value = "/{id}")
    public AjaxResults<BMainEmissionOnlineMonAir> getInfo(@PathVariable("id") Integer id) {
        return AjaxResults.success(bMainEmissionOnlineMonAirService.getById(id));
    }
    /**
     * 新增企业排放信息-在线监测排放趋势-废气
     */
    @ApiOperation(value = "新增企业排放信息-在线监测排放趋势-废气")
    @Log(title = "企业排放信息-在线监测排放趋势-废气", businessType = BusinessType.INSERT)
    @PostMapping(value = "/add")
    public AjaxResults<Boolean> add(@RequestBody BMainEmissionOnlineMonAir bMainEmissionOnlineMonAir) {
        return toAjax(bMainEmissionOnlineMonAirService.save(bMainEmissionOnlineMonAir));
    }
    /**
     * 修改企业排放信息-在线监测排放趋势-废气
     */
    @ApiOperation(value = "修改企业排放信息-在线监测排放趋势-废气")
    @Log(title = "企业排放信息-在线监测排放趋势-废气", businessType = BusinessType.UPDATE)
    @PostMapping(value = "/edit")
    public AjaxResults<Boolean> edit(@RequestBody BMainEmissionOnlineMonAirVo bMainEmissionOnlineMonAirVo) {
        if(ObjectUtil.isEmpty(bMainEmissionOnlineMonAirVo)){
            throw new InvalidParameterException("参数为空");
        }
        if(ObjectUtil.isEmpty(bMainEmissionOnlineMonAirVo.getId())){
            throw new InvalidParameterException("参数id为空");
        }
        BMainEmissionOnlineMonAir bMainEmissionOnlineMonAir = bMainEmissionOnlineMonAirService.getById(bMainEmissionOnlineMonAirVo.getId());
        if(ObjectUtil.isEmpty(bMainEmissionOnlineMonAir)){
            throw new CommonException(StrUtil.format("根据id{}查询不到数据", bMainEmissionOnlineMonAirVo.getId()));
        }
        //赋值
        BeanUtil.copyProperties(bMainEmissionOnlineMonAirVo,bMainEmissionOnlineMonAir);
        return toAjax(bMainEmissionOnlineMonAirService.saveOrUpdate(bMainEmissionOnlineMonAir));
    }

    /**
     * 删除企业排放信息-在线监测排放趋势-废气
     */
    @ApiOperation(value = "删除企业排放信息-在线监测排放趋势-废气")
    @RequiresPermissions("talroad:bmainEmissionOnlineMonAir:remove")
    @Log(title = "企业排放信息-在线监测排放趋势-废气", businessType = BusinessType.DELETE)
    @PostMapping("/{ids}")
    public AjaxResults<Boolean> remove(@PathVariable String[] ids) {
        return toAjax(bMainEmissionOnlineMonAirService.removeByIds(Arrays.asList(ids)));
    }
}
