package com.lideeyunji.core.framework.config.excel.check.strategy;

import cn.hutool.core.util.NumberUtil;
import com.lideeyunji.core.framework.config.excel.check.IExcelCheckStrategy;
import com.lideeyunji.core.framework.config.excel.check.param.ExcelCheckParams;
import com.lideeyunji.core.framework.entity.FormFieldEntity;
import com.lideeyunji.core.framework.params.vo.DbFormConfigVo;
import com.lideeyunji.core.framework.utils.Func;
import com.lideeyunji.tool.framework.yunji.enums.LideeYunJiFieldTypeEnum;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;

/**
 * 数据类型-校验
 */
@Component
@Slf4j
public class ExcelDataTypeStrategy implements IExcelCheckStrategy {

    //执行
    @Override
    public void check(ExcelCheckParams checkParams) throws Exception {
        Map<String, Object> dataMap = checkParams.getDataMap();
        DbFormConfigVo vo = checkParams.getDbFormConfigVo();

        List<FormFieldEntity> fieldList = vo.getFieldList();

        for(FormFieldEntity fieldEntity : fieldList){
            String fieldName = fieldEntity.getFieldName();
            String fieldCode = fieldEntity.getFieldCode();
            String fieldType = fieldEntity.getFieldType();

            Object obj = dataMap.get(fieldCode);
            if(Func.isEmpty( obj)){
                continue;
            }
            LideeYunJiFieldTypeEnum fieldTypeEnum = LideeYunJiFieldTypeEnum.getByFieldType(fieldType);
            if(Func.isEmpty(fieldTypeEnum)){
                throw new Exception("字段类型错误");
            }
            //简单校验，如果是数字类型，就不允许是字符串
            if(Func.equals(fieldType,"Integer") || Func.equals(fieldType,"BigInt")){
                boolean isNumber = NumberUtil.isNumber(obj.toString());
                if(!isNumber){
                    throw new Exception("字段【"+fieldName+"】不是数字");
                }
            }
            //日期
            if(Func.equals(fieldType,"Date") || Func.equals(fieldType,"DateTime") || Func.equals(fieldType,"Time")){
                if(!(obj instanceof Data)){
                    throw new Exception("字段【"+fieldName+"】不是日期");
                }
            }
        }


    }


}
