package com.engine.recruit.service.impl;

import cn.hutool.core.convert.Convert;
import com.engine.core.impl.Service;
import com.engine.recruit.conn.ApplicantCommonInfo;
import com.engine.recruit.entity.common.ImportLog;
import com.engine.recruit.exception.CustomizeRunTimeException;
import com.engine.recruit.service.WrittenResultsService;
import com.engine.recruit.util.ExcelUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import weaver.conn.RecordSet;
import weaver.file.ImageFileManager;

import java.io.IOException;
import java.util.*;

/**
 * @author:dxfeng
 * @createTime: 2024/01/24
 * @version: 1.0
 */
public class WrittenResultsServiceImpl extends Service implements WrittenResultsService {
    @Override
    public Map<String, Object> getFormCondition() {
        return null;
    }

    @Override
    public Map<String, Object> importExcel(Map<String, Object> params) {
        Integer excelId = Convert.toInt(params.get("excel"));
        ImageFileManager manager = new ImageFileManager();
        manager.getImageFileInfoById(excelId);

        XSSFWorkbook workbook;
        try {
            workbook = new XSSFWorkbook(manager.getInputStream());
        } catch (IOException e) {
            throw new CustomizeRunTimeException(e);
        }
        // 当前sheet
        XSSFSheet sheetAt = workbook.getSheetAt(0);
        // 最后一行
        int lastRowNum = sheetAt.getLastRowNum();
        if (lastRowNum < 1) {
            throw new CustomizeRunTimeException("导入数据为空");
        }
        // 最后一列
        short lastCellNum = sheetAt.getRow(0).getLastCellNum();
        Map<String, Integer> keyMap = new HashMap<>(16);
        // 标题行
        for (int cellIndex = 0; cellIndex < lastCellNum; cellIndex++) {
            XSSFRow row = sheetAt.getRow(0);
            if (row == null) {
                throw new CustomizeRunTimeException("表单字段名称获取失败，请检查Excel文件");
            }
            XSSFCell cell = row.getCell((short) cellIndex);
            String cellValue = ExcelUtil.getCellValue(cell).trim();
            keyMap.put(cellValue, cellIndex);
        }
        // 校验必填列
        checkRequiredFields(keyMap, "ID", "笔试成绩", "笔试结果");

        Integer idCellNum = keyMap.get("ID");
        Integer scoreCellNum = keyMap.get("笔试成绩");
        Integer resultCellNum = keyMap.get("笔试结果");

        return updateWrittenResult(sheetAt, lastRowNum, idCellNum, scoreCellNum, resultCellNum);
    }


    /**
     * 更新笔试结果
     *
     * @param sheetAt
     * @param lastRowNum
     * @param idCellNum
     * @param scoreCellNum
     * @param resultCellNum
     * @return
     */
    private Map<String, Object> updateWrittenResult(XSSFSheet sheetAt, int lastRowNum, Integer idCellNum, Integer scoreCellNum, Integer resultCellNum) {
        Map<String, Object> resultMap = new HashMap<>(4);
        Integer allCount = 0;
        Integer successCount = 0;
        Integer failCount = 0;
        List<ImportLog> logList = new ArrayList<>();
        RecordSet rs = new RecordSet();
        for (int rowIndex = 1; rowIndex <= lastRowNum; rowIndex++) {
            allCount++;
            XSSFRow row = sheetAt.getRow(rowIndex);
            if (null == row) {
                continue;
            }
            List<String> descriptionList = new ArrayList<>();
            boolean success = true;
            XSSFCell idCell = row.getCell(idCellNum);
            String ideCellValue = ExcelUtil.getCellValue(idCell).trim();
            if (StringUtils.isBlank(ideCellValue)) {
                descriptionList.add("[ID]为空");
                success = false;
            }
            XSSFCell scoreCell = row.getCell(scoreCellNum);
            String scoreCellValue = ExcelUtil.getCellValue(scoreCell).trim();
            if (StringUtils.isBlank(scoreCellValue)) {
                descriptionList.add("[笔试成绩]为空");
                success = false;
            }
            XSSFCell resultCell = row.getCell(resultCellNum);
            String resultCellValue = ExcelUtil.getCellValue(resultCell).trim();
            if (StringUtils.isBlank(resultCellValue)) {
                descriptionList.add("[笔试结果]为空");
                success = false;
            }
            if (StringUtils.isNotBlank(resultCellValue)) {
                resultCellValue = convertResultValue(resultCellValue);
                if (StringUtils.isBlank(resultCellValue)) {
                    descriptionList.add("[笔试结果]转换失败");
                    success = false;
                }
            }

            // 更新笔试成绩
            if (success) {
                rs.executeUpdate("update uf_jcl_bs set bscj = ? ,bsjg = ? where id = ? ", scoreCellValue, resultCellValue, ideCellValue);
                String exceptionMsg = rs.getExceptionMsg();
                if (StringUtils.isNotBlank(exceptionMsg)) {
                    descriptionList.add(exceptionMsg);
                    success = false;
                }
            }
            if (success) {
                successCount++;
            } else {
                failCount++;
            }

            ImportLog importLog = ImportLog.builder().
                    rowIndex(rowIndex + 1) // 对应Excel的行，从1开始累加
                    .description(success ? "导入成功" : StringUtils.join(descriptionList, ","))
                    .status(String.valueOf(success))
                    .build();
            logList.add(importLog);
        }
        resultMap.put("log", logList);
        resultMap.put("allCount", allCount);
        resultMap.put("successCount", successCount);
        resultMap.put("failCount", failCount);
        return resultMap;
    }


    /**
     * 标题行、校验必填列
     *
     * @param keyMap         字段集合
     * @param requiredFields 必填字段
     */
    private void checkRequiredFields(Map<String, Integer> keyMap, String... requiredFields) {
        // 校验必填列
        Set<String> keySet = keyMap.keySet();
        for (String field : requiredFields) {
            if (!keySet.contains(field)) {
                throw new CustomizeRunTimeException("未获取到必填列[" + field + "]");
            }
        }
    }

    /**
     * 转化笔试结果的值
     *
     * @param resultCellValue
     * @return
     */
    private String convertResultValue(String resultCellValue) {
        int formId = ApplicantCommonInfo.getFormIdByTableName("uf_jcl_bs");
        return ApplicantCommonInfo.getSelectValue(String.valueOf(formId), "bsjg", resultCellValue);
    }
}
