package com.nantian.cloud.jljc.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.nantian.cloud.jljc.entity.DischargeEnergyConstruction;
import com.nantian.cloud.jljc.entity.DischargeEnergyPlan;
import com.nantian.cloud.jljc.entity.DischargeEnergyStock;
import com.nantian.cloud.jljc.service.DischargeEnergyPlanService;
import com.nantian.cloud.jljc.vo.dischargeEnergy.DischargeEnergyPlanVo;
import com.nantian.cloud.jljc.vo.dischargeEnergy.DischargeEnergyPlanVo;
import com.nantian.sc.cloud.common.core.util.R;
import com.nantian.sc.cloud.common.log.annotation.SysLog;
import com.nantian.sc.cloud.common.minio.service.MinioTemplate;
import com.nantian.sc.cloud.common.security.service.ScUser;
import com.nantian.sc.cloud.common.security.util.SecurityUtils;
import io.minio.errors.*;
import lombok.AllArgsConstructor;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFFont;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.xmlpull.v1.XmlPullParserException;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Date;
import java.util.List;

/**
 * 两高项目拟建表服务控制器
 *
 * @author gj
 * @since 2022-02-17 09:16:42
 * @description 
 */
@CrossOrigin
@RestController
@AllArgsConstructor
@RequestMapping("/dischargeEnergyPlan")
public class DischargeEnergyPlanController {
    private final DischargeEnergyPlanService dischargeEnergyPlanService;
    @Autowired
    private MinioTemplate minioTemplate;

    /**
     * 分页查询
     *
     * @param page      分页对象
     * @return
     */
    @GetMapping("/page")
    @SysLog("分页查询两高项目拟建表")
    public R getStockPage(Page page, DischargeEnergyPlan dischargeEnergyPlan) {
        dischargeEnergyPlan.setDelFlag("1");  //筛选未删除项
        return R.ok(dischargeEnergyPlanService.getPageData(page,dischargeEnergyPlan));
    }

    /**
     * 查询
     *
     * @param
     * @return
     */
    @GetMapping("/getByEpc")
    @SysLog("通过企业查询两高项目拟建表")
    public R getByEpc(DischargeEnergyPlan dischargeEnergyPlan) {
        QueryWrapper<DischargeEnergyPlan> queryWrapper = new QueryWrapper<DischargeEnergyPlan>();
        queryWrapper.eq("enterprise_code",dischargeEnergyPlan.getEnterpriseCode());
        queryWrapper.eq("year",dischargeEnergyPlan.getYear());
        queryWrapper.eq("quarter",dischargeEnergyPlan.getQuarter());
        List<DischargeEnergyPlan> list = dischargeEnergyPlanService.list(queryWrapper);
        return R.ok(list);
    }


    /**
     两高项目拟建表添加
     */
    @PostMapping("/save")
    @SysLog("添加两高项目拟建表")
    public R save(@RequestBody DischargeEnergyPlan dischargeEnergyPlan){
        ScUser u= SecurityUtils.getUser();
        if(u.getId()!=null){
            dischargeEnergyPlan.setUserid(u.getId());
        }
        if (u.getDeptId() != null) {
            dischargeEnergyPlan.setDeptId(u.getDeptId());
        }
        dischargeEnergyPlan.setDelFlag("1");
        dischargeEnergyPlan.setUpdateTime(new Date());
        return R.ok(dischargeEnergyPlanService.save(dischargeEnergyPlan));
    }

    /**
     两高项目拟建表添加
     */
    @PostMapping("/addPlan")
    @SysLog("通过企业查询两高项目拟建表")
    public R addPlan(@RequestBody String s){
        return R.ok(dischargeEnergyPlanService.addPlan(s));
    }

    /**
     两高项目拟建表修改
     */
    @PostMapping("/edit")
    @SysLog("修改两高项目拟建表")
    public R edit(@RequestBody DischargeEnergyPlan dischargeEnergyPlan){
        return R.ok(dischargeEnergyPlanService.updateById(dischargeEnergyPlan));
    }

    /**
     * 按照州市统计数据
     */
    @PostMapping("/statisticsCityPlan")
    @SysLog("按照州市统计两高项目拟建表")
    public R statistics(@RequestBody DischargeEnergyPlan dischargeEnergyPlan){
        List<DischargeEnergyPlanVo> data = dischargeEnergyPlanService.getData(dischargeEnergyPlan);
        return R.ok(data);
    }


    /**
     * 导出Excel
     */
    @GetMapping("/excel")
    @ResponseBody
    @SysLog("通两高项目拟建表导出")
    public R excel (DischargeEnergyPlan dischargeEnergyPlan, HttpServletResponse response) throws IOException {

        try {
            List<DischargeEnergyPlanVo> data1 = dischargeEnergyPlanService.getData(dischargeEnergyPlan);
            writeExcel(response, data1);
        } catch (Exception e) {
            System.out.println(e);
        }
        return null;
    }

