package org.jeecg.ctop.finance.settlement.controller;

import cn.afterturn.easypoi.cache.manager.POICacheManager;
import cn.afterturn.easypoi.entity.ImageEntity;
import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.TemplateExportParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.util.CellRangeAddress;
import org.jeecg.common.api.vo.Result;
import org.jeecg.ctop.finance.settlement.entity.vo.SettlementReportBytedanceVo;
import org.jeecg.ctop.finance.settlement.service.IReportSettlementService;
import org.jeecg.ctop.finance.settlement.service.serviceImpl.FileLoaderImpl;
import org.jeecg.ctop.finance.utils.SettlementUtil;
import org.jeecg.ctop.finance.utils.createExcelByTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * 导出 结算单 利润表
 * Administrator
 * 2021/7/28
 **/

@Slf4j
@RestController
@RequestMapping("/exportReportDemoController")
public class DemoReportController {

    @Autowired
    private IReportSettlementService reportSettlementService;

    @ApiOperation(value="财务结算-结算单导出", notes="财务结算-结算单导出")
    @GetMapping(value = "/exportSettlementReport")
    public Result exportSettlementReport(HttpServletResponse response) {

       // byte[] img = SettlementUtil.getByteImgByUrl("https://media-1301855440.cos.ap-chongqing.myqcloud.com/image/2021-08-05/2-1628129040416.jpg");

        List<SettlementReportBytedanceVo> list = reportSettlementService.getAccountTransactionDayBytedance();



        Workbook workbook = ExcelExportUtil.exportExcel(new ExportParams("这是表头", "这是sheet名称"), SettlementReportBytedanceVo.class, list);


        try {
            response.setCharacterEncoding("UTF-8");
            response.setHeader("content-Type", "application/vnd.ms-excel");
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("文件名称.xlsx", "UTF-8"));
            workbook.write(response.getOutputStream());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }


