/*
 * Copyright [2022] [https://www.xiaonuo.vip]
 *
 * Snowy采用APACHE LICENSE 2.0开源协议，您在使用过程中，需要注意以下几点：
 *
 * 1.请不要删除和修改根目录下的LICENSE文件。
 * 2.请不要删除和修改Snowy源码头部的版权声明。
 * 3.本项目代码可免费商业使用，商业使用请保留源码和相关描述文件的项目出处，作者声明等。
 * 4.分发源码时候，请注明软件出处 https://www.xiaonuo.vip
 * 5.不可二次分发开源参与同类竞品，如有想法可联系团队xiaonuobase@qq.com商议合作。
 * 6.若您的项目无法满足以上几点，需要更多功能代码，获取Snowy商业授权许可，请在官网购买授权，地址为 https://www.xiaonuo.vip
 */
package com.unis.basic.info.modular.unReporCity.controller;

import cn.dev33.satoken.annotation.SaCheckPermission;
import com.aliyun.oss.common.utils.DateUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import com.github.xiaoymin.knife4j.annotations.ApiSupport;
import com.unis.basic.info.modular.unReporCity.entity.UnReporCity;
import com.unis.basic.info.modular.unReporCity.param.UnReporCityAddParam;
import com.unis.basic.info.modular.unReporCity.param.UnReporCityEditParam;
import com.unis.basic.info.modular.unReporCity.param.UnReporCityIdParam;
import com.unis.basic.info.modular.unReporCity.param.UnReporCityPageParam;
import com.unis.basic.info.modular.unReporCity.service.UnReporCityService;
import com.unis.common.annotation.CommonLog;
import com.unis.common.pojo.CommonResult;
import com.unis.common.pojo.CommonValidList;
import com.unis.common.util.CommonTimeFormatUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.beanutils.BeanUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.BorderStyle;
import org.apache.poi.ss.usermodel.FillPatternType;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.usermodel.VerticalAlignment;
import org.apache.poi.ss.util.CellRangeAddress;
import java.util.Map.Entry;
import javax.servlet.ServletOutputStream;




import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import javax.validation.constraints.NotEmpty;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.io.IOException;
import java.io.OutputStream;


/**
 * 漏报统计市州控制器
 *
 * @author weiyinbin
 * @date  2024/04/02 20:13
 */
@Api(tags = "漏报统计市州控制器")
@ApiSupport(author = "SNOWY_TEAM", order = 1)
@RestController
@Validated
public class UnReporCityController {

    @Resource
    private UnReporCityService unReporCityService;

    /**
     * 获取漏报统计市州分页
     *
     * @author weiyinbin
     * @date  2024/04/02 20:13
     */
    @ApiOperationSupport(order = 1)
    @ApiOperation("获取漏报统计市州分页")
    //@SaCheckPermission("/basic.info/unReporCity/page")
    @GetMapping("/basic.info/unReporCity/page")
    public CommonResult<Page<UnReporCity>> page(UnReporCityPageParam unReporCityPageParam) {
        return CommonResult.data(unReporCityService.page(unReporCityPageParam));
    }

    /**
     * 添加漏报统计市州
     *
     * @author weiyinbin
     * @date  2024/04/02 20:13
     */
    @ApiOperationSupport(order = 2)
    @ApiOperation("添加漏报统计市州")
    @CommonLog("添加漏报统计市州")
    @SaCheckPermission("/basic.info/unReporCity/add")
    @PostMapping("/basic.info/unReporCity/add")
    public CommonResult<String> add(@RequestBody @Valid UnReporCityAddParam unReporCityAddParam) {
        unReporCityService.add(unReporCityAddParam);
        return CommonResult.ok();
    }

