package top.imwork.window.silos.service;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import freemarker.template.Template;
import org.apache.commons.configuration.Configuration;
import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.PropertiesConfiguration;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import top.imwork.commons.core.constants.DateConstants;
import top.imwork.commons.core.exception.BusinessException;
import top.imwork.commons.core.pojo.ResponseMsg;
import top.imwork.commons.core.utils.DateUtils;
import top.imwork.window.silos.dao.generator.BaseMapper;
import top.imwork.window.silos.entity.generator.Column;
import top.imwork.window.silos.entity.generator.Table;
import top.imwork.window.silos.pojo.GeneratorDTO;
import top.imwork.window.silos.utils.FreeMarkerTemplateUtils;
import top.imwork.window.silos.utils.WordUtils;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.StringWriter;
import java.util.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * 〈功能简述〉<br>
 * 〈〉
 *
 * @author Administrator
 * @create 2020/5/10 0010
 * @since 1.0.0
 */
@Service
public class GeneratorService {
    @Autowired
    private GeneratorDTO generatorDTO;

    @Autowired
    private BaseMapper baseMapper;

    public ResponseMsg queryList(Map<String, Object> params) {
        Integer pages = Integer.parseInt(String.valueOf(params.get("page")));
        Integer rows = Integer.parseInt(String.valueOf(params.get("limit")));

        Page<?> page = PageHelper.startPage(pages, rows);
        List<Map<String, Object>> list = baseMapper.queryList(params);

        Map<String, Object> map = new HashMap<>();
        map.put("code", 0);
        map.put("count", (int) page.getTotal());
        map.put("data", list);
        return ResponseMsg.ok(map);
    }

    public Map<String, String> queryTable(String tableName) {
        return baseMapper.queryTable(tableName);
    }

    public List<Map<String, String>> queryColumns(String tableName) {
        return baseMapper.queryColumns(tableName);
    }

    public byte[] generatorCode(String[] tableNames) throws ConfigurationException {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ZipOutputStream zip = new ZipOutputStream(outputStream);

        for (String tableName : tableNames) {
            //查询表信息
            Map<String, String> table = queryTable(tableName);
            //查询列信息
            List<Map<String, String>> columns = queryColumns(tableName);
            //生成代码
            generatorCode(table, columns, zip);
        }
        IOUtils.closeQuietly(zip);
        return outputStream.toByteArray();
    }

    public static List<String> getTemplates() {
        List<String> templates = new ArrayList<String>();
        templates.add("Entity.ftl");
        templates.add("Dao.ftl");
        templates.add("Dao.xml.ftl");
        templates.add("Service.ftl");
        templates.add("ServiceImpl.ftl");
        templates.add("ServiceController.ftl");
        templates.add("Feign.ftl");
        templates.add("FallBack.ftl");
        templates.add("VO.ftl");
        templates.add("ResultBO.ftl");
        templates.add("BO.ftl");
        templates.add("DTO.ftl");
        templates.add("ListDTO.ftl");
        templates.add("API.ftl");
        templates.add("ListParamVO.ftl");
        templates.add("ParamVO.ftl");
        templates.add("ResultVO.ftl");
        templates.add("Convert.ftl");

        return templates;
    }

    /**
     * 获取配置信息
     */
    public static Configuration getConfig() throws ConfigurationException {
        return new PropertiesConfiguration("db.properties");
    }