       return null;
    }



    @ApiOperation(value="财务结算-模板结算单导出", notes="财务结算-模板结算单导出")
    @GetMapping(value = "/exportImg")
    public String exportImg(HttpServletResponse response) throws Exception {

       // byte[] img = SettlementUtil.getByteImgByUrl("https://media-1301855440.cos.ap-chongqing.myqcloud.com/image/2021-08-05/2-1628129040416.jpg");

        TemplateExportParams params = new TemplateExportParams("C://Users//Administrator//Desktop//bytedance.xlsx",true);
       // params.setSheetName("这是sheet名称");
        params.setSheetName(new String[]{"这是sheet名称1","这是sheet名称2"});

        // 重要代码
        //POICacheManager.setFileLoader(new FileLoaderImpl());
        POICacheManager.setFileLoder(new FileLoaderImpl());

        Map<String, Object> map = new HashMap<String, Object>();
        List<SettlementReportBytedanceVo> list = reportSettlementService.getAccountTransactionDayBytedance();
        List<Map<String, Object>> pictureList = new ArrayList<Map<String, Object>>() ;

        Map<String,Object> picture1 = new HashMap<String, Object>();
        Map<String,Object> picture2 = new HashMap<String, Object>();
       byte[] datas =  SettlementUtil.getByteImgByUrl("https://media-1301855440.cos.ap-chongqing.myqcloud.com/image/2021-08-05/2-1628129040416.jpg");
        ImageEntity img = new ImageEntity();
        img.setUrl("https://media-1301855440.cos.ap-chongqing.myqcloud.com/image/2021-08-05/2-1628129040416.jpg");
        //img.setUrl("C:\\Users\\Administrator\\Desktop\\汇创\\20210507161223.jpg");
        img.setHeight(1000);
        img.setWidth(500);
        picture1.put("imag", img);
        picture2.put("imag", img);
        pictureList.add(picture1);
        pictureList.add(picture2);

        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("l",list);
        resultMap.put("p",pictureList);

        try {
            Workbook workbook = ExcelExportUtil.exportExcel(params, resultMap);
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/vnd.ms-excel;charset=UTF-8");
            response.setHeader("Pragma", "no-cache");
            response.setHeader("Cache-Control", "no-cache");
            response.setDateHeader("Expires", 0);
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("文件名称.xlsx", "UTF-8"));
            OutputStream output = response.getOutputStream();
            BufferedOutputStream bufferedOutPut = new BufferedOutputStream(output);
            workbook.write(bufferedOutPut);
            bufferedOutPut.flush();
            bufferedOutPut.close();
            output.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

       return "123";
    }


    @ApiOperation(value="财务结算-结算单导出", notes="财务结算-结算单导出")
    @GetMapping(value = "/demo")
    public String demo(HttpServletResponse response) throws Exception {
        //第一步创建workbook
        HSSFWorkbook wb = new HSSFWorkbook();

        HSSFCellStyle style = wb.createCellStyle();
        style.setAlignment(HorizontalAlignment.CENTER);//水平居中

        HSSFFont font = wb.createFont();
        font.setFontName("黑体");
        font.setFontHeightInPoints((short) 12);//设置字体大小
        style.setFont(font);

        //第二步创建sheet
        HSSFSheet sheet = wb.createSheet("账户id");

        sheet.autoSizeColumn(1,true);

        HSSFRow row1 = sheet.createRow(0);
        HSSFCell cell1 = row1.createCell(0);     //第一个单元格
        cell1.setCellValue("头条");         //设定值
        CellRangeAddress region = new CellRangeAddress(0, 0, 0, 1);
        sheet.addMergedRegion(region);
        cell1.setCellStyle(style);

        //第三步创建行row:添加表头0行
        HSSFRow row = sheet.createRow(1);

        //第四步创建单元格
        HSSFCell cell = row.createCell(0);     //第一个单元格
        cell.setCellValue("测试1");         //设定值
        cell.setCellStyle(style);          //内容居中

        cell = row.createCell(1);          //第二个单元格
        cell.setCellValue("测试2");
        cell.setCellStyle(style);

        List<SettlementReportBytedanceVo> list = reportSettlementService.getAccountTransactionDayBytedance();
        for (int i = 0; i < list.size(); i++) {
            SettlementReportBytedanceVo vo = list.get(i);
            //创建行
            row = sheet.createRow(i+2);
            row.setRowStyle(style);
            //创建单元格并且添加数据
            row.createCell(0).setCellValue(vo.getAdvertiserId());
            row.createCell(1).setCellValue(vo.getDate());
        }

        FileOutputStream fileOut = null;
        BufferedImage bufferImg = null;

        //先把读进来的图片放到一个ByteArrayOutputStream中，以便产生ByteArray
        ByteArrayOutputStream byteArrayOut = new ByteArrayOutputStream();
        //bufferImg = ImageIO.read(new File("C:\\Users\\Administrator\\Desktop\\汇创\\20210507161223.jpg"));
        //bufferImg = ImageIO.read(new File(URLDecoder.decode("https://media-1301855440.cos.ap-chongqing.myqcloud.com/image/2021-08-05/2-1628129040416.jpg","utf-8")));
        String imagePath = "https://media-1301855440.cos.ap-chongqing.myqcloud.com/image/2021-08-05/2-1628129040416.jpg";
        //InputStream is = new FileInputStream(imagePath);
        InputStream is = createExcelByTemplate.getInputStreamByUrl(imagePath);
        bufferImg = ImageIO.read(is);

        ImageIO.write(bufferImg, imagePath.substring(imagePath.lastIndexOf(".")+1), byteArrayOut);

        //画图的顶级管理器，一个sheet只能获取一个
        HSSFPatriarch patriarch = sheet.createDrawingPatriarch();
        //anchor主要用于设置图片的属性
        //HSSFClientAnchor anchor = new HSSFClientAnchor(0, 0, 255, 255,(short) 1, 1, (short) 5, 8);
        HSSFClientAnchor anchor = new HSSFClientAnchor(0, 0, 255, 255,(short) 5, list.size()+6, (short) 10, 40);
        HSSFClientAnchor anchor2 = new HSSFClientAnchor(0, 0, 255, 255,(short) 5, list.size()+40, (short) 10, 40*2);
        anchor.setAnchorType(3);
        //插入图片
        patriarch.createPicture(anchor, wb.addPicture(byteArrayOut.toByteArray(), HSSFWorkbook.PICTURE_TYPE_JPEG));
        patriarch.createPicture(anchor2, wb.addPicture(byteArrayOut.toByteArray(), HSSFWorkbook.PICTURE_TYPE_JPEG));


        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/vnd.ms-excel;charset=UTF-8");
        response.setHeader("Pragma", "no-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);
        response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("文件名称.xlsx", "UTF-8"));
        OutputStream output = response.getOutputStream();
        BufferedOutputStream bufferedOutPut = new BufferedOutputStream(output);
        wb.write(bufferedOutPut);
        bufferedOutPut.flush();
        bufferedOutPut.close();
        output.close();
       return "123";
    }
}