package cc.mrbird.febs.server.generator.controller;

import com.baomidou.dynamic.datasource.spring.boot.autoconfigure.DataSourceProperty;
import com.baomidou.dynamic.datasource.spring.boot.autoconfigure.DynamicDataSourceProperties;
import com.yida.data.common.core.entity.FebsResponse;
import com.yida.data.common.core.entity.QueryRequest;
import com.yida.data.common.core.entity.constant.GeneratorConstant;
import com.yida.data.common.core.entity.system.Column;
import com.yida.data.common.core.entity.system.GeneratorConfig;
import com.yida.data.common.core.entity.system.Table;
import com.yida.data.common.core.exception.FebsException;
import com.yida.data.common.core.utils.FebsUtil;
import com.yida.data.common.core.utils.FileUtil;

import org.apache.commons.lang3.RegExUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.FileSystemUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;

import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotBlank;

import cc.mrbird.febs.server.generator.helper.GeneratorHelper;
import cc.mrbird.febs.server.generator.service.GeneratorConfigService;
import cc.mrbird.febs.server.generator.service.GeneratorService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

/**
 * @author MrBird
 */
@Slf4j
@Validated
@RestController
@RequiredArgsConstructor
public class GeneratorController {

    private static final String SUFFIX = "_code.zip";

    private final GeneratorService generatorService;
    private final GeneratorConfigService generatorConfigService;
    private final GeneratorHelper generatorHelper;
    private final DynamicDataSourceProperties properties;

    @GetMapping("datasources")
    @PreAuthorize("hasAuthority('gen:generate')")
    public FebsResponse datasources() {
        Map<String, DataSourceProperty> datasources = properties.getDatasource();
        List<String> datasourcesName = new ArrayList<>();
        datasources.forEach((k, v) -> {
            String datasourceName = StringUtils.substringBefore(StringUtils.substringAfterLast(v.getUrl(), "/"), "?");
            datasourcesName.add(datasourceName);
        });
        return new FebsResponse().data(datasourcesName);
    }

    @GetMapping("tables")
    @PreAuthorize("hasAuthority('gen:generate')")
    public FebsResponse tablesInfo(String tableName, String datasource, QueryRequest request) {
        Map<String, Object> dataTable = FebsUtil.getDataTable(generatorService.getTables(tableName, request, GeneratorConstant.DATABASE_TYPE, datasource));
        return new FebsResponse().data(dataTable);
    }

    @PostMapping
    //@PreAuthorize("hasAuthority('gen:generate:gen')")
    public void generate(String[] name,
                         @NotBlank(message = "{required}") String datasource,
                         String remark, HttpServletResponse response) throws Exception {
        GeneratorConfig generatorConfig = generatorConfigService.findGeneratorConfig();
        if (generatorConfig == null) {
            throw new FebsException("代码生成配置为空");
        }

        for (String name1 : name) {
            String className = name1;
            if (GeneratorConfig.TRIM_YES.equals(generatorConfig.getIsTrim())) {
                className = RegExUtils.replaceFirst(name1, generatorConfig.getTrimValue(), StringUtils.EMPTY);
            }

            generatorConfig.setTableName(name1);
            generatorConfig.setClassName(FebsUtil.underscoreToCamel(className));
            Table table = generatorService.getTable(GeneratorConstant.DATABASE_TYPE, datasource, name1);
            generatorConfig.setTableComment(Objects.nonNull(table) ? table.getRemark() : remark);
            // 生成代码到临时目录
            List<Column> columns = generatorService.getColumns(GeneratorConstant.DATABASE_TYPE, datasource, name1);
            generatorHelper.generateEntityFile(columns, generatorConfig);
            generatorHelper.generateMapperFile(columns, generatorConfig);
            generatorHelper.generateMapperXmlFile(columns, generatorConfig);
            generatorHelper.generateServiceFile(columns, generatorConfig);
            generatorHelper.generateServiceImplFile(columns, generatorConfig);
            generatorHelper.generateControllerFile(columns, generatorConfig);
        }
        // 打包
        String zipFile = System.currentTimeMillis() + SUFFIX;
        FileUtil.compress(GeneratorConstant.TEMP_PATH + "src", zipFile);
        // 下载
        FileUtil.download(zipFile, "generate" + SUFFIX, true, response);
        // 删除临时目录
        FileSystemUtils.deleteRecursively(new File(GeneratorConstant.TEMP_PATH));
    }
}
