package cn.stylefeng.team.meta.modular.service;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Dict;
import cn.hutool.core.util.NumberUtil;
import cn.stylefeng.roses.kernel.dict.modular.entity.SysDict;
import cn.stylefeng.team.generator.api.CodeGeneratorApi;
import cn.stylefeng.team.generator.api.TemplateGetApi;
import cn.stylefeng.team.generator.api.enums.GeneratorTypeEnum;
import cn.stylefeng.team.generator.api.pojo.generator.result.CommonGenerateResult;
import cn.stylefeng.team.generator.api.pojo.template.GeneratorTemplateGroup;
import cn.stylefeng.team.generator.core.util.TemplateFormatUtil;
import cn.stylefeng.team.meta.api.constants.MetaConstants;
import cn.stylefeng.team.meta.api.pojo.MetaModelCreatSqlDTO;
import cn.stylefeng.team.meta.modular.entity.MetaUserDict;
import cn.stylefeng.team.meta.modular.factory.MetaDictFactory;
import cn.stylefeng.team.meta.modular.pojo.SysDictAggregation;
import cn.stylefeng.team.meta.modular.pojo.request.BusinessGenerateRequest;
import cn.stylefeng.team.meta.modular.pojo.request.MetaModelRequest;
import cn.stylefeng.team.meta.modular.pojo.response.GenerateCreateTableSqlResult;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class BusinessCodeGenerateService {

    @Resource
    private CreateTableGenerateService createTableGenerateService;

    @Resource
    private TemplateGetApi templateGetApi;

    @Resource
    private MetaUserDictService metaUserDictService;

    @Resource
    private CodeGeneratorApi codeGeneratorApi;

    public GenerateCreateTableSqlResult summaryCreateTableSql(MetaModelRequest metaModelRequest) {

        List<MetaModelCreatSqlDTO> businessMetaModelFieldInfoList = createTableGenerateService.getBusinessMetaModelFieldInfoList(metaModelRequest);

        GeneratorTemplateGroup templateGroup = templateGetApi.getTemplateGroup(GeneratorTypeEnum.CREAT_SQL);

        List<CommonGenerateResult> commonGenerateResults = createTableGenerateService.codeGenerate(templateGroup, businessMetaModelFieldInfoList);

        StringBuilder mysqlSql = new StringBuilder();
        StringBuilder oracleSql = new StringBuilder();
        StringBuilder postGreSql = new StringBuilder();
        for (CommonGenerateResult commonGenerateResult : commonGenerateResults) {
            String fileName = commonGenerateResult.getFileName();
            if (fileName.contains(MetaConstants.MYSQL_CREATE_TABLE_FILE_NAME)) {
                mysqlSql.append(commonGenerateResult.getFileContent()).append("\n");
            } else if (fileName.contains(MetaConstants.ORACLE_CREATE_TABLE_FILE_NAME)) {
                oracleSql.append(commonGenerateResult.getFileContent()).append("\n");
            } else if (fileName.contains(MetaConstants.POSTGRESQL_CREATE_TABLE_FILE_NAME)) {
                postGreSql.append(commonGenerateResult.getFileContent()).append("\n");
            }
        }

        GenerateCreateTableSqlResult result = new GenerateCreateTableSqlResult();
        result.setMysqlScript(mysqlSql.toString());
        result.setOracleScript(oracleSql.toString());
        result.setPostgreScript(postGreSql.toString());
        return result;
    }

    public CommonGenerateResult summaryCreateDictSql(BusinessGenerateRequest businessGenerateRequest) {

        List<SysDictAggregation> dictAggregationList = this.getBusinessDictAggregationList(businessGenerateRequest);

        GeneratorTemplateGroup templateGroup = templateGetApi.getTemplateGroup(GeneratorTypeEnum.INSERT_SYS_DICT_SQL);

        Dict dict = Dict.create();
        dict.set("dictAggregationList", dictAggregationList);
        return codeGeneratorApi.generateCodeGetResult(templateGroup.getGeneratorTemplates().get(0), "", dict);
    }

    public List<CommonGenerateResult> javaEnums(BusinessGenerateRequest businessGenerateRequest) {

        GeneratorTemplateGroup templateGroup = templateGetApi.getTemplateGroup(GeneratorTypeEnum.JAVA_ENUM);

        List<SysDictAggregation> dictAggregationList = this.getBusinessDictAggregationList(businessGenerateRequest);

        List<CommonGenerateResult> resultList = new ArrayList<>();
        for (SysDictAggregation aggregation : dictAggregationList) {

            Dict dict = this.fillEnumGenVariables(aggregation);

            String fileName = TemplateFormatUtil.camelCaseFirstUp(aggregation.getSysDictType().getDictTypeCode()) + "Enum";

            CommonGenerateResult result = codeGeneratorApi.generateCodeGetResult(templateGroup.getGeneratorTemplates().get(0), fileName, dict);

            resultList.add(result);
        }

        return resultList;
    }

    public List<SysDictAggregation> getBusinessDictAggregationList(BusinessGenerateRequest businessGenerateRequest) {

        List<MetaUserDict> currentProjectDictList = this.metaUserDictService.getCurrentProjectDictList(businessGenerateRequest);

        return MetaDictFactory.createSysDictInfo(currentProjectDictList);
    }

    private Dict fillEnumGenVariables(SysDictAggregation aggregation) {
        Dict dict = Dict.create();

        boolean codeStringFlag = false;
        for (SysDict sysDict : aggregation.getSysDictList()) {
            String dictCode = sysDict.getDictCode();
            if (!NumberUtil.isInteger(dictCode)) {
                codeStringFlag = true;
            }
        }
        dict.put("codeStringFlag", codeStringFlag);

        dict.put("author", "fengshuonan");

        dict.put("date", DateUtil.formatDateTime(new Date()));

        dict.put("dictType", aggregation.getSysDictType());
        dict.put("dictList", aggregation.getSysDictList());

        return dict;
    }

}
