package com.artfess.cqxy.ledger.manager.impl;

import com.artfess.base.query.FieldSort;
import com.artfess.base.query.QueryFilter;
import com.artfess.cqxy.ledger.manager.ChangeLedgerManager;
import com.artfess.cqxy.processManagermant.manager.ChangeManagementManager;
import com.artfess.cqxy.processManagermant.model.ChangeManagement;
import com.artfess.cqxy.utils.BizUtils;
import com.artfess.poi.util.ExcelUtil;
import com.artfess.sysConfig.persistence.manager.SysDictionaryManager;
import com.artfess.sysConfig.persistence.param.DictModel;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author Limuhua
 * @date 2022/3/31 11:42
 */
@Service
public class ChangeLedgerManagerImpl implements ChangeLedgerManager {

    @Autowired
    ChangeManagementManager cmm;
    @Autowired
    private SysDictionaryManager sdm;

    @Override
    public void exportDataToExcel(QueryFilter<ChangeManagement> queryFilter, HttpServletResponse response) throws IOException {
        // 去除分页
        queryFilter.getPageBean().setPageSize(-1);
        // 文件名
        String fileName = "变更管理台账";
        // 获取字典
        List<DictModel> changeType = sdm.queryDictListItemsByCode("gcgl-bglx");
        // 创建excel工作薄
        HSSFWorkbook workbook = new HSSFWorkbook();
        // 获取数据
        queryFilter.withSorter(new FieldSort("bcm.PROJECT_ID_"));
        queryFilter.withSorter(new FieldSort("bcm.CHANGE_DATE_"));
        Map<String, List<ChangeManagement>> data = groupList(cmm.queryAllByPage(queryFilter).getRows());
        if(data.isEmpty()){
            throw new RuntimeException("没有可导出的数据");
        }
        // 处理数据
        for(String key : data.keySet()){
            // 数据
            List<ChangeManagement> list = data.get(key);
            // sheet名，get(0)不会越界
            String sheetName = list.get(0).getProjectInfo().getProjectName()+fileName;
            // 创建excel表
            HSSFSheet sheet = workbook.createSheet(sheetName);
            //创建样式
            HSSFCellStyle cellStyle = workbook.createCellStyle();
            //设置字体
            HSSFFont font = workbook.createFont();
            //设置字体名称
            font.setFontName("宋体");
            cellStyle.setFont(font);
            // 创建标题行
            // 第一行
            HSSFRow titleRow = sheet.createRow(0);
            BizUtils.handelCell(workbook,sheetName, titleRow.createCell(0), sheetName, true);
            sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, 8));
            // 第二行
            HSSFRow titleRow1 = sheet.createRow(1);
            String[] heards = {"序号", "项目名称", "变更类型", "变更内容描述", "变更编号", "变更增加（减少）投资金额", "变更时间", "审批机构", "备注"};
            for (int i = 0; i < heards.length; i++) {
                BizUtils.handelCell(workbook,sheetName, titleRow1.createCell(i), heards[i], true);
            }
            // 数据行，从第2行开始
            int row = 2;
            // 序号标志
            int index = 1;
            for(ChangeManagement ele:list){
                HSSFRow dataRow = sheet.createRow(row);
                BizUtils.handelCell(workbook,cellStyle,font,sheetName, dataRow.createCell(0), String.valueOf(index));
                BizUtils.handelCell(workbook,cellStyle,font,sheetName, dataRow.createCell(1), ele.getProjectInfo().getProjectName());
                BizUtils.handelCell(workbook,cellStyle,font,sheetName, dataRow.createCell(2), BizUtils.getDicValueByCode(changeType,ele.getChangeType()));
                BizUtils.handelCell(workbook,cellStyle,font,sheetName, dataRow.createCell(3), ele.getChangeContent());
                BizUtils.handelCell(workbook,cellStyle,font,sheetName, dataRow.createCell(4), ele.getChangeCode());
                BizUtils.handelCell(workbook,cellStyle,font,sheetName, dataRow.createCell(5), String.valueOf(ele.getChangePrice()));
                BizUtils.handelCell(workbook,cellStyle,font,sheetName, dataRow.createCell(6), BizUtils.handleDateFormat(ele.getChangeDate()));
                BizUtils.handelCell(workbook,cellStyle,font,sheetName, dataRow.createCell(7), "");
                BizUtils.handelCell(workbook,cellStyle,font,sheetName, dataRow.createCell(8), ele.getRemarks());
                row++;
                index++;
            }
        }
        ExcelUtil.downloadExcel(workbook, fileName, response);
    }


    /**
     * 对list进行分组
     * @param list list
     * @return map
     */
    private Map<String, List<ChangeManagement>> groupList(List<ChangeManagement> list){
        Map<String, List<ChangeManagement>> resultMap = new HashMap<String, List<ChangeManagement>>();
        for (ChangeManagement ele : list) {
            //map中已存在，将该数据存放到同一个key的map中
            if (resultMap.containsKey(ele.getProjectId())) {
                resultMap.get(ele.getProjectId()).add(ele);
            } else {//map中不存在，新建key
                List<ChangeManagement> tmpList = new ArrayList<ChangeManagement>();
                tmpList.add(ele);
                resultMap.put(ele.getProjectId(), tmpList);
            }
        }
        return resultMap;
    }

}
