package com.ximai.common.utils.excel;

import com.alibaba.excel.write.handler.CellWriteHandler;
import com.alibaba.excel.write.handler.context.CellWriteHandlerContext;
import com.ximai.common.utils.MessageUtils;
import com.ximai.common.utils.data.StringUtils;
import org.springframework.context.NoSuchMessageException;

import java.lang.reflect.Field;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;

public class I18ncellWriteHandler implements CellWriteHandler {
    @Override
    public void beforeCellCreate(CellWriteHandlerContext context) {
        final List<String> headNameList = context.getHeadData().getHeadNameList();
        Field field = context.getHeadData().getField();
        Optional<String[]> codesOpt = Optional.ofNullable(field.getAnnotation(I18nField.class)).map(I18nField::value);
        if(codesOpt.isPresent()){
            String[] codes = codesOpt.get();
            AtomicReference<Integer> i = new AtomicReference<>(0);
            List<String> newHeadNames = headNameList.stream().map(headName ->{
                String temp;
                try {
                    temp = MessageUtils.message(codes[i.get()]);
                }catch (NoSuchMessageException e){
                    return headName;
                }
                i.getAndSet(i.get() + 1);
                if(StringUtils.isBlank(temp)){
                    return headName;
                }
                return temp;
            }).collect(Collectors.toList());
            context.getHeadData().setHeadNameList(newHeadNames);
        }
    }

}
