package com.saye.hospitalgd.controller.FinancialReconciliation;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.saye.hospitalgd.commons.date.DateDUtil;
import com.saye.hospitalgd.commons.log.ExceptionDUtil;
import com.saye.hospitalgd.commons.log.LogUtil;
import com.saye.hospitalgd.commons.string.StringDUtil;
import com.saye.hospitalgd.model.StatusDefine;
import com.saye.hospitalgd.service.ReconciliationResultService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.awt.*;
import java.io.File;
import java.io.FileOutputStream;
import java.util.List;
import java.util.*;

/**
 * @author thuang
 * @version 1.0
 * @description: 对账结果
 * @date 2021/8/31 10:17
 */
@Api(tags = "对账结果相关接口")
@Controller
@RequestMapping("/reconciliationResult")
public class ReconciliationResultController {

    @Autowired
    private ReconciliationResultService reconciliationResultService;

    @RequestMapping("/toReconciliationResult")
    public String toReconciliationResult(ModelMap modelMap) {

        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());

        calendar.add(Calendar.DATE, -1);
        Date startDate = calendar.getTime();

        String startTime = DateDUtil.DateToStr(DateDUtil.yyyy_MM_dd, startDate);
        String endTime = DateDUtil.getCurrentDate(DateDUtil.yyyy_MM_dd);

        modelMap.addAttribute("startTime", startTime);
        modelMap.addAttribute("endTime", endTime);

