package com.artfess.easyExcel.converter;

import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.converters.ReadConverterContext;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.GlobalConfiguration;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.metadata.property.ExcelContentProperty;
import com.alibaba.fastjson.JSON;
import com.artfess.base.cache.CacheManager;
import com.artfess.base.cache.ICache;
import com.artfess.base.cache.setting.CacheSetting;
import com.artfess.base.constants.CacheKeyConst;
import com.artfess.base.util.AppUtil;
import com.artfess.base.util.StringUtil;
import com.artfess.easyExcel.annotaion.ExcelDictItem;
import com.artfess.easyExcel.annotaion.ExcelDictItemLabel;
import com.artfess.easyExcel.vo.DictionaryDetailVo;

import java.lang.reflect.Field;
import java.util.List;
import java.util.concurrent.atomic.AtomicReference;

/**
 * Excel Converter字典转换器
 */
public class ExcelDictConverter implements Converter<String> {

	private static final CacheSetting cacheSetting = CacheSetting.buildDefault("字典缓存");

	public ExcelDictConverter() {
	}

	@Override
	public Class supportJavaTypeKey() {
		return null;
	}

	@Override
	public CellDataTypeEnum supportExcelTypeKey() {
		return null;
	}

	/**
	 * 将excel单元格数据转换成对象属性值（适配多个逗号分隔的字典值）
	 *
	 * @return 转换后的对象属性值
	 * @throws Exception 异常
	 */
	@Override
	public String convertToJavaData(ReadConverterContext<?> context) throws Exception {
		// 获取字典类型
		Field field = context.getContentProperty().getField();
		ExcelDictItemLabel excel = field.getAnnotation(ExcelDictItemLabel.class);
		String dictType = excel.type();
		String dictLabel = context.getReadCellData().getStringValue();

		// 为空返回
		if (StringUtil.isEmpty(dictLabel)) {
			return dictLabel;
		}
		//获取字典服务类
		CacheManager cacheManager = AppUtil.getBean(CacheManager.class);
		ICache cache = cacheManager.getCache("", cacheSetting);
		String key = CacheKeyConst.SYS_DICTIONARY_KEY + ":" + dictType.toUpperCase() + ":";
		Object o = cache.get(key);
		if(null == o) {
			return dictLabel;
		}

		//将excel中name转换成 字典中的value
		List<DictionaryDetailVo> dictionaryDetails = JSON.parseArray(o.toString(), DictionaryDetailVo.class);
		AtomicReference<String> value = new AtomicReference<>();
		dictionaryDetails.forEach(dictionaryDetail -> {
			String name = dictionaryDetail.getName();
			if(dictLabel.equals(name)) {
				value.set(dictionaryDetail.getValue());
				return;
			}
		});
		return value.get();
	}

	/**
	 * 将对象属性值转换成excel单元格数据（适配多个逗号分隔的字典值）
	 *
	 * @return 转换后的对象属性值
	 * @throws Exception 异常
	 */
	@Override
	public WriteCellData<?> convertToExcelData(String dictLabel, ExcelContentProperty excelContentProperty, GlobalConfiguration globalConfiguration) throws Exception{
		Field field = excelContentProperty.getField();
		ExcelDictItem excel = field.getAnnotation(ExcelDictItem.class);
		String dictType = excel.type();

		// 为空返回
		if (StringUtil.isEmpty(dictLabel)) {
			return null;
		}
		//获取字典服务类
		CacheManager cacheManager = AppUtil.getBean(CacheManager.class);
		ICache cache = cacheManager.getCache("", cacheSetting);

		String key = CacheKeyConst.SYS_DICTIONARY_KEY + ":" + dictType.toUpperCase() + ":";

		Object o = cache.get(key);
		if(null == o) {
			return null;
		}
		List<DictionaryDetailVo> dictionaryDetails = JSON.parseArray(o.toString(), DictionaryDetailVo.class);
		AtomicReference<String> name = new AtomicReference<>();
		dictionaryDetails.forEach(dictionaryDetail -> {
			String value = dictionaryDetail.getValue();
			if(dictLabel.equals(value)) {
				name.set(dictionaryDetail.getName());
				return;
			}
		});
		return new WriteCellData<>(name.get());
	}

}
