package com.yifu.cloud.plus.v1.yifu.common.security.util.dict;

import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.converters.ReadConverterContext;
import com.alibaba.excel.converters.WriteConverterContext;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.yifu.cloud.plus.v1.yifu.common.core.constant.CommonConstants;
import com.yifu.cloud.plus.v1.yifu.common.core.util.Common;
import com.yifu.cloud.plus.v1.yifu.common.core.util.RedisUtil;

import java.lang.reflect.Field;
import java.util.Map;

/**
 * @Author fxj
 * @Date 2022/6/23
 * @Description
 * @Version 1.0
 */
public class ConverterDiy implements Converter<String> {
	@Override
	public Class<?> supportJavaTypeKey() {
		return String.class;
	}

	@Override
	public CellDataTypeEnum supportExcelTypeKey() {
		return CellDataTypeEnum.STRING;
	}

	/**
	 * 这里是读的时候会调用 不用管
	 *
	 * @return
	 */
	@Override
	public String convertToJavaData(ReadConverterContext<?> context) {
		Field field = context.getContentProperty().getField();
		String converRes = context.getReadCellData().getStringValue();
		if (Common.isNotNull(field)){
			DictValidator attr = field.getAnnotation(DictValidator.class);
			if (Common.isNotNull(attr) && Common.isNotNull(attr.dictType())){
				Map<String,String> dicObj = (Map<String, String>) RedisUtil.redis.opsForValue().get(attr.dictType());
				for (Map.Entry<String,String> entry:dicObj.entrySet()){
					if (Common.isNotNull(entry.getValue()) && entry.getValue().equals(converRes)){
						converRes = entry.getKey();
						break;
					}
				}
			}
		}
		return converRes;
	}

	/**
	 * 这里是写的时候会调用 不用管
	 *
	 * @return
	 */
	@Override
	public WriteCellData<?> convertToExcelData(WriteConverterContext<String> context) {
		return new WriteCellData<>("" + context.getValue());
	}
}
