package cn.cecep.talroad.controller.analysis;

import cn.cecep.talroad.common.core.annotation.Excel;
import cn.cecep.talroad.common.core.domain.R;
import cn.cecep.talroad.common.core.exception.CommonException;
import cn.cecep.talroad.common.core.web.domain.AjaxResults;
import cn.cecep.talroad.common.security.utils.SecurityUtils;
import cn.cecep.talroad.domain.analysis.*;
import cn.cecep.talroad.feign.BaseRegionService;
import cn.cecep.talroad.service.analysis.ISRaMultiSourceService;
import cn.cecep.talroad.vo.analysis.SRaMultiSourceVo;
import cn.cecep.talroad.vo.query.analysis.SRaMultiSourceQuery;
import cn.cecep.talroad.vo.query.analysis.SRaWaterPermittedOnlineQuery;
import cn.hutool.core.bean.BeanUtil;
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 io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Proxy;
import java.security.InvalidParameterException;
import java.util.ArrayList;
import java.util.List;
import java.util.Arrays;
import java.util.Map;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.*;
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.common.core.web.controller.BasesController;
import cn.cecep.talroad.common.core.utils.poi.ExcelUtil;


/**
 * * 开发公司：中节能天融科技有限公司
 * 多源排放量汇总Controller 控制层
 *
 * @author szhpt
 * @date 2023-06-03*/
@Api(tags = "多源排放量汇总")
@RestController
@RequestMapping("/source")
public class SRaMultiSourceController extends BasesController
{
    @Autowired
    private ISRaMultiSourceService sRaMultiSourceService;

    @Autowired
    @Qualifier("baseRegionService")
    private BaseRegionService baseRegionService;
    /**
     * 查询多源排放量汇总列表
     */
    @ApiOperation(value = "查询多源排放量汇总")
    @GetMapping("/list")
    public AjaxResults<IPage<SRaWaterPermittedOnline>> list(SRaWaterPermittedOnlineQuery sRaMultiSource)
    {
        String regionCode = SecurityUtils.getLoginUser().getSysUser().getRegionCode();
        List<String> regionCodes=new ArrayList<>();
        R<List<String>> r = baseRegionService.getRegionCodeListChild(regionCode);
        if(r.getCode()==200){
            regionCodes=r.getData();
        }
        sRaMultiSource.setRegionCodes(regionCodes);
        IPage<SRaWaterPermittedOnline> list = sRaMultiSourceService.selectSRaMultiSourceListBy(sRaMultiSource);
        return AjaxResults.success(list);
    }

    /**
     * 导出多源排放量汇总列表
     */
    @ApiOperation(value = "导出多源排放量汇总",produces = "application/octet-stream")
    @Log(title = "多源排放量汇总", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, @RequestBody SRaWaterPermittedOnlineQuery sRaMultiSource)
    {
        String regionCode = SecurityUtils.getLoginUser().getSysUser().getRegionCode();
        List<String> regionCodes=new ArrayList<>();
        R<List<String>> r = baseRegionService.getRegionCodeListChild(regionCode);
        if(r.getCode()==200){
            regionCodes=r.getData();
        }
        sRaMultiSource.setRegionCodes(regionCodes);
        List<SRaWaterPermittedOnline> list = sRaMultiSourceService.selectSRaMultiSourceList(sRaMultiSource);
        List<SRaSourcePermittedOnline> sRaSourcePermittedOnlines=list.stream().map(o -> {
            SRaSourcePermittedOnline vo = new SRaSourcePermittedOnline();
            BeanUtils.copyProperties(o, vo);
            return vo;
        }).collect(Collectors.toList());
        ExcelUtil<SRaSourcePermittedOnline> util = new ExcelUtil<SRaSourcePermittedOnline>(SRaSourcePermittedOnline.class);
        if(sRaMultiSource.getPollutantOutletType().equals("1")){
            util.hideColumnNative(3,4,5,6,7,8,9,10);
            util.exportExcel(response, sRaSourcePermittedOnlines, "多源废气排放量汇总数据");
        }else {
            util.hideColumnNative(11,12,13,14,15,16,17,18);
            util.exportExcel(response, sRaSourcePermittedOnlines, "多源废水排放量汇总数据");
        }
    }
    /**
     * 查询多源排放量汇总详情
     */
    @ApiOperation(value = "查询多源排放量汇总详情")
    @GetMapping("/listDetails")
    public AjaxResults<IPage<SRaMultiSource>> listDetails(SRaMultiSourceQuery sRaMultiSource)
    {
        IPage<SRaMultiSource> list = sRaMultiSourceService.selectSRaMultiSourceListDetailsBy(sRaMultiSource);
        return AjaxResults.success(list);
    }
    /**
     * 导出多源排放量汇总详情
     */
    @ApiOperation(value = "导出多源排放量汇总详情")
    @Log(title = "多源排放量汇总详情", businessType = BusinessType.EXPORT)
    @PostMapping("/exportDetails")
    public void exportDetails(HttpServletResponse response, @RequestBody SRaMultiSourceQuery sRaMultiSource)
    {
        if(StringUtils.isBlank(sRaMultiSource.getSourceType())){
            throw new InvalidParameterException("多源数据类型参数为空");
        }
        if(StringUtils.isBlank(sRaMultiSource.getPollutantsName())){
            throw new InvalidParameterException("污染物名称参数为空");
        }
        if(sRaMultiSource.getSourceType().equals("1")){
            List<SRaMultiSource> list = sRaMultiSourceService.selectSRaMultiSourceListDetails(sRaMultiSource);
            List<SRaMultiSource.SRaMultiSourcePermission> factoryCoalList=list.stream().map(o -> {
                SRaMultiSource.SRaMultiSourcePermission vo = new SRaMultiSource.SRaMultiSourcePermission();
                BeanUtils.copyProperties(o, vo);
                return vo;
            }).collect(Collectors.toList());
            Class clazz =configClass(SRaMultiSource.SRaMultiSourcePermission.class, sRaMultiSource.getPollutantsName()+"排放量(kg)","permission");
            ExcelUtil<SRaMultiSource.SRaMultiSourcePermission> util = new ExcelUtil<SRaMultiSource.SRaMultiSourcePermission>(clazz);
            util.exportExcel(response, factoryCoalList, "许可排放量详情");
        }else {
            List<SRaMultiSource> list = sRaMultiSourceService.selectSRaMultiSourceListDetails(sRaMultiSource);
            List<SRaMultiSource.SRaMultiSourceOnline> factoryCoalList=list.stream().map(o -> {
                SRaMultiSource.SRaMultiSourceOnline vo = new SRaMultiSource.SRaMultiSourceOnline();
                BeanUtils.copyProperties(o, vo);
                return vo;
            }).collect(Collectors.toList());
            Class clazz =configClass(SRaMultiSource.SRaMultiSourceOnline.class, sRaMultiSource.getPollutantsName()+"排放量(kg)","online");
            ExcelUtil<SRaMultiSource.SRaMultiSourceOnline> util = new ExcelUtil<SRaMultiSource.SRaMultiSourceOnline>(clazz);
            util.exportExcel(response, factoryCoalList, "在线排放量详情");
        }

    }

