package com.hw.tdengine.api.domain;

import com.hw.common.core.enums.DataTypeEnums;
import org.apache.commons.lang3.StringUtils;
import org.springframework.validation.annotation.Validated;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * @Description: Tdengine 创建表的字段实体类
 * @ClassName: TdFieldsVo
 * @Author : xins
 * @Date :2023-08-28  14:34
 * @Version :1.0
 */
public class TdFieldVo {
    private static final long serialVersionUID = 1L;

    private String fieldName;

    private String dataType;

    private Integer size;


    public TdFieldVo(String fieldName, Integer dataTypeCode, Integer size) {
        this.fieldName = fieldName;
        this.dataType = DataTypeEnums.dataCodeTypeMap.get(dataTypeCode);
        this.size = size;
    }

    /**
     * @description 将TdFields转换为创建表的实体类TdFieldsVo，主要是datatype转换
     * @author xins
     * @date 2023-08-28 14:40
      * @param field
     * @return TdFieldsVo
     */
    public static TdFieldVo convertField(@Validated TdField field) throws SQLException {
        String fieldName = field.getFieldName();
        Integer datatypeCode = field.getDataTypeCode();
        Integer size = field.getSize();
        if(StringUtils.isBlank(fieldName) || datatypeCode == null){
            throw new SQLException("fieldname and datatype cannot be null");
        }
        TdFieldVo tdFieldsVo = new TdFieldVo(fieldName, datatypeCode, size);
        return tdFieldsVo;
    }


    /**
     * @description 批量转换创建表的字段
     * @author xins
     * @date 2023-08-28 14:58
      * @param fieldList
     * @return List<TdFieldsVo>
     */
    public static List<TdFieldVo> batchConvertFields(List<TdField> fieldList) throws SQLException{
        List<TdFieldVo> tdFieldsVoList = new ArrayList<>();
        for(TdField tdField:fieldList){
            tdFieldsVoList.add(convertField(tdField));
        }
        return tdFieldsVoList;
    }

}
