package com.testor.common.convert;

import cn.hutool.core.annotation.AnnotationUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.CellData;
import com.alibaba.excel.metadata.GlobalConfiguration;
import com.alibaba.excel.metadata.property.ExcelContentProperty;
import com.testor.common.annotation.ExcelDictFormat;
import com.testor.common.core.utils.SpringUtils;
import com.testor.common.core.utils.poi.ExcelUtil;
import com.testor.module.sys.model.domian.NewSysOrg;
import com.testor.module.sys.service.NewSysDictDataService;
import com.testor.module.sys.service.NewSysOrgService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.lang.reflect.Field;

/**
 * 部门id/名称化转换处理
 *
 * @author Lion Li
 */
@Slf4j
public class ExcelDeptConvert implements Converter<Object> {

    @Override
    public Class<Object> supportJavaTypeKey() {
        return Object.class;
    }

    @Override
    public CellDataTypeEnum supportExcelTypeKey() {
        return null;
    }

    @Override
    public Object convertToJavaData(CellData cellData, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) {
        String name = cellData.getStringValue();
        String value = SpringUtils.getBean(NewSysOrgService.class).getDeptIdByName(name);
        return Convert.convert(contentProperty.getField().getType(), value);
    }

    @Override
    public CellData<String> convertToExcelData(Object object, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) {
        if (ObjectUtil.isNull(object)) {
            return new CellData<>("");
        }
        String id = Convert.toStr(object);
        String name = "";
        NewSysOrg byId = SpringUtils.getBean(NewSysOrgService.class).getById(id);
        if (byId != null){
            name = byId.getOrgName();
        }
        return new CellData<>(name);
    }

    private ExcelDictFormat getAnnotation(Field field) {
        return AnnotationUtil.getAnnotation(field, ExcelDictFormat.class);
    }
}
