package com.tmerclub.cloud.product.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.api.auth.constant.SysTypeEnum;
import com.tmerclub.cloud.product.vo.SpuExcelVO;
import com.tmerclub.cloud.product.vo.SupplierProdExcelVO;
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;

import java.util.Objects;

/**
 * 商品excel批注处理
 *
 * @author gaozijie
 * @date 2023-04-06
 */
public class ProductCommentWriteHandler implements RowWriteHandler {

    /**
     * @see SysTypeEnum
     */
    private final Integer sysType;

    private boolean isSetComment;

    public ProductCommentWriteHandler(Integer sysType) {
        this.sysType = sysType;
    }

    @Override
    public void afterRowDispose(RowWriteHandlerContext context) {
        // 表头存在两行(会导致执行两次，加多一个字段进行区分判断)
        if (BooleanUtils.isTrue(context.getHead()) && !isSetComment) {
            Sheet sheet = context.getWriteSheetHolder().getSheet();
            Drawing<?> drawingPatriarch = sheet.createDrawingPatriarch();
            // 准备批注信息(区分商家or供应商)
            int[] commentIndex = {};
            String[] comments = {};
            if (Objects.equals(SysTypeEnum.MULTISHOP.value(), sysType)) {
                commentIndex = SpuExcelVO.COMMENT_INDEX;
                comments = SpuExcelVO.COMMENTS;
            } else if (Objects.equals(SysTypeEnum.SUPPLIER.value(), sysType)) {
                commentIndex = SupplierProdExcelVO.COMMENT_INDEX;
                comments = SupplierProdExcelVO.COMMENTS;
            }
            // 插入批注
            Comment comment;
            for (int i = 0; i < commentIndex.length; i++) {
                comment = drawingPatriarch.createCellComment(new XSSFClientAnchor(0, 0, 0, 0, commentIndex[i], 1, commentIndex[i] + 1, 2));
                comment.setString(new XSSFRichTextString(comments[i]));
                sheet.getRow(0).getCell(commentIndex[i]).setCellComment(comment);
            }
            isSetComment = true;
        }
    }

}
