package cn.cecep.talroad.controller;

import cn.cecep.talroad.common.core.exception.CommonException;
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.BMainEmissionPollutionAir;
import cn.cecep.talroad.domain.BMainEmissionPollutionSolidWaste;
import cn.cecep.talroad.domain.BMainEmissionPollutionWater;
import cn.cecep.talroad.service.IBMainEmissionPollutionAirService;
import cn.cecep.talroad.service.IBMainEmissionPollutionSolidWasteService;
import cn.cecep.talroad.service.IBMainEmissionPollutionWaterService;
import cn.cecep.talroad.util.CustomDateUtil;
import cn.cecep.talroad.vo.BMainEmissionPollutionAirVo;
import cn.cecep.talroad.vo.ChartVo;
import cn.cecep.talroad.vo.query.BMainEmissionPollutionAirQuery;
import cn.cecep.talroad.vo.query.BMainEmissionPollutionSolidWasteQuery;
import cn.cecep.talroad.vo.query.BMainEmissionPollutionWaterQuery;
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.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.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


/**
 * * 开发公司：中节能天融科技有限公司
 * 企业排放信息-不同污染物年度排放趋势-废气Controller 控制层
 *
 * @author szhpt
 * @date 2023-01-31*/
@Api(tags = "企业排放信息-不同污染物年度排放趋势-废气")
@RestController
@RequestMapping("/bmainEmissionPollutionAir")
public class BMainEmissionPollutionAirController extends BasesController
{
    @Autowired
    private IBMainEmissionPollutionAirService bMainEmissionPollutionAirService;

    @Autowired
    private IBMainEmissionPollutionWaterService bMainEmissionPollutionWaterService;

    @Autowired
    private IBMainEmissionPollutionSolidWasteService bMainEmissionPollutionSolidWaterService;

    /**
     * 导出企业排放信息-不同污染物年度排放趋势-废气列表
     */
    @ApiOperation(value = "废气-废水-固废-导出企业排放信息-不同污染物年度排放趋势")
    @Log(title = "废气-废水-固废-导出企业排放信息-不同污染物年度排放趋势", businessType = BusinessType.EXPORT)
    @PostMapping("/chart/export")
    public void chartExport(HttpServletResponse response, @Valid @RequestBody BMainEmissionPollutionAirQuery bMainEmissionPollutionAir)
    {
        switch(bMainEmissionPollutionAir.getPollutionCategory()){
            case "废气":
                bMainEmissionPollutionAir.setPollutionCategory(null);
                List<BMainEmissionPollutionAir> airTables = bMainEmissionPollutionAirService.list(BMainEmissionPollutionAirQuery.createLambdaQueryWrapper(bMainEmissionPollutionAir));
                ExcelUtil<BMainEmissionPollutionAir> util = new ExcelUtil<BMainEmissionPollutionAir>(BMainEmissionPollutionAir.class);
                util.exportExcel(response, airTables, "企业排放信息-不同污染物年度排放趋势-废气数据");
                break;
            case "废水":
                bMainEmissionPollutionAir.setPollutionCategory(null);
                List<BMainEmissionPollutionWater> waterTables = bMainEmissionPollutionWaterService.list(BMainEmissionPollutionWaterQuery.createLambdaQueryWrapper(new BMainEmissionPollutionWaterQuery(bMainEmissionPollutionAir.getPollutionCategory(), bMainEmissionPollutionAir.getDataSource(), bMainEmissionPollutionAir.getSearchBeginYear(), bMainEmissionPollutionAir.getSearchEndYear(), bMainEmissionPollutionAir.getFactoryId())));
                ExcelUtil<BMainEmissionPollutionWater> waterUtil = new ExcelUtil<BMainEmissionPollutionWater>(BMainEmissionPollutionWater.class);
                waterUtil.exportExcel(response, waterTables, "企业排放信息-不同污染物年度排放趋势-废水数据");
                break;
            case "固废":
                List<BMainEmissionPollutionSolidWaste> solidTables = bMainEmissionPollutionSolidWaterService.list(BMainEmissionPollutionSolidWasteQuery.createLambdaQueryWrapper(new BMainEmissionPollutionSolidWasteQuery(bMainEmissionPollutionAir.getPollutionCategory(), bMainEmissionPollutionAir.getDataSource(), bMainEmissionPollutionAir.getSearchBeginYear(), bMainEmissionPollutionAir.getSearchEndYear(), bMainEmissionPollutionAir.getFactoryId())));
                ExcelUtil<BMainEmissionPollutionSolidWaste> solidUtil = new ExcelUtil<BMainEmissionPollutionSolidWaste>(BMainEmissionPollutionSolidWaste.class);
                solidUtil.exportExcel(response, solidTables, "企业排放信息-不同污染物年度排放趋势-固废数据");
                break;
        }
    }