    /**
     * 生成代码
     */
    public void generatorCode(Map<String, String> table,
                              List<Map<String, String>> columns, ZipOutputStream zip) throws ConfigurationException {
        //配置信息
        Configuration config = getConfig();
        boolean hasBigDecimal = false;
        //表信息
        Table tb = new Table();
        tb.setTableName(table.get("tableName"));
        tb.setComments(table.get("tableComment"));

        //表名转换成Java类名
        String className = tableToJava(tb.getTableName(), this.generatorDTO.getTablePrefix().split(","));
        tb.setClassName(className);
        tb.setClassname(StringUtils.uncapitalize(className));

        //列信息
        List<Column> columsList = new ArrayList<>();
        for (Map<String, String> column : columns) {
            Column columnEntity = new Column();
            columnEntity.setColumnName(column.get("columnName"));
            columnEntity.setDataType(column.get("dataType"));
            columnEntity.setComments(column.get("columnComment"));
            columnEntity.setExtra(column.get("extra"));

            //列名转换成Java属性名
            String attrName = columnToJava(columnEntity.getColumnName());
            columnEntity.setAttrName(attrName);
            columnEntity.setAttrname(StringUtils.uncapitalize(attrName));

            //列的数据类型，转换成Java类型
            String attrType = config.getString(columnEntity.getDataType(), "unknowType");
            columnEntity.setAttrType(attrType);
            if (!hasBigDecimal && attrType.equals("BigDecimal")) {
                hasBigDecimal = true;
            }
            //是否主键
            if ("PRI".equalsIgnoreCase(column.get("columnKey")) && tb.getPk() == null) {
                tb.setPk(columnEntity);
            }

            columsList.add(columnEntity);
        }
        tb.setColumns(columsList);

        //没主键，则第一个字段为主键
        if (tb.getPk() == null) {
            tb.setPk(tb.getColumns().get(0));
        }


        String mainPath = generatorDTO.getMainPath();
        mainPath = StringUtils.isBlank(mainPath) ? "top.imwork" : mainPath;
        //封装模板数据
        Map<String, Object> map = new HashMap<>();
        map.put("tableName", tb.getTableName());
        map.put("comments", tb.getComments());
        map.put("pk", tb.getPk());
        map.put("className", tb.getClassName());
        map.put("classname", tb.getClassname());
        map.put("pathName", tb.getClassname().toLowerCase());
        map.put("columns", tb.getColumns());
        map.put("hasBigDecimal", hasBigDecimal);
        map.put("mainPath", mainPath);
        map.put("commonsPath", generatorDTO.getCommonsPath());
        map.put("package", generatorDTO.getPackages());
        map.put("moduleName", generatorDTO.getModuleName());
        map.put("author", generatorDTO.getAuthor());
        map.put("email", generatorDTO.getEmail());
        map.put("datetime", DateUtils.format(new Date(), DateConstants.DATE_TIME_PATTERN));

        //获取模板列表
        List<String> templates = getTemplates();
        for (String template : templates) {
            try {
                Template tl = FreeMarkerTemplateUtils.getTemplate(template);

                //渲染模板
                StringWriter sw = new StringWriter();
                tl.process(map, sw);
                //添加到zip
                zip.putNextEntry(new ZipEntry(getFileName(template, tb.getClassName(), generatorDTO.getPackages(), generatorDTO.getModuleName())));
                IOUtils.write(sw.toString(), zip, "UTF-8");
                IOUtils.closeQuietly(sw);
                zip.closeEntry();
            } catch (Exception e) {
                throw new BusinessException("渲染模板失败，表名：" + tb.getTableName(), e);
            }
        }
    }

    /**
     * 列名转换成Java属性名
     */
    public static String columnToJava(String columnName) {
        return WordUtils.capitalizeFully(columnName, new char[]{'_'}).replace("_", "");
    }

    /**
     * 表名转换成Java类名
     */
    public static String tableToJava(String tableName, String[] tablePrefixArray) {
        if (null != tablePrefixArray && tablePrefixArray.length > 0) {
            for (String tablePrefix : tablePrefixArray) {
                tableName = tableName.replace(tablePrefix, "");
            }
        }
        return columnToJava(tableName);
    }

