package com.nantian.cloud.jljc.controller;


import cn.hutool.core.io.IoUtil;
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.nantian.cloud.jljc.entity.TFaReviewerComment;
import com.nantian.cloud.jljc.service.TFaReviewerCommentService;
import com.nantian.cloud.jljc.vo.util.FileUtil;
import com.nantian.sc.cloud.common.core.util.R;
import com.nantian.sc.cloud.common.data.datascope.DataScope;
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.annotation.Inner;
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 org.apache.commons.lang.StringUtils;
import org.apache.ibatis.annotations.Param;
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.core.io.ClassPathResource;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.xmlpull.v1.XmlPullParserException;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.net.URL;
import java.net.URLEncoder;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.*;

/**
 * <p>
 * 固定资产投资项目节能审查评审意见汇总 前端控制器
 * </p>
 *
 * @author fyf
 * @since 2022-03-10
 */
@CrossOrigin
@AllArgsConstructor
@RestController
@RequestMapping("/tFaReviewerComment")
public class TFaReviewerCommentController {

    @Autowired
    private TFaReviewerCommentService tFaReviewerCommentService;

    @Autowired
    MinioTemplate minioTemplate;

    @GetMapping("/getPage")
    @SysLog("分页获取固定资产投资项目节能审查评审意见汇总")
    public R getPage(Page page, TFaReviewerComment tFaReviewerComment){
        tFaReviewerComment.setDelFlag(1);
        IPage<TFaReviewerComment> pageList = tFaReviewerCommentService.getPage(page, tFaReviewerComment, new DataScope());
        return R.ok(pageList);
    }

    @GetMapping("/getInfo/{id}")
    @SysLog("根据id获取固定资产投资项目节能审查评审意见汇总")
    public R getInfo(@PathVariable Integer id){

        TFaReviewerComment tFaReviewerComment = tFaReviewerCommentService.getOne(
                new QueryWrapper<TFaReviewerComment>()
                .eq("del_flag", 1).eq("id", id));
        return R.ok(tFaReviewerComment);
    }

    @PostMapping("/saveOrUpdate")
    @SysLog("新增/修改获取固定资产投资项目节能审查评审意见汇总")
    public R saveOrUpdate(@RequestBody TFaReviewerComment tFaReviewerComment){
        ScUser u = SecurityUtils.getUser();
        if (tFaReviewerComment.getId() != null){
            tFaReviewerComment.setUserId(u.getId());
            tFaReviewerComment.setDelFlag(1);
            tFaReviewerComment.setDeptId(u.getDeptId());
            tFaReviewerComment.setUserRealName(u.getUserRealName());
            tFaReviewerComment.setUpdateTime(new Date());
            return R.ok(tFaReviewerCommentService.updateById(tFaReviewerComment));
        }else {
            tFaReviewerComment.setUserRealName(u.getUserRealName());
            tFaReviewerComment.setUserId(u.getId());
            tFaReviewerComment.setUpdateTime(new Date());
            tFaReviewerComment.setDeptId(u.getDeptId());
            tFaReviewerComment.setDelFlag(1);
            return R.ok(tFaReviewerCommentService.save(tFaReviewerComment));
        }
    }

    @DeleteMapping("/delete/{id}")
    @SysLog("删除获取固定资产投资项目节能审查评审意见汇总")
    public R delete(@PathVariable Integer id){
        TFaReviewerComment tFaReviewerComment = tFaReviewerCommentService.getById(id);
        ScUser u = SecurityUtils.getUser();
        tFaReviewerComment.setDelFlag(4);
        tFaReviewerComment.setDeptId(u.getDeptId());
        tFaReviewerComment.setUserRealName(u.getUserRealName());
        tFaReviewerComment.setUserId(u.getId());
        tFaReviewerComment.setUpdateTime(new Date());
        return R.ok(tFaReviewerCommentService.updateById(tFaReviewerComment));
    }

    @PostMapping("/excelImport")
    @SysLog("导入固定资产投资项目节能审查评审意见汇总")
    public R excelUpload(@RequestParam("file") MultipartFile multipartFile) throws IOException {

        tFaReviewerCommentService.excelImport(multipartFile);
        return R.ok();
    }