    private void writeExcel(HttpServletResponse response, List<DischargeEnergyPlanVo> data1) throws InvalidPortException, InvalidEndpointException, IOException, InvalidKeyException, NoSuchAlgorithmException, InsufficientDataException, InvalidArgumentException, InternalException, NoResponseException, InvalidBucketNameException, XmlPullParserException, ErrorResponseException {
        InputStream is = minioTemplate.getObject("jljc", "云南省拟建“两高”清单模板.xlsx");
        XSSFWorkbook xSSFWorkbook = null;
        XSSFSheet xSSFSheet = null;
        try {
            xSSFWorkbook = new XSSFWorkbook(is);
            //获取第一个sheet
            xSSFSheet = xSSFWorkbook.getSheetAt(0);

        } catch (Exception e1) {
            e1.printStackTrace();
        }

        if (xSSFSheet != null) {
            try {
                //写数据
                XSSFFont font = xSSFWorkbook.createFont();
                XSSFFont font1 = xSSFWorkbook.createFont();
                CellStyle style = xSSFWorkbook.createCellStyle();
                CellStyle style1 = xSSFWorkbook.createCellStyle();
                font.setFontName("方正仿宋_GBK");
                font1.setFontName("Times New Roman");
                style.setFont(font);
                style1.setFont(font1);
                style.setWrapText(true);//自動換行
                style1.setWrapText(true);//自動換行
                style.setVerticalAlignment(style.getVerticalAlignmentEnum().CENTER);//设置居中
                style.setAlignment(HorizontalAlignment.CENTER);
                style1.setVerticalAlignment(style.getVerticalAlignmentEnum().CENTER);//设置居中
                style1.setAlignment(HorizontalAlignment.CENTER);
                style.setBorderBottom(BorderStyle.THIN);//边框
                style.setBorderLeft(BorderStyle.THIN);
                style.setBorderRight(BorderStyle.THIN);
                style.setBorderTop(BorderStyle.THIN);
                style1.setBorderBottom(BorderStyle.THIN);
                style1.setBorderLeft(BorderStyle.THIN);
                style1.setBorderRight(BorderStyle.THIN);
                style1.setBorderTop(BorderStyle.THIN);

                //构建每行的数据内容
                int rowNum = 4;
                for (DischargeEnergyPlanVo data : data1) {
                    if (data == null) {
                        continue;
                    }
                    //输出行数据
                    Row row = xSSFSheet.createRow(rowNum++);

                    int cellNum = 0;
                    Cell cell;
                    // 序号
                    cell = row.createCell(cellNum++);
                    cell.setCellValue(null == data.getIndex() ? "" : data.getIndex());
                    cell.setCellStyle(style1);
                    // 所在州市
                    cell = row.createCell(cellNum++);
                    cell.setCellValue(null == data.getMeaning2() ? "" : data.getMeaning2());
                    cell.setCellStyle(style);
                    // 行业类别
                    cell = row.createCell(cellNum++);
                    cell.setCellValue(null == data.getIndustryClassName() ? "" : data.getIndustryClassName());
                    cell.setCellStyle(style);
                    // 大类代码
                    cell = row.createCell(cellNum++);
                    cell.setCellValue(null == data.getIndustryTypeCode() ? "" : data.getIndustryTypeCode());
                    cell.setCellStyle(style1);
                    //项目名称
                    cell = row.createCell(cellNum++);
                    cell.setCellValue(null == data.getItemName() ? "" : data.getItemName());
                    cell.setCellStyle(style);
                    // 企业名称
                    cell = row.createCell(cellNum++);
                    cell.setCellValue(null == data.getEnterpriseName() ? "" : data.getEnterpriseName());
                    cell.setCellStyle(style);
//                    // 组织机构代码
//                    cell = row.createCell(cellNum++);
//                    cell.setCellValue(null == data.getEnterpriseCode() ? "" : data.getEnterpriseCode());
//                    cell.setCellStyle(style1);
//                    // 小类代码
//                    cell = row.createCell(cellNum++);
//                    cell.setCellValue(null == data.getIndustrySubclassCode() ? "" : data.getIndustrySubclassCode());
//                    cell.setCellStyle(style1);
                    // 项目状态
                    cell = row.createCell(cellNum++);
                    cell.setCellValue(null == data.getItemState() ? "" : data.getItemState());
                    cell.setCellStyle(style);
                    // 节能审查机关
                    cell = row.createCell(cellNum++);
                    cell.setCellValue(null == data.getEnergyOffice() ? "" : data.getEnergyOffice());
                    cell.setCellStyle(style);
                    // 审查完成时间
                    cell = row.createCell(cellNum++);
                    cell.setCellValue(null == data.getEnergyTime() ? "" : data.getEnergyTime());
                    cell.setCellStyle(style);
                    // 节能审查批复文号
                    cell = row.createCell(cellNum++);
                    cell.setCellValue(null == data.getEnergyNumber() ? "" : data.getEnergyNumber());
                    cell.setCellStyle(style);
                    // 工业总产值(当年价)(万元)
                    cell = row.createCell(cellNum++);
                    cell.setCellValue(null == data.getProductionValue() ? "" : data.getProductionValue());
                    cell.setCellStyle(style1);
                    //开工时间
                    cell = row.createCell(cellNum++);
                    cell.setCellValue(null == data.getStartTime() ? "" : data.getStartTime());
                    cell.setCellStyle(style1);
                    //投产时间
                    cell = row.createCell(cellNum++);
                    cell.setCellValue(null == data.getProductionTime() ? "" : data.getProductionTime());
                    cell.setCellStyle(style1);
                    //项目总投资
                    cell = row.createCell(cellNum++);
                    cell.setCellValue(null == data.getItemInvest() ? "" : data.getItemInvest());
                    cell.setCellStyle(style1);
                    // 是否存在原料用能（是/否）
                    cell = row.createCell(cellNum++);
                    cell.setCellValue(null == data.getEnergyRaw() ? "" : data.getEnergyRaw());
                    cell.setCellStyle(style1);
                    // 原料用能（万吨标准煤）
                    cell = row.createCell(cellNum++);
                    cell.setCellValue(null == data.getEnergyRawValue() ? "" : data.getEnergyRawValue());
                    cell.setCellStyle(style1);
                    // 产品
                    cell = row.createCell(cellNum++);
                    cell.setCellValue(null == data.getProduct() ? "" : data.getProduct());
                    cell.setCellStyle(style);
                    // 设计产能（吨/千瓦时/重量箱等）
                    cell = row.createCell(cellNum++);
                    cell.setCellValue(null == data.getCapacityDesign() ? "" : data.getCapacityDesign());
                    cell.setCellStyle(style1);
                    // 2022年预计实际产量（吨/千瓦时/重量箱等）
                    cell = row.createCell(cellNum++);
                    cell.setCellValue(null == data.getProductOutput() ? "" : data.getProductOutput());
                    cell.setCellStyle(style1);
                    // 2023年预计实际产量（吨/千瓦时/重量箱等）
                    cell = row.createCell(cellNum++);
                    cell.setCellValue(null == data.getProductOutputNext() ? "" : data.getProductOutputNext());
                    cell.setCellStyle(style1);
                    // 2024年预计实际产量（吨/千瓦时/重量箱等）
                    cell = row.createCell(cellNum++);
                    cell.setCellValue(null == data.getProductOutputNextTwo() ? "" : data.getProductOutputNextTwo());
                    cell.setCellStyle(style1);
                    // 2025年预计实际产量（吨/千瓦时/重量箱等）
                    cell = row.createCell(cellNum++);
                    cell.setCellValue(null == data.getProductOutputNextThree() ? "" : data.getProductOutputNextThree());
                    cell.setCellStyle(style1);
                    //设计能耗当量
                    cell = row.createCell(cellNum++);
                    cell.setCellValue(null == data.getEnergyDesignDl() ? "" : data.getEnergyDesignDl()+"");
                    cell.setCellStyle(style1);
                    //设计能耗等价
                    cell = row.createCell(cellNum++);
                    cell.setCellValue(null == data.getEnergyDesignDj() ? "" : data.getEnergyDesignDj()+"");
                    cell.setCellStyle(style1);
                    //新增能耗当量值
                    cell = row.createCell(cellNum++);
                    cell.setCellValue(null == data.getEnergyNewPlanDl() ? "" : data.getEnergyNewPlanDl()+"");
                    cell.setCellStyle(style1);
                    //新增能耗等价值
                    cell = row.createCell(cellNum++);
                    cell.setCellValue(null == data.getEnergyNewPlanDj() ? "" : data.getEnergyNewPlanDj()+"");
                    cell.setCellStyle(style1);
                    // 单位产品能耗(t/tce)
                    cell = row.createCell(cellNum++);
                    cell.setCellValue(null == data.getProductEnergy() ? "" : data.getProductEnergy());
                    cell.setCellStyle(style1);
                    //节能效果
                    cell = row.createCell(cellNum++);
                    cell.setCellValue(null == data.getEnergySavingEffect() ? "" : data.getEnergySavingEffect());
                    cell.setCellStyle(style1);
                    //电力消耗量
                    cell = row.createCell(cellNum++);
                    cell.setCellValue(null == data.getEnergyElectricity() ? "" : data.getEnergyElectricity());
                    cell.setCellStyle(style1);
                    //煤炭消耗量
                    cell = row.createCell(cellNum++);
                    cell.setCellValue(null == data.getEnergyCoal() ? "" : data.getEnergyCoal());
                    cell.setCellStyle(style1);
//                    // 单位产品电耗（t/kWh）
//                    cell = row.createCell(cellNum++);
//                    cell.setCellValue(null == data.getProductElectricity() ? "" : data.getProductElectricity());
//                    cell.setCellStyle(style1);
                    // 备注
                    cell = row.createCell(cellNum++);
                    cell.setCellValue(null == data.getRemark() ? "" : data.getRemark());
                    cell.setCellStyle(style);
                }

                OutputStream output = response.getOutputStream(); // 读取的文件路径
                response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("云南省“两高”清单.xlsx", "UTF-8"));
                response.setCharacterEncoding("UTF-8");
                response.setContentType("charset=GBK");
                xSSFWorkbook.write(output);
                output.close();
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                try {
                    if (null != is) {
                        is.close();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }


}