    /**
     * 获取文件名
     */
    public static String getFileName(String template, String className, String packageName, String moduleName) {
        String packagePath = "main" + File.separator + "java" + File.separator;
        String apiPath = "main" + File.separator + "java" + File.separator;
        if (StringUtils.isNotBlank(packageName)) {
            packagePath += packageName.replace(".", File.separator) + File.separator;
            apiPath += packageName.replace(".", File.separator) + File.separator;
        }

        if (template.equals("Entity.ftl")) {
            return packagePath + "entity" + File.separator + moduleName + File.separator + className + ".java";
        }

        if (template.equals("Dao.xml.ftl")) {
            return "main" + File.separator + "resources" + File.separator + "mapper" + File.separator + moduleName + File.separator + className + "Dao.xml";
        }

        if (template.equals("Dao.ftl")) {
            return packagePath + "dao" + File.separator + moduleName + File.separator + className + "Dao.java";
        }

        if (template.equals("Service.ftl")) {
            return packagePath + "service" + File.separator + moduleName + File.separator + "I" + className + "Service.java";
        }

        if (template.equals("ServiceImpl.ftl")) {
            return packagePath + "service" + File.separator + moduleName + File.separator + "impl" + File.separator + className + "ServiceImpl.java";
        }

        /*if (template.contains("Controller.ftl")) {
            return packagePath + "controller" + File.separator + className + "Controller.java";
        }*/

        if (template.equals("ServiceController.ftl")) {
            return packagePath + "controller" + File.separator + moduleName + File.separator + className + "ServiceController.java";
        }

        if (template.equals("API.ftl")) {
            return apiPath + "api" + File.separator + moduleName + File.separator + "I" + className + "ServiceApi.java";
        }

        if (template.equals("Feign.ftl")) {
            return apiPath + "feign" + File.separator + moduleName + File.separator + "I" + className + "ServiceFeign.java";
        }

        if (template.equals("FallBack.ftl")) {
            return apiPath + "feign" + File.separator + moduleName + File.separator + "fallback" + File.separator + className + "ServiceFeignFallbackFactory.java";
        }

        if (template.equals("VO.ftl")) {
            return packagePath + File.separator + "pojo" + File.separator + moduleName + File.separator + "vo" + File.separator + className + "VO.java";
        }

        if (template.equals("ResultBO.ftl")) {
            return packagePath + File.separator + "pojo" + File.separator + moduleName + File.separator + "bo" + File.separator + className + "ResultBO.java";
        }

        if (template.equals("BO.ftl")) {
            return packagePath + File.separator + "pojo" + File.separator + moduleName + File.separator + "bo" + File.separator + className + "BO.java";
        }

        if (template.equals("DTO.ftl")) {
            return packagePath + File.separator + "pojo" + File.separator + moduleName + File.separator + "dto" + File.separator + className + "DTO.java";
        }

        if (template.equals("ListDTO.ftl")) {
            return packagePath + File.separator + "pojo" + File.separator + moduleName + File.separator + "dto" + File.separator + className + "ListDTO.java";
        }

        if (template.equals("ListParamVO.ftl")) {
            return packagePath + File.separator + "pojo" + File.separator + moduleName + File.separator + "po" + File.separator + className + "ListParamVO.java";
        }

        if (template.equals("ParamVO.ftl")) {
            return packagePath + File.separator + "pojo" + File.separator + moduleName + File.separator + "po" + File.separator + className + "ParamVO.java";
        }

        if (template.equals("ResultVO.ftl")) {
            return packagePath + File.separator + "pojo" + File.separator + moduleName + File.separator + "vo" + File.separator + className + "ResultVO.java";
        }

        if (template.equals("Convert.ftl")) {
            return packagePath + File.separator + "convert" + File.separator + moduleName + File.separator + className + "Convert.java";
        }

        /*if (template.contains("menu.sql.ftl" )) {
            return className.toLowerCase() + "_menu.sql";
        }

        if (template.contains("index.vue.ftl" )) {
            return "main" + File.separator + "resources" + File.separator + "src" + File.separator + "views" + File.separator + "modules" +
                    File.separator + moduleName + File.separator + className.toLowerCase() + ".vue";
        }

        if (template.contains("add-or-update.vue.ftl" )) {
            return "main" + File.separator + "resources" + File.separator + "src" + File.separator + "views" + File.separator + "modules" +
                    File.separator + moduleName + File.separator + className.toLowerCase() + "-add-or-update.vue";
        }*/

        return null;
    }
}
