package cn.cecep.talroad.controller;

import cn.cecep.talroad.common.core.exception.CommonException;
import cn.cecep.talroad.common.core.utils.SpringUtils;
import cn.cecep.talroad.common.core.utils.StringUtils;
import cn.cecep.talroad.common.core.web.domain.AjaxResults;
import cn.cecep.talroad.domain.BStatTableZxbgJbxxInfo;
import cn.cecep.talroad.util.ZipUtils;
import cn.cecep.talroad.vo.query.BStatTablepPwxkWaterQuery;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.cecep.talroad.vo.query.BStatTableZxbgPflAirQuery;

import cn.hutool.core.util.ReflectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.core.util.ZipUtil;
import com.alibaba.fastjson.JSONObject;
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.io.File;
import java.io.IOException;
import java.lang.reflect.Method;
import java.security.InvalidParameterException;
import java.text.SimpleDateFormat;
import java.util.*;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
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;
import cn.cecep.talroad.domain.BStatTableZxbgPflAir;
import cn.cecep.talroad.vo.BStatTableZxbgPflAirVo;
import cn.cecep.talroad.service.IBStatTableZxbgPflAirService;


/**
 * * 开发公司：中节能天融科技有限公司
 * 固定源产排治--执行报告--废气实际排放量Controller 控制层
 *
 * @author szhpt
 * @date 2023-07-27*/
@Api(tags = "固定源产排治--执行报告--废气实际排放量")
@RestController
@RequestMapping("/execution/report/air")
public class BStatTableZxbgPflAirController extends BasesController
{
    @Autowired
    private IBStatTableZxbgPflAirService bStatTableZxbgPflAirService;

    /**
     * 查询固定源产排治--执行报告--废气实际排放量列表
     */
    @ApiOperation(value = "查询--执行报告--废气实际排放量")
    @PostMapping("/list")
    public AjaxResults<IPage<BStatTableZxbgPflAir>> list(@RequestBody BStatTablepPwxkWaterQuery query)
    {
        return bStatTableZxbgPflAirService.selectBStatTableZxbgPflAirListBy(query);
    }
    