    /**
     * 注解之运行时修改字段的注解值操作
     * @param clazz
     * @param val
     * @return
     */
    private Class configClass(Class clazz , String val,String filed) {

        Field[] fields = clazz.getDeclaredFields();
        try {
            for(int i = 0;i < fields.length;i++){
                Field f = fields[i];
                if(f.getName().equals(filed)){
                    Excel excelAn = f.getAnnotation(Excel.class);//Excel是注解类型
                    if(excelAn == null){
                        continue;
                    }
                    InvocationHandler h = Proxy.getInvocationHandler(excelAn);
                    Field hField = h.getClass().getDeclaredField("memberValues");
                    // 因为这个字段事 private final 修饰，所以要打开权限
                    hField.setAccessible(true);
                    // 获取 memberValues
                    Map memberValues = (Map) hField.get(h);
                    // 修改 value 属性值 这里修改的是@Excel(name = "姓名")
                    //name是key
                    memberValues.put("name", val);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return clazz;
    }
    /**
     * 获取多源排放量汇总详细信息
     */
    @ApiOperation(value = "获取多源排放量汇总详细信息")
    @PostMapping(value = "/{dataId}")
    public AjaxResults<SRaMultiSource> getInfo(@PathVariable("id") Integer id) {
        return AjaxResults.success(sRaMultiSourceService.getById(id));
    }
    /**
     * 新增多源排放量汇总
     */
    @ApiOperation(value = "新增多源排放量汇总")
    @Log(title = "多源排放量汇总", businessType = BusinessType.INSERT)
    @PostMapping(value = "/add")
    public AjaxResults<Boolean> add(@RequestBody SRaMultiSource sRaMultiSource) {
        return toAjax(sRaMultiSourceService.save(sRaMultiSource));
    }
    /**
     * 修改多源排放量汇总
     */
    @ApiOperation(value = "修改多源排放量汇总")
    @Log(title = "多源排放量汇总", businessType = BusinessType.UPDATE)
    @PostMapping(value = "/edit")
    public AjaxResults<Boolean> edit(@RequestBody SRaMultiSourceVo sRaMultiSourceVo) {
        if(ObjectUtil.isEmpty(sRaMultiSourceVo)){
            throw new InvalidParameterException("参数为空");
        }
        if(ObjectUtil.isEmpty(sRaMultiSourceVo.getDataId())){
            throw new InvalidParameterException("参数id为空");
        }
        SRaMultiSource sRaMultiSource = sRaMultiSourceService.getById(sRaMultiSourceVo.getDataId());
        if(ObjectUtil.isEmpty(sRaMultiSource)){
            throw new CommonException(StrUtil.format("根据id{}查询不到数据", sRaMultiSourceVo.getDataId()));
        }
        //赋值
        BeanUtil.copyProperties(sRaMultiSourceVo,sRaMultiSource);
        return toAjax(sRaMultiSourceService.saveOrUpdate(sRaMultiSource));
    }

    /**
     * 删除多源排放量汇总
     */
    @ApiOperation(value = "删除多源排放量汇总")
    @RequiresPermissions("talroad:source:remove")
    @Log(title = "多源排放量汇总", businessType = BusinessType.DELETE)
    @PostMapping("/{dataIds}")
    public AjaxResults<Boolean> remove(@PathVariable String[] dataIds) {
        return toAjax(sRaMultiSourceService.removeByIds(Arrays.asList(dataIds)));
    }
    /**
     * 获取废气废水类型
     */
    @ApiOperation(value = "获取废气废水类型")
    @GetMapping("/getPollType")
    public AjaxResults<String> getPollType(SRaMultiSourceQuery lambdaQueryWrapper) {
        return AjaxResults.success(sRaMultiSourceService.pullMonitorNameOptions(lambdaQueryWrapper));
    }

}
