package com.yunzhupaas.generater.service.impl;

import com.google.common.base.CaseFormat;
import com.yunzhupaas.base.UserInfo;
import com.yunzhupaas.base.entity.VisualdevEntity;
import com.yunzhupaas.base.mapper.VisualdevMapper;
import com.yunzhupaas.base.model.DownloadCodeForm;
import com.yunzhupaas.base.model.VisualWebTypeEnum;
import com.yunzhupaas.base.service.DbLinkService;
import com.yunzhupaas.base.service.SuperServiceImpl;
import com.yunzhupaas.base.service.SysconfigService;
import com.yunzhupaas.base.service.VisualAliasService;
import com.yunzhupaas.base.util.VisualUtils;
import com.yunzhupaas.base.util.common.AliasModel;
import com.yunzhupaas.base.util.common.GenerateCommon;
import com.yunzhupaas.base.util.common.GenerateParamModel;
import com.yunzhupaas.base.util.custom.VelocityEnum;
import com.yunzhupaas.config.ConfigValueUtil;
import com.yunzhupaas.constant.GenerateConstant;
import com.yunzhupaas.database.model.entity.DbLinkEntity;
import com.yunzhupaas.database.util.DataSourceUtil;
import com.yunzhupaas.generater.factory.CodeGenerateFactoryV3;
import com.yunzhupaas.generater.model.FormDesign.TemplateMethodEnum;
import com.yunzhupaas.generater.service.VisualdevGenService;
import com.yunzhupaas.model.FileListVO;
import com.yunzhupaas.model.OnlineDevData;
import com.yunzhupaas.model.visualJson.TableModel;
import com.yunzhupaas.util.*;
import org.apache.velocity.app.Velocity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 可视化开发功能表
 *
 * @author 云筑产品开发平台组
 * @version V3.1.0
 * @copyright 深圳市乐程软件有限公司（http://www.szlecheng.cn）
 * @date 2024-04-02
 */
@Service
public class VisualdevGenServiceImpl extends SuperServiceImpl<VisualdevMapper, VisualdevEntity> implements VisualdevGenService {

    
    @Autowired
    private DataSourceUtil dataSourceUtil;
    @Autowired
    private DbLinkService dataSourceApi;

    @Autowired
    private ConfigValueUtil configValueUtil;

    @Autowired
    private CodeGenerateFactoryV3 GenerateFactoryV3;

    @Autowired
    private SysconfigService sysconfigService;

    @Autowired
    private VisualAliasService aliasService;