    /**
     * 导出固定源产排治--执行报告--废气实际排放量列表
     */
    @ApiOperation(value = "导出固定源产排治--执行报告--废气实际排放量",produces = "application/octet-stream")
    @Log(title = "固定源产排治--执行报告--废气实际排放量", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, @RequestBody BStatTablepPwxkWaterQuery query)
    {
        AjaxResults<IPage<BStatTableZxbgPflAir>> iPageAjaxResults = bStatTableZxbgPflAirService.selectBStatTableZxbgPflAirListBy(query);
        ExcelUtil<BStatTableZxbgPflAir> util = new ExcelUtil<BStatTableZxbgPflAir>(BStatTableZxbgPflAir.class);
        util.setBol(query.getBol());
        util.exportExcel(response, iPageAjaxResults.getData().getRecords(), "执行报告--废气实际排放量数据");
    }
    /**
     * 多表导出
     */
    @ApiOperation(value = "导出固定源产排治--多表导出")
    @Log(title = "固定源产排治--多表导出", businessType = BusinessType.EXPORT)
    @PostMapping("/exportZip")
    public void exportZip(HttpServletResponse response, @RequestBody BStatTablepPwxkWaterQuery query)
    {

        try {
            if(StringUtils.isNotBlank(query.getBeanMethodList())){
                for (String beanMethod : query.getBeanMethodList().split(",")) {
                    try {
                        // 根据参数使用反射来调用对应的Controller方法
                        String invokeTarget = beanMethod+"('response query')";
                        String beanName = StrUtil.subBefore(invokeTarget, ".", true);
                        String methodName = StrUtil.subBetween(invokeTarget, ".", "(");
                        String param = StrUtil.subBetween(invokeTarget, "(", ")");
                        Object bean;
                        if (StrUtil.count(beanName, ".") == 0) {
                            bean = SpringUtils.getBean(beanName);
                        } else {
                            //Package 的形式得到 Bean，如： beanName="cn.cecep.talroad.controller.BStatTableZxbgJbxxInfoController"
                            bean = Class.forName(beanName).newInstance();
                        }
                        if (bean != null) {
                            if (StrUtil.isNotEmpty(param)) {
                                Method method = bean.getClass().getDeclaredMethod(methodName, HttpServletResponse.class,BStatTablepPwxkWaterQuery.class);
                                method.invoke(bean, response,query);
                            } else {
                                Method method = bean.getClass().getDeclaredMethod(methodName);
                                method.invoke(bean);
                            }
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                        logger.info("{}调用报错",beanMethod);
                    }
                }
            }
            //filePaths：文件url。  zipFileName：下载的压缩包名字
            List<String> filePaths = new ArrayList<String>();
            String tempFilePath = System.getProperty("user.dir");
            String dir =tempFilePath + File.separator+ExcelUtil.zipMkdir;
            File file=new File(dir);
            List<File> fileList = (List<File>)FileUtils.listFiles(file, null, true);
            fileList.forEach(item->{
                filePaths.add(item.getPath());
            });
            String zipFileName = "许可数据多表"  + ".zip";
            ZipUtils.downloadAndZipFiles(response, filePaths, zipFileName);
            //删除临时目录
            FileUtils.deleteDirectory(file);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    @PostMapping("/exportZip1")
    public void exportZip1(HttpServletResponse response, @RequestBody JSONObject query)
    {
        try {
            Object o = Class.forName("cn.cecep.talroad.vo.query.BStatTablepPwxkWaterQuery").newInstance();
            Object queryVo =query.toJavaObject(o.getClass());
            if(StringUtils.isNotBlank(query.getString("beanMethodList"))){
                for (String beanMethod : query.getString("beanMethodList").split(",")) {
                    try {
                        // 根据参数使用反射来调用对应的Controller方法
                        String invokeTarget = beanMethod+"('response query')";
                        String beanName = StrUtil.subBefore(invokeTarget, ".", true);
                        String methodName = StrUtil.subBetween(invokeTarget, ".", "(");
                        String param = StrUtil.subBetween(invokeTarget, "(", ")");
                        Object bean;
                        if (StrUtil.count(beanName, ".") == 0) {
                            bean = SpringUtils.getBean(beanName);
                        } else {
                            //Package 的形式得到 Bean，如： beanName="cn.cecep.talroad.controller.BStatTableZxbgJbxxInfoController"
                            bean = Class.forName(beanName).newInstance();
                        }
                        if (bean != null) {
                            if (StrUtil.isNotEmpty(param)) {
                                Method method = bean.getClass().getDeclaredMethod(methodName, HttpServletResponse.class,queryVo.getClass());
                                method.invoke(bean, response,queryVo);
                            } else {
                                Method method = bean.getClass().getDeclaredMethod(methodName);
                                method.invoke(bean);
                            }
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                        logger.info("{}调用报错",beanMethod);
                    }
                }
            }
            //filePaths：文件url。  zipFileName：下载的压缩包名字
            List<String> filePaths = new ArrayList<String>();
            String tempFilePath = System.getProperty("user.dir");
            String dir =tempFilePath + File.separator+ExcelUtil.zipMkdir;
            File file=new File(dir);
            List<File> fileList = (List<File>)FileUtils.listFiles(file, null, true);
            fileList.forEach(item->{
                filePaths.add(item.getPath());
            });
            String zipFileName = "许可数据多表"  + ".zip";
            ZipUtils.downloadAndZipFiles(response, filePaths, zipFileName);
            //删除临时目录
            FileUtils.deleteDirectory(file);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取固定源产排治--执行报告--废气实际排放量详细信息
     */
    @ApiOperation(value = "获取固定源产排治--执行报告--废气实际排放量详细信息")
    @PostMapping(value = "/{id}")
    public AjaxResults<BStatTableZxbgPflAir> getInfo(@PathVariable("id") Integer id) {
        return AjaxResults.success(bStatTableZxbgPflAirService.getById(id));
    }
    /**
     * 新增固定源产排治--执行报告--废气实际排放量
     */
    @ApiOperation(value = "新增固定源产排治--执行报告--废气实际排放量")
    @Log(title = "固定源产排治--执行报告--废气实际排放量", businessType = BusinessType.INSERT)
    @PostMapping(value = "/add")
    public AjaxResults<Boolean> add(@RequestBody BStatTableZxbgPflAir bStatTableZxbgPflAir) {
        return toAjax(bStatTableZxbgPflAirService.save(bStatTableZxbgPflAir));
    }
    /**
     * 修改固定源产排治--执行报告--废气实际排放量
     */
    @ApiOperation(value = "修改固定源产排治--执行报告--废气实际排放量")
    @Log(title = "固定源产排治--执行报告--废气实际排放量", businessType = BusinessType.UPDATE)
    @PostMapping(value = "/edit")
    public AjaxResults<Boolean> edit(@RequestBody BStatTableZxbgPflAirVo bStatTableZxbgPflAirVo) {
        if(ObjectUtil.isEmpty(bStatTableZxbgPflAirVo)){
            throw new InvalidParameterException("参数为空");
        }
        if(ObjectUtil.isEmpty(bStatTableZxbgPflAirVo.getId())){
            throw new InvalidParameterException("参数id为空");
        }
        BStatTableZxbgPflAir bStatTableZxbgPflAir = bStatTableZxbgPflAirService.getById(bStatTableZxbgPflAirVo.getId());
        if(ObjectUtil.isEmpty(bStatTableZxbgPflAir)){
            throw new CommonException(StrUtil.format("根据id{}查询不到数据", bStatTableZxbgPflAirVo.getId()));
        }
        //赋值
        BeanUtil.copyProperties(bStatTableZxbgPflAirVo,bStatTableZxbgPflAir);
        return toAjax(bStatTableZxbgPflAirService.saveOrUpdate(bStatTableZxbgPflAir));
    }

    /**
     * 删除固定源产排治--执行报告--废气实际排放量
     */
    @ApiOperation(value = "删除固定源产排治--执行报告--废气实际排放量")
    @RequiresPermissions("talroad:air:remove")
    @Log(title = "固定源产排治--执行报告--废气实际排放量", businessType = BusinessType.DELETE)
    @PostMapping("/{ids}")
    public AjaxResults<Boolean> remove(@PathVariable Long[] ids) {
        return toAjax(bStatTableZxbgPflAirService.removeByIds(Arrays.asList(ids)));
    }
}