    /**
     * 编辑漏报统计市州
     *
     * @author weiyinbin
     * @date  2024/04/02 20:13
     */
    @ApiOperationSupport(order = 3)
    @ApiOperation("编辑漏报统计市州")
    @CommonLog("编辑漏报统计市州")
    @SaCheckPermission("/basic.info/unReporCity/edit")
    @PostMapping("/basic.info/unReporCity/edit")
    public CommonResult<String> edit(@RequestBody @Valid UnReporCityEditParam unReporCityEditParam) {
        unReporCityService.edit(unReporCityEditParam);
        return CommonResult.ok();
    }

    /**
     * 删除漏报统计市州
     *
     * @author weiyinbin
     * @date  2024/04/02 20:13
     */
    @ApiOperationSupport(order = 4)
    @ApiOperation("删除漏报统计市州")
    @CommonLog("删除漏报统计市州")
    @SaCheckPermission("/basic.info/unReporCity/delete")
    @PostMapping("/basic.info/unReporCity/delete")
    public CommonResult<String> delete(@RequestBody @Valid @NotEmpty(message = "集合不能为空")
                                       CommonValidList<UnReporCityIdParam> unReporCityIdParamList) {
        unReporCityService.delete(unReporCityIdParamList);
        return CommonResult.ok();
    }

    /**
     * 获取漏报统计市州详情
     *
     * @author weiyinbin
     * @date  2024/04/02 20:13
     */
    @ApiOperationSupport(order = 5)
    @ApiOperation("获取漏报统计市州详情")
    @SaCheckPermission("/basic.info/unReporCity/detail")
    @GetMapping("/basic.info/unReporCity/detail")
    public CommonResult<UnReporCity> detail(@Valid UnReporCityIdParam unReporCityIdParam) {
        return CommonResult.data(unReporCityService.detail(unReporCityIdParam));
    }


    @ApiOperationSupport(order = 6)
    @ApiOperation("市州导出")
    //@SaCheckPermission("/basic.info/unReporCity/exportByEntity")
    @PostMapping("/basic.info/unReporCity/exportByEntity")
    public void exportByEntity(
            @RequestParam(value = "sysOrgId",required = false) String sysOrgId
            , HttpServletResponse response) {

        try {
            // 查询list
            UnReporCity unReporCity =new UnReporCity();
            if(sysOrgId != null && sysOrgId != ""){
                unReporCity.setSysOrgId(sysOrgId);
            }

            LocalDate today = LocalDate.now();
            int year = today.getYear();
            String date = year+"-01-01"+" 00:00:00";
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date ctime = simpleDateFormat.parse(date);
            unReporCity.setCreateTime(ctime);

            List<Map<String, Object>> data= unReporCityService.exportByEntityResult(unReporCity);

            LinkedHashMap<String, String> columnName = new LinkedHashMap<>();

            columnName.put("number","序号");
            columnName.put("sys_org_name","市州");
            columnName.put("un_report_count","漏报次数");
            columnName.put("false_report_count","错报次数");
            columnName.put("un_self_price_monitor_count","未在实地采集次数");

            // 输出Excel文件

            response.reset();
            String fileName = "漏报市州统计表";
            response.setHeader("content-disposition", "attachment;filename="
                    + new String(CommonTimeFormatUtil.getDate()) + ".xls");

            response.setContentType("application/vnd.ms-excel;charset=gb2312");
            ServletOutputStream output = response.getOutputStream();
            pojo3Excel(data, output, columnName,fileName);

            output.close();

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

        }
    }

    public static <T> void pojo3Excel(List<T> pojoList, OutputStream out, LinkedHashMap<String, String> alias,
                                      String fileName) throws Exception {
        // 创建一个工作簿
        HSSFWorkbook wb = new HSSFWorkbook();

        // 创建一个表
        HSSFSheet sheet = wb.createSheet(fileName);
        HSSFCellStyle contentStyle = createContentCellStyle(wb);
        // 创建第一行，作为表名
        HSSFRow row = sheet.createRow(0);
        row.setHeightInPoints(25);

        HSSFCell cell = row.createCell(0);
        cell.setCellValue(fileName);

        HSSFCellStyle cellStyle = wb.createCellStyle();
        cellStyle.setAlignment(HorizontalAlignment.CENTER);//水平居中
        cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);//垂直对齐
        cellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
        cellStyle.setFillForegroundColor(IndexedColors.GREY_40_PERCENT.getIndex());//背景颜色