    //导出Excel模板
    @Inner(value = false)
    @GetMapping("/download")
    @SysLog("下载固定资产投资项目节能审查评审意见汇总表模板文件")
    public R download(HttpServletResponse response) throws IOException {
        InputStream templateObject = minioTemplate.getObject("jljc", "opinionSummary.xlsx");
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/x-download;charset=utf-8");
//        response.setHeader("Content-disposition", URLEncoder.encode(file.getName(), "UTF-8"));

        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode("固定资产节能审查材料导入模板.xlsx", "UTF-8"));
        response.setHeader("Pragma", "No-cache");
        IoUtil.copy(templateObject, response.getOutputStream());
//        URL url = new ClassPathResource("mouldFile/opinionSummary.xlsx").getURL();
//        File file = new File(url.getFile());
//        if (!file.exists()){
//            return R.failed("路径有误，文件不存在！");
//        }
//        response.setCharacterEncoding("UTF-8");
//        response.setContentType("application/x-download;charset=utf-8");
//        response.setHeader("Content-disposition", URLEncoder.encode(file.getName(), "UTF-8"));
//
//        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
//        response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode("xxxx年全年固定资产投资项目节能审查实施情况报送表.xlsx", "UTF-8"));
//        response.setHeader("Pragma", "No-cache");
//
//        //从内存中写出来
//        OutputStream outputStream = response.getOutputStream();
//        outputStream.write(FileUtil.file2byte(file));
//        outputStream.flush();
//        outputStream.close();
        return R.ok("模板导出成功!");
    }

    @GetMapping("/getExcelData")
    @SysLog("导出固定资产投资项目节能审查评审意见汇总表")
    @ResponseBody
    public R getExcelData(TFaReviewerComment tFaReviewerComment, HttpServletResponse response) throws IOException {

        try {
            List<TFaReviewerComment> excelData = tFaReviewerCommentService.getExcelData(tFaReviewerComment);
            writeExcel(response, excelData);
        } catch (Exception e) {
            System.out.println(e);
        }
        return null;
    }

    private void writeExcel(HttpServletResponse response, List<TFaReviewerComment> data1) throws InvalidPortException, InvalidEndpointException, IOException, InvalidKeyException, NoSuchAlgorithmException, InsufficientDataException, InvalidArgumentException, InternalException, NoResponseException, InvalidBucketNameException, XmlPullParserException, ErrorResponseException {
        InputStream is = minioTemplate.getObject("jljc", "opinionSummaryDownload.xlsx");
        XSSFWorkbook xSSFWorkbook = null;
        XSSFSheet xSSFSheet = null;

        try {
            //is = new FileInputStream(newFile);
            xSSFWorkbook = new XSSFWorkbook(is);
            //获取第一个sheet
            xSSFSheet = xSSFWorkbook.getSheetAt(0);
        } catch (Exception e1) {
            e1.printStackTrace();
        }

        if (xSSFSheet != null) {
            try {
                //写数据
                //FileOutputStream fos = new FileOutputStream(newFile);
                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 = 3, index = 0;
                for (TFaReviewerComment data : data1) {
                    if (data == null) {
                        continue;
                    }
                    //输出行数据
                    Row row = xSSFSheet.createRow(rowNum++);

                    int cellNum = 0;
                    Cell cell;
                    // 序号
                    cell = row.createCell(cellNum++);
                    cell.setCellValue(++index);
                    cell.setCellStyle(style1);
                    //项目名称
                    cell = row.createCell(cellNum++);
                    cell.setCellValue(null == data.getProjectName() ? "" : data.getProjectName());
                    cell.setCellStyle(style);
                    //项目代码
                    cell = row.createCell(cellNum++);
                    cell.setCellValue(null == data.getProjectCode() ? "" : data.getProjectCode());
                    cell.setCellStyle(style);
                    //建设单位
                    cell = row.createCell(cellNum++);
                    cell.setCellValue(null == data.getConstructionUnit() ? "" : data.getConstructionUnit());
                    cell.setCellStyle(style);
                    //所属行业
                    cell = row.createCell(cellNum++);
                    cell.setCellValue(null == data.getIndustryName() ? "" : data.getIndustryName());
                    cell.setCellStyle(style);
                    //拟投产时间
                    cell = row.createCell(cellNum++);
                    cell.setCellValue(null == data.getStartingTime() ? "" : data.getStartingTime());
                    cell.setCellStyle(style);
                    //节能评审单位
                    cell = row.createCell(cellNum++);
                    cell.setCellValue(null == data.getOrgan() ? "" : data.getOrgan());
                    cell.setCellStyle(style);
                    //评审完成时间
                    cell = row.createCell(cellNum++);
                    cell.setCellValue(null == data.getEndingTime() ? "" : data.getEndingTime());
                    cell.setCellStyle(style);
                    //评审意见文号
                    cell = row.createCell(cellNum++);
                    cell.setCellValue(null == data.getReferenceNumber() ? "" : data.getReferenceNumber());
                    cell.setCellStyle(style);
                    //年综合能源消费量-当量值 (tce)
                    cell = row.createCell(cellNum++);
                    cell.setCellValue(null==data.getEquivalentValue()? "" :data.getEquivalentValue().toString());
                    cell.setCellStyle(style1);
                    //年综合能源消费量-等价值 (tce)
                    cell = row.createCell(cellNum++);
                    cell.setCellValue(null == data.getIndifferenceValue() ? "" : data.getIndifferenceValue().toString());
                    cell.setCellStyle(style1);
                    //项目能源消费量增量-当量值 (tce)
                    cell = row.createCell(cellNum++);
                    cell.setCellValue(null == data.getIncreEquivalentValue() ? "" : data.getIncreEquivalentValue().toString());
                    cell.setCellStyle(style1);
                    //项目能源消费量增量-等价值 (tce)
                    cell = row.createCell(cellNum++);
                    cell.setCellValue(null == data.getIncreIndifferenceValue() ? "" : data.getIncreIndifferenceValue().toString());
                    cell.setCellStyle(style1);
                    //电力消耗量(万KWH)
                    cell = row.createCell(cellNum++);
                    cell.setCellValue(null == data.getElectricExpend() ? "" : data.getElectricExpend().toString());
                    cell.setCellStyle(style1);
                    //煤炭消费量(tce)
                    cell = row.createCell(cellNum++);
                    cell.setCellValue(null == data.getCoalExpend() ? "" : data.getCoalExpend().toString());
                    cell.setCellStyle(style1);
                    //备注
                    cell = row.createCell(cellNum++);
                    cell.setCellValue(null == data.getRest() ? "" : data.getRest());
                    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();
                }
            }
        }
    }

}
