package com.tmerclub.cloud.user.handler;

import com.alibaba.excel.util.BooleanUtils;
import com.alibaba.excel.write.handler.RowWriteHandler;
import com.alibaba.excel.write.handler.context.RowWriteHandlerContext;
import com.tmerclub.cloud.user.dto.AllinpayUserExcelDTO;
import com.tmerclub.cloud.user.dto.UserExcelDTO;
import org.apache.poi.ss.usermodel.Comment;
import org.apache.poi.ss.usermodel.Drawing;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.xssf.usermodel.XSSFClientAnchor;
import org.apache.poi.xssf.usermodel.XSSFRichTextString;

/**
 * @author gaozijie
 * @since 2024-01-02
 */
public class UserRowWriterHandler implements RowWriteHandler {

    private boolean isSetComment = false;

    private boolean isAllinpay;

    public UserRowWriterHandler(boolean isAllinpay) {
        this.isAllinpay = isAllinpay;
    }

    @Override
    public void afterRowDispose(RowWriteHandlerContext context) {
        // 表头批注
        if (BooleanUtils.isTrue(context.getHead()) && !isSetComment) {
            Sheet sheet = context.getWriteSheetHolder().getSheet();
            Drawing<?> drawingPatriarch = sheet.createDrawingPatriarch();
            // 批注准备
            int[] commentIndex;
            String[] comments;
            if (isAllinpay) {
                commentIndex = UserExcelDTO.COMMENT_INDEX;
                comments = UserExcelDTO.COMMENTS;
            } else {
                commentIndex = AllinpayUserExcelDTO.COMMENT_INDEX;
                comments = AllinpayUserExcelDTO.COMMENTS;
            }
            // 插入批注
            Comment comment;
            for (int i = 0; i < commentIndex.length; i++) {
                comment = drawingPatriarch.createCellComment(new XSSFClientAnchor(0, 0, 0, 0, commentIndex[i], 0, commentIndex[i] + 1, 1));
                comment.setString(new XSSFRichTextString(comments[i]));
                sheet.getRow(0).getCell(commentIndex[i]).setCellComment(comment);
            }
            isSetComment = true;
        }
    }
}