        HSSFFont headerFont1 = (HSSFFont) wb.createFont(); // 创建字体样式
        headerFont1.setBold(true); //字体加粗
        headerFont1.setFontName("宋体"); // 设置字体类型
        headerFont1.setFontHeightInPoints((short) 12); // 设置字体大小
        cellStyle.setFont(headerFont1); // 为标题样式设置字体样式



        sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, 5));//合并第一行单元格


        for (int i = 1; i < pojoList.size()+1; i++) {
            HSSFRow tempRow = sheet.createRow(i);
            tempRow.setHeight((short) 350);
            for (int j = 0; j < 9; j++) {
                sheet.setColumnWidth(j, 4500);
                HSSFCell tempCell = tempRow.createCell(j);
                tempCell.setCellStyle(contentStyle);
            }

        }



        cell.setCellStyle(cellStyle);


        sheet.setDefaultColumnWidth(256*50);
        // 在第一行插入列名
        insertColumnName(1, sheet, alias);
        // *从第2行开始插入数据
        insertColumnDate(2, pojoList, sheet, alias);
        // 输出表格文件
        try {
            wb.write(out);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //wb.close();

        }
    }

    /**
     * 创建内容样式
     * @param wb
     * @return
     */
    private  static HSSFCellStyle createContentCellStyle(HSSFWorkbook wb) {
        HSSFCellStyle cellStyle = wb.createCellStyle();
        cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);// 垂直居中
        cellStyle.setAlignment(HorizontalAlignment.CENTER);// 水平居中
        //cellStyle.setWrapText(true);// 设置自动换行
        cellStyle.setBorderBottom(BorderStyle.THIN); //下边框
        cellStyle.setBorderLeft(BorderStyle.THIN); //左边框
        cellStyle.setBorderRight(BorderStyle.THIN); //右边框
        cellStyle.setBorderTop(BorderStyle.THIN); //上边框

        // 生成12号字体
        HSSFFont font = wb.createFont();
        font.setColor((short)8);
        font.setFontHeightInPoints((short) 9);
        cellStyle.setFont(font);

        return cellStyle;
    }


    private static void insertColumnName(int rowNum, HSSFSheet sheet, Map<String, String> alias) {
        HSSFRow row = sheet.createRow(rowNum);
        // 列的数量
        int columnCount = 0;

        Set<Entry<String, String>> entrySet = alias.entrySet();

        for (Entry<String, String> entry : entrySet) {
            // 创建第一行的第columnCount个格子
            HSSFCell cell = row.createCell(columnCount++);
            // 将此格子的值设置为alias中的键名
            cell.setCellValue(isNull(entry.getValue()).toString());
        }
    }


    private static Object isNull(Object object) {
        if (object != null) {
            return object;
        } else {
            return "0";
        }
    }



    /**
     * 从指定行开始插入数据
     *
     * @param beginRowNum
     *            开始行
     * @param models
     *            对象数组
     * @param sheet
     *            表
     * @param alias
     *            列别名
     * @throws Exception
     */
    private static <T> void insertColumnDate(int beginRowNum, List<T> models, HSSFSheet sheet,
                                             Map<String, String> alias) throws Exception {
        for (T model : models) {
            // 创建新的一行
            HSSFRow rowTemp = sheet.createRow(beginRowNum++);

            // 获取列的迭代
            Set<Entry<String, String>> entrySet = alias.entrySet();

            // 从第0个格子开始创建
            int columnNum = 0;
            for (Entry<String, String> entry : entrySet) {
                // 获取属性值
                String property = BeanUtils.getProperty(model, entry.getKey());
                // 创建一个格子
                HSSFCell cell = rowTemp.createCell(columnNum++);
                cell.setCellValue(property);
            }
        }
    }

}
