package com.cym.utils;

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

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import com.cym.bean.InitValue;
import com.cym.bean.Update;

import cn.hutool.core.util.ClassUtil;
import cn.hutool.core.util.ReflectUtil;
import jakarta.persistence.Entity;
import jakarta.transaction.Transactional;

@Service
public class InitTool {
	@Autowired
	PackageTools packageTools;

	@Autowired
	JpaHelper jpaHelper;

	@Autowired
	JdbcTemplate jdbcTemplate;

	@Value("${spring.datasource.url:}")
	String url;

	@Transactional
	public void init() {
		Set<Class<?>> set = ClassUtil.scanPackage(packageTools.getMainPackage());
		// 注入默认值
		for (Class<?> clazz : set) {
			Entity entity = clazz.getAnnotation(Entity.class);
			if (entity != null) {
				Field[] fields = ReflectUtil.getFields(clazz);
				for (Field field : fields) {
					if (field.isAnnotationPresent(InitValue.class)) {
						InitValue defaultValue = field.getAnnotation(InitValue.class);
						if (defaultValue.value() != null) {
							// 更新默认值
							Long count = jpaHelper.findCountByQuery(new ConditionAndWrapper().isNull(field.getName()), clazz);
							if (count > 0) {
								String value = defaultValue.value();
								Object obj = null;
								// 获取字段类型
								Class<?> type = field.getType();
								if (type.equals(String.class)) {
									obj = value;
								}
								if (type.equals(Short.class)) {
									obj = Short.parseShort(value);
								}
								if (type.equals(Integer.class)) {
									obj = Integer.parseInt(value);
								}
								if (type.equals(Long.class)) {
									obj = Long.parseLong(value);
								}
								if (type.equals(Float.class)) {
									obj = Float.parseFloat(value);
								}
								if (type.equals(Double.class)) {
									obj = Double.parseDouble(value);
								}
								if (type.equals(Boolean.class)) {
									obj = Boolean.parseBoolean(value);
								}

								jpaHelper.updateByQuery(new ConditionAndWrapper().isNull(field.getName()), new Update().set(field.getName(), obj), clazz);
							}
						}
					}
				}
			}
		}
	}

}
