package cn.gov.customs.wxjy.generator.service.impl;

import cn.gov.customs.wxjy.common.constant.Constants;
import cn.gov.customs.wxjy.common.constant.GenConstants;
import cn.gov.customs.wxjy.common.core.text.CharsetKit;
import cn.gov.customs.wxjy.common.exception.ServiceException;
import cn.gov.customs.wxjy.common.utils.StringUtils;
import cn.gov.customs.wxjy.generator.util.SysGenUtils;
import cn.gov.customs.wxjy.generator.util.SysVelocityUtils;
import cn.gov.customs.wxjy.generator.util.VelocityInitializer;
import cn.gov.customs.wxjy.generator.dao.GenTableColumnMapper;
import cn.gov.customs.wxjy.generator.dao.GenTableMapper;
import cn.gov.customs.wxjy.generator.pojo.GenTable;
import cn.gov.customs.wxjy.generator.pojo.GenTableColumn;
import cn.gov.customs.wxjy.generator.pojo.GenTableQuery;
import cn.gov.customs.wxjy.generator.service.IGenTableService;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.github.pagehelper.PageInfo;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.validation.Validator;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.StringWriter;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * 代码生成业务Service业务层处理
 *
 * @author xiong
 * @date 2025-12-25
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class GenTableServiceImpl implements IGenTableService {

    private final GenTableMapper genTableMapper;

    private final GenTableColumnMapper genTableColumnMapper;

    private final Validator validator;

    /**
     * 查询代码生成业务
     *
     * @param tableId 代码生成业务主键
     * @return 代码生成业务
     */
    @Override
    public GenTable selectByTableId(String tableId) {
        return genTableMapper.selectByTableId(tableId);
    }

    /**
     * 分页查询代码生成业务列表
     *
     * @param query
     * @return 代码生成业务
     */
    @Override
    public PageInfo<GenTable> selectPageList(GenTableQuery query) {
        return PageInfo.of(genTableMapper.selectList(query));
    }

    /**
     * 查询代码生成业务列表
     *
     * @param query
     * @return 代码生成业务
     */
    @Override
    public List<GenTable> selectList(GenTableQuery query) {
        return genTableMapper.selectList(query);
    }

    /**
     * 新增代码生成业务
     *
     * @param genTable 代码生成业务
     * @return 结果
     */
    @Override
    public int insert(GenTable genTable) {
            return genTableMapper.insert(genTable);
    }

    /**
     * 修改代码生成业务
     *
     * @param genTable 代码生成业务
     * @return 结果
     */
    @Override
    public int update(GenTable genTable) {
        String options = JSON.toJSONString(genTable.getParams());
        genTable.setOptions(options);
        int row = genTableMapper.update(genTable);
        if (row > 0)
        {
            for (GenTableColumn cenTableColumn : genTable.getColumns())
            {
                genTableColumnMapper.update(cenTableColumn);
            }
        }
        return row;
    }

    /**
     * 批量删除代码生成业务
     *
     * @param ids 需要删除的代码生成业务主键
     * @return 结果
     */
    @Override
    @Transactional
    public int deleteByTableIds(String[] ids) {
        genTableColumnMapper.deleteGenTableColumnByIds(ids);
        return genTableMapper.deleteByTableIds(ids);
    }

    /**
     * 删除代码生成业务信息
     *
     * @param tableId 代码生成业务主键
     * @return 结果
     */
    @Override
    public int deleteByTableId(String tableId) {
        return genTableMapper.deleteByTableId(tableId);
    }

    /**
     * 逻辑删除代码生成业务信息
     *
     * @param tableId 代码生成业务主键
     * @return 结果
     */
    @Override
    public int logicDelete(String tableId) {

        return genTableMapper.logicDelete(tableId);
    }

    /**
     * 导入代码生成业务数据
     *
     * @param genTableList 代码生成业务数据列表
     * @param operUser 操作用户
     * @return 结果
     */
    @Override
    public void importGenTable(List<GenTable> genTableList, String operUser) {
        {
            try
            {
                for (GenTable table : genTableList)
                {
                    String tableName = table.getTableName();
                    SysGenUtils.initTable(table, operUser);
                    int row = genTableMapper.insert(table);
                    if (row > 0)
                    {
                        // 保存列信息
                        List<GenTableColumn> genTableColumns = genTableColumnMapper.selectDbTableColumnsByName(tableName);
                        for (GenTableColumn column : genTableColumns)
                        {
                            SysGenUtils.initColumnField(column, table);
                            genTableColumnMapper.insert(column);
                        }
                    }
                }
            }
            catch (Exception e)
            {
                throw new ServiceException("导入失败：" + e.getMessage());
            }
        }
    }

    @Override
    public List<GenTable> selectGenTableAll() {
        return genTableMapper.selectGenTableAll();
    }

    @Override
    public PageInfo<GenTable> selectDbTableList(GenTableQuery query) {
        return PageInfo.of(genTableMapper.selectDbTableList(query));
    }

    @Override
    public List<GenTable> selectDbTableListByNames(String[] tableNames) {
        return genTableMapper.selectDbTableListByNames(tableNames);
    }

    @Override
    public void validateEdit(GenTable genTable) {
        if (GenConstants.TPL_TREE.equals(genTable.getTplCategory()))
        {
            String options = JSON.toJSONString(genTable.getParams());
            JSONObject paramsObj = JSON.parseObject(options);
            if (StringUtils.isEmpty(paramsObj.getString(GenConstants.TREE_CODE)))
            {
                throw new ServiceException("树编码字段不能为空");
            }
            else if (StringUtils.isEmpty(paramsObj.getString(GenConstants.TREE_PARENT_CODE)))
            {
                throw new ServiceException("树父编码字段不能为空");
            }
            else if (StringUtils.isEmpty(paramsObj.getString(GenConstants.TREE_NAME)))
            {
                throw new ServiceException("树名称字段不能为空");
            }
            else if (GenConstants.TPL_SUB.equals(genTable.getTplCategory()))
            {
                if (StringUtils.isEmpty(genTable.getSubTableName()))
                {
                    throw new ServiceException("关联子表的表名不能为空");
                }
                else if (StringUtils.isEmpty(genTable.getSubTableFkName()))
                {
                    throw new ServiceException("子表关联的外键名不能为空");
                }
            }
        }
    }

    @Override
    public Map<String, String> previewCode(String tableId) {
        Map<String, String> dataMap = new LinkedHashMap<>();
        // 查询表信息
        GenTable table = genTableMapper.selectByTableId(tableId);
        // 设置主子表信息
        setSubTable(table);
        // 设置主键列信息
        setPkColumn(table);
        VelocityInitializer.initVelocity();

        VelocityContext context = SysVelocityUtils.prepareContext(table);

        // 获取模板列表
        List<String> templates = SysVelocityUtils.getTemplateList(table.getTplCategory(), table.getTplWebType());
        for (String template : templates)
        {
            // 渲染模板
            StringWriter sw = new StringWriter();
            Template tpl = Velocity.getTemplate(template, Constants.UTF8);
            tpl.merge(context, sw);
            dataMap.put(template, sw.toString());
        }
        return dataMap;
    }

    @Override
    public byte[] downloadCode(String tableName) {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ZipOutputStream zip = new ZipOutputStream(outputStream);
        generatorCode(tableName, zip);
        IOUtils.closeQuietly(zip);
        return outputStream.toByteArray();
    }

    @Override
    public byte[] downloadCode(String[] tableNames) {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ZipOutputStream zip = new ZipOutputStream(outputStream);
        for (String tableName : tableNames)
        {
            generatorCode(tableName, zip);
        }
        IOUtils.closeQuietly(zip);
        return outputStream.toByteArray();
    }

    /**
     * 生成代码（自定义路径）
     *
     * @param tableName 表名称
     */
    @Override
    public void generatorCode(String tableName) {
        // 查询表信息
        GenTable table = genTableMapper.selectGenTableByName(tableName);
        // 设置主子表信息
        setSubTable(table);
        // 设置主键列信息
        setPkColumn(table);

        VelocityInitializer.initVelocity();

        VelocityContext context = SysVelocityUtils.prepareContext(table);

        // 获取模板列表
        List<String> templates = SysVelocityUtils.getTemplateList(table.getTplCategory(), table.getTplWebType());
        for (String template : templates)
        {
            if (!StringUtils.containsAny(template, "sql.vm", "api.js.vm", "index.vue.vm", "index-tree.vue.vm"))
            {
                // 渲染模板
                StringWriter sw = new StringWriter();
                Template tpl = Velocity.getTemplate(template, Constants.UTF8);
                tpl.merge(context, sw);
                try
                {
                    String path = getGenPath(table, template);
                    FileUtils.writeStringToFile(new File(path), sw.toString(), CharsetKit.UTF_8);
                }
                catch (IOException e)
                {
                    throw new ServiceException("渲染模板失败，表名：" + table.getTableName());
                }
            }
        }
    }

    @Override
    @Transactional
    public void synchDb(String tableName) {
        GenTable table = genTableMapper.selectGenTableByName(tableName);
        List<GenTableColumn> tableColumns = table.getColumns();
        Map<String, GenTableColumn> tableColumnMap = tableColumns.stream().collect(Collectors.toMap(GenTableColumn::getColumnName, Function.identity()));

        List<GenTableColumn> dbTableColumns = genTableColumnMapper.selectDbTableColumnsByName(tableName);
        if (StringUtils.isEmpty(dbTableColumns))
        {
            throw new ServiceException("同步数据失败，原表结构不存在");
        }
        List<String> dbTableColumnNames = dbTableColumns.stream().map(GenTableColumn::getColumnName).collect(Collectors.toList());

        dbTableColumns.forEach(column -> {
            SysGenUtils.initColumnField(column, table);
            if (tableColumnMap.containsKey(column.getColumnName()))
            {
                GenTableColumn prevColumn = tableColumnMap.get(column.getColumnName());
                column.setColumnId(prevColumn.getColumnId());
                if (column.isList())
                {
                    // 如果是列表，继续保留查询方式/字典类型选项
                    column.setDictType(prevColumn.getDictType());
                    column.setQueryType(prevColumn.getQueryType());
                }
                if (StringUtils.isNotEmpty(prevColumn.getIsRequired()) && !column.isPk()
                        && (column.isInsert() || column.isEdit())
                        && ((column.isUsableColumn()) || (!column.isSuperColumn())))
                {
                    // 如果是(新增/修改&非主键/非忽略及父属性)，继续保留必填/显示类型选项
                    column.setIsRequired(prevColumn.getIsRequired());
                    column.setHtmlType(prevColumn.getHtmlType());
                }
                genTableColumnMapper.update(column);
            }
            else
            {
                genTableColumnMapper.update(column);
            }
        });

        List<GenTableColumn> delColumns = tableColumns.stream().filter(column -> !dbTableColumnNames.contains(column.getColumnName())).collect(Collectors.toList());
        if (StringUtils.isNotEmpty(delColumns))
        {
            genTableColumnMapper.deleteGenTableColumns(delColumns);
        }
    }

    /**
     * 设置主子表信息
     *
     * @param table 业务表信息
     */
    public void setSubTable(GenTable table)
    {
        String subTableName = table.getSubTableName();
        if (StringUtils.isNotEmpty(subTableName))
        {
            table.setSubTable(genTableMapper.selectGenTableByName(subTableName));
        }
    }

    /**
     * 设置主键列信息
     *
     * @param table 业务表信息
     */
    public void setPkColumn(GenTable table)
    {
        for (GenTableColumn column : table.getColumns())
        {
            if (column.isPk())
            {
                table.setPkColumn(column);
                break;
            }
        }
        if (StringUtils.isNull(table.getPkColumn()))
        {
            table.setPkColumn(table.getColumns().get(0));
        }
        if (GenConstants.TPL_SUB.equals(table.getTplCategory()))
        {
            for (GenTableColumn column : table.getSubTable().getColumns())
            {
                if (column.isPk())
                {
                    table.getSubTable().setPkColumn(column);
                    break;
                }
            }
            if (StringUtils.isNull(table.getSubTable().getPkColumn()))
            {
                table.getSubTable().setPkColumn(table.getSubTable().getColumns().get(0));
            }
        }
    }


    /**
     * 查询表信息并生成代码
     */
    private void generatorCode(String tableName, ZipOutputStream zip)
    {
        // 查询表信息
        GenTable table = genTableMapper.selectGenTableByName(tableName);
        // 设置主子表信息
        setSubTable(table);
        // 设置主键列信息
        setPkColumn(table);

        VelocityInitializer.initVelocity();

        VelocityContext context = SysVelocityUtils.prepareContext(table);

        // 获取模板列表
        List<String> templates = SysVelocityUtils.getTemplateList(table.getTplCategory(), table.getTplWebType());
        for (String template : templates)
        {
            // 渲染模板
            StringWriter sw = new StringWriter();
            Template tpl = Velocity.getTemplate(template, Constants.UTF8);
            tpl.merge(context, sw);
            try
            {
                // 添加到zip
                zip.putNextEntry(new ZipEntry(SysVelocityUtils.getFileName(template, table)));
                IOUtils.write(sw.toString(), zip, Constants.UTF8);
                IOUtils.closeQuietly(sw);
                zip.flush();
                zip.closeEntry();
            }
            catch (IOException e)
            {
                log.error("渲染模板失败，表名：" + table.getTableName(), e);
            }
        }
    }

    /**
     * 获取代码生成地址
     *
     * @param table 业务表信息
     * @param template 模板文件路径
     * @return 生成地址
     */
    public static String getGenPath(GenTable table, String template)
    {
        String genPath = table.getGenPath();
        if (StringUtils.equals(genPath, "/"))
        {
            return System.getProperty("user.dir") + File.separator + "src" + File.separator + SysVelocityUtils.getFileName(template, table);
        }
        return genPath + File.separator + SysVelocityUtils.getFileName(template, table);
    }

}