    /**
     * vue3代码生成
     *
     * @param entity           可视化开发功能
     * @param downloadCodeForm 下载相关信息
     * @return
     * @throws Exception
     */
    @Override
    public String codeGengerateV3(VisualdevEntity entity, DownloadCodeForm downloadCodeForm) throws Exception {
        UserInfo userInfo = UserProvider.getUser();
        DbLinkEntity linkEntity = null;
        if (entity != null) {
            //初始化模板
            Velocity.reset();
            VelocityEnum.init.initVelocity(GenerateCommon.getLocalBasePath() + configValueUtil.getTemplateCodePathVue3());

            //视图代码生成独立逻辑
            if(VisualWebTypeEnum.DATA_VIEW.getType().equals(entity.getWebType())){
                String fileName = entity.getFullName() + "_" + DateUtil.nowDateTime();
                String mainClass = "St" + entity.getEnCode();
                downloadCodeForm.setMainClassName(mainClass);
                System.out.print(GenerateCommon.getLocalBasePath());
                System.out.print(configValueUtil.getTemplateCodePathVue3());
                //执行代码生成器
                GenerateParamModel generateParamModel = new GenerateParamModel().builder()
                        .path(GenerateCommon.getLocalBasePath() + configValueUtil.getTemplateCodePathVue3())
                        .fileName(fileName)
                        .downloadCodeForm(downloadCodeForm)
                        .entity(entity)
                        .userInfo(userInfo)
                        .configValueUtil(configValueUtil)
                        .className(mainClass)
                        .templatesPath(TemplateMethodEnum.T6.getMethod())
                        .template7Model(GenerateCommon.getTemplate7Model(sysconfigService.getList(GenerateConstant.SYSCONFIG)))
                        .build();
                GenerateFactoryV3.runGenerator(TemplateMethodEnum.T6.getMethod(), generateParamModel);
                return fileName;
            }
            // 是否存在关联数据库
            if (StringUtil.isNotEmpty(entity.getDbLinkId())) {
                linkEntity = dataSourceApi.getInfo(entity.getDbLinkId());
            }
            // 是否存在关联表
            if (StringUtil.isNotEmpty(entity.getVisualTables())) {
                String fileName = entity.getFullName() + "_" + DateUtil.nowDateTime();

                List<TableModel> list = JsonUtil.getJsonToList(entity.getVisualTables(), TableModel.class);
                Map<String, AliasModel> tableAliasMap = aliasService.getAllFiledsAlias(entity.getId());

                //获取主表
                String mainTable = list.stream().filter(t -> "1".equals(t.getTypeId())).findFirst().orElse(null).getTable();
                Map<String, String> fieldsMap = tableAliasMap.get(mainTable).getFieldsMap();
                //获取主键
                String pKeyName = VisualUtils.getpKey(linkEntity, mainTable);

                //自定义包名
                String modulePackageName = StringUtil.isNotEmpty(downloadCodeForm.getModulePackageName()) ? downloadCodeForm.getModulePackageName() :
                        GenerateConstant.PACKAGE_NAME;
                downloadCodeForm.setModulePackageName(modulePackageName);
                downloadCodeForm.setMainClassName(tableAliasMap.get(mainTable).getAliasName());
                //获取其他子表的主键
                Map<String, Object> childpKeyMap = new HashMap<>(16);
                for (TableModel tableModel : list) {
                    String childKey = VisualUtils.getpKey(linkEntity, tableModel.getTable());
                    if (childKey.length() > 2) {
                        if ("f_".equals(childKey.substring(0, 2).toLowerCase())) {
                            childKey = childKey.substring(2);
                        }
                    }
                    childpKeyMap.put(tableModel.getTable(), childKey);
                }

                String templatesPath = null;
                //功能表单
                if (OnlineDevData.FORM_TYPE_DEV.equals(entity.getType())) {
                    switch (entity.getWebType()) {
                        case 1:
                            templatesPath = downloadCodeForm.getEnableFlow() == 1 ? TemplateMethodEnum.T5.getMethod() : TemplateMethodEnum.T4.getMethod() ;
                            break;
                        case 2:
                            templatesPath = downloadCodeForm.getEnableFlow() == 1 ? TemplateMethodEnum.T3.getMethod() : TemplateMethodEnum.T2.getMethod() ;
                            break;
                        default:
                            break;
                    }
                }
                //非本地模板需要下载-获取模板如下
                if (!FileUploadUtils.getDefaultPlatform().startsWith(GenerateConstant.LOCAL)) {
                    List<FileListVO> fileList = new ArrayList<>();
                    fileList.addAll(FileUploadUtils.getDefaultFileList(configValueUtil.getTemplateCodePathVue3()));
                    String basePath = FileUploadUtils.getBasePath();
                    for (FileListVO fileListVO : fileList) {
                        String eachFileName = fileListVO.getFileName();
                        int index = eachFileName.lastIndexOf("/");
                        //服务器路径
                        String floderName = eachFileName.substring(0, index + 1);
                        if(StringUtil.isNotEmpty(basePath) && floderName.contains(basePath)){
                            floderName = floderName.substring(basePath.length());
                        }
                        //本地路径
                        String filePath = FileUploadUtils.getLocalBasePath() + floderName;
                        //文件名
                        String objectName = eachFileName.substring(index + 1);
                        FileUploadUtils.downLocal(floderName, filePath, objectName);
                    }
                }
                System.out.print(GenerateCommon.getLocalBasePath());
                System.out.print(configValueUtil.getTemplateCodePathVue3());
                //执行代码生成器
                GenerateParamModel generateParamModel = new GenerateParamModel().builder()
                        .dataSourceUtil(dataSourceUtil)
                        .path(GenerateCommon.getLocalBasePath() + configValueUtil.getTemplateCodePathVue3())
                        .fileName(fileName)
                        .templatesPath(templatesPath)
                        .downloadCodeForm(downloadCodeForm)
                        .entity(entity)
                        .userInfo(userInfo)
                        .configValueUtil(configValueUtil)
                        .linkEntity(linkEntity)
                        .pKeyNameOriginal(pKeyName)
                        .pKeyName(fieldsMap.get(pKeyName))
                        .template7Model(GenerateCommon.getTemplate7Model(sysconfigService.getList(GenerateConstant.SYSCONFIG)))
                        .tableAliseMap(tableAliasMap)
                        .build();
                GenerateFactoryV3.runGenerator(templatesPath, generateParamModel);
                return fileName;
            }
        }
        return null;
    }
}