        return "financialReconciliation/reconciliationResult";
    }

    /**
     * @description: 查询对账的结果记录
     * @author thuang
     * @date 2021/8/30 14:30
     * @version 1.0
     */
    @RequestMapping("/findReconciliationResultPageList")
    @ResponseBody
    @ApiOperation(value = "查询对账的结果记录")
    public HashMap<Object, Object> findReconciliationResultPageList(@ApiParam(name = "开始时间") String startTime,
                                                                    @ApiParam(name = "结束时间") String endTime,
                                                                    @ApiParam(name = "页码") int page,
                                                                    @ApiParam(name = "每页限制个数") int limit) {
        HashMap<Object, Object> responseMap = new HashMap<Object, Object>();

        try {
            HashMap<Object, Object> map = new HashMap<Object, Object>();
            map.put("startTime", startTime);
            map.put("endTime", endTime);

            PageHelper.startPage(page, limit);
            PageInfo<HashMap<Object, Object>> pageInfo = new PageInfo<HashMap<Object, Object>>(reconciliationResultService.findReconciliationResultPageList(map));

            responseMap.put("code", 0);
            responseMap.put("msg", "OK");
            responseMap.put("count", pageInfo.getTotal());
            responseMap.put("data", pageInfo.getList());
        } catch (Exception e) {
            e.printStackTrace();
            String msg = e.getMessage();
            responseMap.put("code", 1);
            responseMap.put("msg", "查询失败,原因：" + msg);
        }

        return responseMap;
    }


    /**
     * @description: 导出对账结果excel
     * @author thuang
     * @date 2021/10/22 10:43
     * @version 1.0
     */
    @PostMapping("/exportReconciliationResult")
    @ResponseBody
    @ApiOperation(value = "导出对账结果excel")
    public HashMap<Object, Object> exportReconciliationResult(@RequestBody HashMap<Object, Object> map) {
        HashMap<Object, Object> responseMap = new HashMap<Object, Object>();
        String errCode = "0";
        String errMsg = "";
        String dlName = "";
        String fileName = "";

        String dowloadName = StringDUtil.changeNullToEmpty(map.get("dowloadName"));

        try {
            String startTime = StringDUtil.changeNullToEmpty(map.get("startTime"));
            String endTime = StringDUtil.changeNullToEmpty(map.get("endTime"));

            List<HashMap<Object, Object>> list = reconciliationResultService.findReconciliationResultPageList(map);

            if (list != null && list.size() > 0) {

                //创建工作薄对象
                XSSFWorkbook xwb = new XSSFWorkbook();//这里也可以设置sheet的Name
                //创建工作表对象
                XSSFSheet sheet = xwb.createSheet("sheet0");
                //设置主标题样式
                XSSFFont mainTitleFont = xwb.createFont();
                mainTitleFont.setFontName("宋体");
                mainTitleFont.setBoldweight(XSSFFont.BOLDWEIGHT_BOLD);//字体加粗
                mainTitleFont.setFontHeightInPoints((short) 14);// 字体大小
                XSSFCellStyle mainTitleStyle = xwb.createCellStyle();
                mainTitleStyle.setFont(mainTitleFont);
                mainTitleStyle.setAlignment(XSSFCellStyle.ALIGN_CENTER);// 左右居中
                mainTitleStyle.setVerticalAlignment(XSSFCellStyle.VERTICAL_CENTER);// 上下居中
                mainTitleStyle.setLocked(true);
                //标题样式
                XSSFFont titleFont = xwb.createFont();
                titleFont.setFontName("宋体");
                titleFont.setBoldweight(XSSFFont.BOLDWEIGHT_BOLD);//字体加粗
                titleFont.setFontHeightInPoints((short) 10);// 字体大小
                XSSFCellStyle titleStyle = xwb.createCellStyle();
                titleStyle.setFont(titleFont);
                titleStyle.setAlignment(XSSFCellStyle.ALIGN_CENTER);// 左右居中
                titleStyle.setVerticalAlignment(XSSFCellStyle.VERTICAL_CENTER);// 上下居中
                titleStyle.setFillForegroundColor(new XSSFColor(new Color(225, 225, 225)));
                titleStyle.setFillBackgroundColor(new XSSFColor(new Color(225, 225, 225)));
                titleStyle.setFillPattern(XSSFCellStyle.SPARSE_DOTS);
                titleStyle.setBorderBottom(XSSFCellStyle.BORDER_THIN); // 下边框
                titleStyle.setBorderLeft(XSSFCellStyle.BORDER_THIN);// 左边框
                titleStyle.setBorderTop(XSSFCellStyle.BORDER_THIN);// 上边框
                titleStyle.setBorderRight(XSSFCellStyle.BORDER_THIN);// 右边框
                titleStyle.setLocked(true);
                //内容样式
                XSSFFont contentFont = xwb.createFont();
                contentFont.setFontName("宋体");
                contentFont.setFontHeightInPoints((short) 10);// 字体大小
                XSSFCellStyle contentStyle = xwb.createCellStyle();
                contentStyle.setFont(contentFont);
                contentStyle.setAlignment(XSSFCellStyle.ALIGN_CENTER);// 左右居中
                contentStyle.setVerticalAlignment(XSSFCellStyle.VERTICAL_CENTER);// 上下居中
                contentStyle.setBorderBottom(XSSFCellStyle.BORDER_THIN); // 下边框
                contentStyle.setBorderLeft(XSSFCellStyle.BORDER_THIN);// 左边框
                contentStyle.setBorderTop(XSSFCellStyle.BORDER_THIN);// 上边框
                contentStyle.setBorderRight(XSSFCellStyle.BORDER_THIN);// 右边框
                contentStyle.setWrapText(true);
                contentStyle.setLocked(true);

                //标题
                LinkedHashMap<String, String> titleMap = new LinkedHashMap<>();
//                titleMap.put("院区", "1,2");//一列两行
                titleMap.put("日期", "1,2");
                titleMap.put("结算金额", "4,1");
                titleMap.put("单边账", "2,1");
                titleMap.put("对账情况", "1,1");

                //第二行标题
                List<String> titleList2 = new ArrayList<>();
                titleList2.add("第三方支付结算");
                titleList2.add("HIS结算金额");
                titleList2.add("三方单边账");
                titleList2.add("HIS单边账");
                titleList2.add("处理历史单边账金额");
                titleList2.add("当日结算单边账条数");
                titleList2.add("是否通过");

                //内容key
                List<String> contentKey = new ArrayList<>();
//                contentKey.add("AREA");
                contentKey.add("TRADE_DATE");
                contentKey.add("THIRD_MONEY");
                contentKey.add("HIS_MONEY");
                contentKey.add("THIRD_UNILATERAL");
                contentKey.add("HIS_UNILATERAL");
                contentKey.add("MANAGER_HISTORY_UNILATERAL");
                contentKey.add("UNILATERAL_NUM");
                contentKey.add("STATUS_STR");

                //定义列宽
                sheet.setColumnWidth(0, 5000);
                sheet.setColumnWidth(1, 5000);
                sheet.setColumnWidth(2, 5000);
                sheet.setColumnWidth(3, 5000);
                sheet.setColumnWidth(4, 5000);
                sheet.setColumnWidth(5, 5000);
                sheet.setColumnWidth(6, 5000);
                sheet.setColumnWidth(7, 5000);
//                sheet.setColumnWidth(8, 5000);

                //刚开始先创建大标题
                //设置行单元格合并
                sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, 7));
                //创建工作表的行
                XSSFRow mainRow = sheet.createRow(0);//设置第一行，从零开始
                mainRow.setHeight((short) 375);
                XSSFCell mainCell = mainRow.createCell(0);
                mainCell.setCellStyle(mainTitleStyle);
                mainCell.setCellValue(startTime + "~" + endTime + "对账结果表（金额单位：元）");

                //创建标题行
                XSSFRow titleRow1 = sheet.createRow(1);
                XSSFRow titleRow2 = sheet.createRow(2);

                int thisColNum = 0;
                for (String title : titleMap.keySet()) {
                    String value = titleMap.get(title);

                    String[] split = value.split(",");
                    int colNum = Integer.parseInt(split[0]);
                    int rowNum = Integer.parseInt(split[1]);


                    XSSFCell cell = titleRow1.createCell(thisColNum);
                    cell.setCellStyle(titleStyle);
                    cell.setCellValue(title);

                    if (rowNum != 1) {

                        XSSFCell cell2 = titleRow2.createCell(thisColNum);
                        cell2.setCellStyle(titleStyle);

                        sheet.addMergedRegion(new CellRangeAddress(1, rowNum, thisColNum, thisColNum));
                    }
                    if (colNum != 1) {
                        for (int i = 1; i < colNum; i++) {
                            XSSFCell cell2 = titleRow1.createCell(thisColNum + i);
                            cell2.setCellStyle(titleStyle);
                        }

                        sheet.addMergedRegion(new CellRangeAddress(1, 1, thisColNum, thisColNum + colNum - 1));
                    }

                    //将大小加上 之后计算起始要用到
                    thisColNum = thisColNum + colNum;
                }

                //第二行标题
                int title2StartCol = 1; //第二行标题开始列是第三列
                for (int i = 0; i < titleList2.size(); i++) {
                    String title2 = titleList2.get(i);
                    XSSFCell cell2 = titleRow2.createCell(title2StartCol + i);
                    cell2.setCellStyle(titleStyle);
                    cell2.setCellValue(title2);
                }

                //循环内容
                int startRow = 3; //标题加上抬头名称 共用了三行
                for (int i = 0; i < list.size(); i++) {
                    int thisRow = startRow + i;
                    XSSFRow contentRow = sheet.createRow(thisRow);
                    HashMap<Object, Object> hashMap = list.get(i);
                    for (int j = 0; j < contentKey.size(); j++) {
                        String s = contentKey.get(j);
                        String content = StringDUtil.changeNullToEmpty(hashMap.get(s));
                        XSSFCell otherCell = contentRow.createCell(j);
                        otherCell.setCellStyle(contentStyle);
                        otherCell.setCellValue(content);
                    }
                }

                String randomStr = StringDUtil.generateRandomCodeForLength(4);
                dlName = DateDUtil.DateToStr(DateDUtil.yyyyMMddHHmmss, new Date()) + randomStr;
                fileName = dlName + ".xlsx";

                String uploadPath = StatusDefine.filePath + "/ReconciliaionResult/";
                File uploadPathFile = new File(uploadPath);
                if (!uploadPathFile.exists()) uploadPathFile.mkdirs();

                String savePath = uploadPath + fileName;
                // 设置输入流
                FileOutputStream fOut = new FileOutputStream(savePath);
                // 将模板的内容写到输出文件上
                xwb.write(fOut);
                fOut.flush();

                // 操作结束，关闭文件
                fOut.close();
            }
        } catch (Exception e) {
            errCode = "999";
            errMsg = "未知异常：" + ExceptionDUtil.getDetailExceptionMsg(e);
            LogUtil.error(this.getClass(), "@@@系统出错！【" + errMsg + "】");
        }

        responseMap.put("errCode", errCode);
        responseMap.put("errMsg", errMsg);
        responseMap.put("dlName", "ReconciliaionResult/" + fileName);
        return responseMap;
    }


}