    /**
     * 查询企业排放信息-不同污染物年度排放趋势-废气列表
     */
    @ApiOperation(value = "废气-废水-固废-(图表+列表)查询企业排放信息-不同污染物年度排放趋势")
    @GetMapping("/chart")
    public AjaxResults<Map<String, Object>> chart(@Valid BMainEmissionPollutionAirQuery bMainEmissionPollutionAir)
    {

        Map<String, Object> res = Maps.newHashMap();
        ChartVo chartVo = new ChartVo();
        switch(bMainEmissionPollutionAir.getPollutionCategory()){
            case "废气":
                bMainEmissionPollutionAir.setPollutionCategory(null);
                List<String> legendData = Arrays.stream(ChartVo.AirPollutant.values()).distinct().map(ChartVo.AirPollutant::getCode).collect(Collectors.toList());
                chartVo.setLegendData(legendData.toArray(new Object[0]));
                List<BMainEmissionPollutionAir> airTables = bMainEmissionPollutionAirService.list(BMainEmissionPollutionAirQuery.createLambdaQueryWrapper(bMainEmissionPollutionAir));
                if(!CollectionUtils.isEmpty(airTables)){
                    /*List<Integer> xsxisData = Lists.newArrayList();
                    for (int i = Integer.parseInt(tables.get(tables.size()-1).getPollYear()); i <= Integer.parseInt(tables.get(0).getPollYear()); i++) {
                        xsxisData.add(i);
                    }*/
                    chartVo.setXsxisData(airTables.stream().map(BMainEmissionPollutionAir::getPollYear).distinct().collect(Collectors.toList()).toArray(new Object[0]));
                    List<Map<Object, Object>> seriesData = Lists.newArrayList();
                    for (Object legendDatum : chartVo.getLegendData()) {
                        Map<Object, Object> map = Maps.newHashMap();
                        if (legendDatum.equals("SO₂")) {
                            map.put("name", legendDatum);
                            map.put("data", airTables.stream().map(BMainEmissionPollutionAir::getActuallyEmittingSo2).collect(Collectors.toList()));
                        }else if (legendDatum.equals("NOₓ")) {
                            map.put("name", legendDatum);
                            map.put("data", airTables.stream().map(BMainEmissionPollutionAir::getActuallyEmittingNox).collect(Collectors.toList()));
                        }else if (legendDatum.equals("颗粒物")) {
                            map.put("name", legendDatum);
                            map.put("data", airTables.stream().map(BMainEmissionPollutionAir::getActuallyEmittingPm).collect(Collectors.toList()));
                        }else if (legendDatum.equals("VOCs")) {
                            map.put("name", legendDatum);
                            map.put("data", airTables.stream().map(BMainEmissionPollutionAir::getActuallyEmittingVocs).collect(Collectors.toList()));
                        }
                        seriesData.add(map);
                    }
                    chartVo.setSeriesData(seriesData);
                } else {
                    chartVo.setSeriesData(Lists.newArrayList());
                    chartVo.setXsxisData(new Object[0]);
                }
                res.put("table", airTables);
            break;
            case "废水":
                bMainEmissionPollutionAir.setPollutionCategory(null);
                List<String> waterLegendData = Arrays.stream(ChartVo.WaterPollutant.values()).distinct().map(ChartVo.WaterPollutant::getCode).distinct().collect(Collectors.toList());
                chartVo.setLegendData(waterLegendData.toArray(new Object[0]));
                List<BMainEmissionPollutionWater> waterTables = bMainEmissionPollutionWaterService.list(BMainEmissionPollutionWaterQuery.createLambdaQueryWrapper(new BMainEmissionPollutionWaterQuery(bMainEmissionPollutionAir.getPollutionCategory(), bMainEmissionPollutionAir.getDataSource(), bMainEmissionPollutionAir.getSearchBeginYear(), bMainEmissionPollutionAir.getSearchEndYear(), bMainEmissionPollutionAir.getFactoryId())));
                if(!CollectionUtils.isEmpty(waterTables)){
                    chartVo.setXsxisData(waterTables.stream().map(BMainEmissionPollutionWater::getPollYear).distinct().collect(Collectors.toList()).toArray(new Object[0]));
                    List<Map<Object, Object>> seriesData = Lists.newArrayList();
                    for (Object legendDatum : chartVo.getLegendData()) {
                        Map<Object, Object> map = Maps.newHashMap();
                        if (legendDatum.equals("COD")) {
                            map.put("name", legendDatum);
                            map.put("data", waterTables.stream().map(BMainEmissionPollutionWater::getActuallyEmittingCod).collect(Collectors.toList()));
                        }else if (legendDatum.equals("氨氮")) {
                            map.put("name", legendDatum);
                            map.put("data", waterTables.stream().map(BMainEmissionPollutionWater::getActuallyEmittingNhn).collect(Collectors.toList()));
                        }else if (legendDatum.equals("总氮")) {
                            map.put("name", legendDatum);
                            map.put("data", waterTables.stream().map(BMainEmissionPollutionWater::getActuallyEmittingTn).collect(Collectors.toList()));
                        }else if (legendDatum.equals("总磷")) {
                            map.put("name", legendDatum);
                            map.put("data", waterTables.stream().map(BMainEmissionPollutionWater::getActuallyEmittingTp).collect(Collectors.toList()));
                        }
                        seriesData.add(map);
                    }
                    chartVo.setSeriesData(seriesData);
                } else {
                    chartVo.setSeriesData(Lists.newArrayList());
                    chartVo.setXsxisData(new Object[0]);
                }
                res.put("table", waterTables);
            break;
            case "固废":
                List<BMainEmissionPollutionSolidWaste> solidTables = bMainEmissionPollutionSolidWaterService.list(BMainEmissionPollutionSolidWasteQuery.createLambdaQueryWrapper(new BMainEmissionPollutionSolidWasteQuery(bMainEmissionPollutionAir.getPollutionCategory(), bMainEmissionPollutionAir.getDataSource(), bMainEmissionPollutionAir.getSearchBeginYear(), bMainEmissionPollutionAir.getSearchEndYear(), bMainEmissionPollutionAir.getFactoryId())));
                if(!CollectionUtils.isEmpty(solidTables)){
                    List<String> solidLegendData = solidTables.stream().map(BMainEmissionPollutionSolidWaste::getSolidWasteName).distinct().collect(Collectors.toList());
                    chartVo.setLegendData(solidLegendData.toArray(new Object[0]));
                    chartVo.setXsxisData(solidTables.stream().map(BMainEmissionPollutionSolidWaste::getPollYear).distinct().collect(Collectors.toList()).toArray(new Object[0]));
                    Map<String, List<BMainEmissionPollutionSolidWaste>> solidMaps = solidTables.stream().collect(Collectors.groupingBy(BMainEmissionPollutionSolidWaste::getSolidWasteName));
                    List<Map<Object, Object>> seriesData = Lists.newArrayList();
                    solidMaps.forEach((solid, data)->{
                        Map<Object, Object> map = Maps.newHashMap();
                        map.put("name", solid);
                        Map<String, List<BMainEmissionPollutionSolidWaste>> yearMaps = CollectionUtils.isEmpty(data) ? Maps.newHashMap() : data.stream().collect(Collectors.groupingBy(BMainEmissionPollutionSolidWaste::getPollYear));
                        List<Object> y = Lists.newArrayList();
                        for (Object year : chartVo.getXsxisData()) {
                            if(yearMaps.containsKey(year)){
                                y.add(yearMaps.get(year).get(0).getAnnualActualProduction());
                            } else {
                                y.add(null);
                            }
                        }
                        map.put("data", y);
                        seriesData.add(map);
                    });
                    chartVo.setSeriesData(seriesData);
                } else {
                    chartVo.setSeriesData(Lists.newArrayList());
                    chartVo.setXsxisData(new Object[0]);
                }
                res.put("table", solidTables);
            break;
        }
        if(bMainEmissionPollutionAir.getSearchBeginYear() != null && bMainEmissionPollutionAir.getSearchEndYear() != null){
            List<String> xsxisDatas = CustomDateUtil.getAllYears(DateUtil.parse(bMainEmissionPollutionAir.getSearchBeginYear()+"", CustomDateUtil.DATE_PATTERN_YEAR), DateUtil.parse(bMainEmissionPollutionAir.getSearchEndYear()+"", CustomDateUtil.DATE_PATTERN_YEAR), CustomDateUtil.DATE_PATTERN_YEAR);
            // 无数据默认补全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);
    }

    /**
     * 查询企业排放信息-不同污染物年度排放趋势-废气列表
     */
    @ApiOperation(value = "查询企业排放信息-不同污染物年度排放趋势-废气")
    @GetMapping("/list")
    public AjaxResults<IPage<BMainEmissionPollutionAir>> list(BMainEmissionPollutionAirQuery bMainEmissionPollutionAir)
    {
        Page<BMainEmissionPollutionAir> page = new Page<>(bMainEmissionPollutionAir.getPageNum(), bMainEmissionPollutionAir.getPageSize());
        IPage<BMainEmissionPollutionAir> list = bMainEmissionPollutionAirService.page(page, BMainEmissionPollutionAirQuery.createLambdaQueryWrapper(bMainEmissionPollutionAir));
        return AjaxResults.success(list);
    }


    /**
     * 导出企业排放信息-不同污染物年度排放趋势-废气列表
     */
    @ApiOperation(value = "导出企业排放信息-不同污染物年度排放趋势-废气")
    @Log(title = "企业排放信息-不同污染物年度排放趋势-废气", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, BMainEmissionPollutionAirQuery bMainEmissionPollutionAir)
    {
        List<BMainEmissionPollutionAir> list = bMainEmissionPollutionAirService.list(BMainEmissionPollutionAirQuery.createLambdaQueryWrapper(bMainEmissionPollutionAir));
        ExcelUtil<BMainEmissionPollutionAir> util = new ExcelUtil<BMainEmissionPollutionAir>(BMainEmissionPollutionAir.class);
        util.exportExcel(response, list, "企业排放信息-不同污染物年度排放趋势-废气数据");
    }

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

    /**
     * 删除企业排放信息-不同污染物年度排放趋势-废气
     */
    @ApiOperation(value = "删除企业排放信息-不同污染物年度排放趋势-废气")
    @RequiresPermissions("talroad:bmainEmissionPollutionAir:remove")
    @Log(title = "企业排放信息-不同污染物年度排放趋势-废气", businessType = BusinessType.DELETE)
    @PostMapping("/{ids}")
    public AjaxResults<Boolean> remove(@PathVariable String[] ids) {
        return toAjax(bMainEmissionPollutionAirService.removeByIds(Arrays.asList(ids)));
    }
}
