package com.codvision.base.config.excel.custom;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.util.BooleanUtils;
import com.alibaba.excel.write.handler.CellWriteHandler;
import com.alibaba.excel.write.handler.context.CellWriteHandlerContext;
import com.alibaba.excel.write.metadata.style.WriteCellStyle;
import com.alibaba.excel.write.metadata.style.WriteFont;
import com.codvision.base.entity.ExcelErrorRecord;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFClientAnchor;
import org.apache.poi.xssf.usermodel.XSSFRichTextString;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 自定义拦截器，数据异常项设置字体颜色（红色）和错误信息批注
 *
 * @author hxl
 */
public class CustomErrorCellWriteHandler<T> implements CellWriteHandler {

    private final List<T> list;

    public CustomErrorCellWriteHandler(List<T> list) {
        this.list = list;
    }

    @Override
    public void afterCellDispose(CellWriteHandlerContext context) {
        Cell cell = context.getCell();
        if (BooleanUtils.isNotTrue(context.getHead()) && cell.getRowIndex() >= 1) {
            T t = list.get(cell.getRowIndex() - 1);
            if (t instanceof ExcelErrorRecord) {
                ExcelErrorRecord record = (ExcelErrorRecord) t;
                if (StringUtils.isBlank(record.getErrorMsgJson())) {
                    return;
                }

                // 根据表头字段获取对应的错误信息
                Map<String, Object> errorMsgMap = jsonToMap(record.getErrorMsgJson());
                String commentStr = (String) errorMsgMap.get(context.getHeadData().getFieldName());
                if (StringUtils.isNotBlank(commentStr)) {
                    // 设置标注
                    Sheet sheet = context.getWriteSheetHolder().getSheet();
                    Drawing<?> drawingPatriarch = sheet.createDrawingPatriarch();
                    Comment comment = drawingPatriarch.createCellComment(
                            new XSSFClientAnchor(0, 0, 0, 0, (short) cell.getColumnIndex(), cell.getRowIndex(),
                                    (short) cell.getColumnIndex() + 2, cell.getRowIndex() + 2));
                    comment.setString(new XSSFRichTextString(commentStr));
                    cell.setCellComment(comment);

                    // 设置字体颜色、加粗
                    WriteCellData<?> cellData = context.getFirstCellData();
                    WriteCellStyle writeCellStyle = cellData.getOrCreateStyle();
                    WriteFont cellWriteFont = new WriteFont();
                    cellWriteFont.setBold(true);
                    cellWriteFont.setColor(IndexedColors.RED.getIndex());
                    writeCellStyle.setWriteFont(cellWriteFont);
                }
            }
        }
    }

    private Map<String, Object> jsonToMap(String json) {
        Map<String, Object> resultMap = new HashMap<>(16);
        JSONObject jsonObject = JSONUtil.parseObj(json);
        for (Map.Entry<String, Object> next : jsonObject.entrySet()) {
            resultMap.put(next.getKey(), next.getValue());
        }
        return resultMap;
    }
}
