package com.boman.gen.service;

import com.boman.common.core.constant.UserConstants;
import com.boman.common.core.utils.DateUtils;
import com.boman.common.core.utils.SecurityUtils;
import com.boman.common.core.utils.StringUtils;
import com.boman.common.core.web.domain.AjaxResult;
import com.boman.gen.domain.GenTable;
import com.boman.gen.domain.GenTableColumn;
import com.boman.gen.domain.TableSql;
import com.boman.gen.mapper.GenTableColumnMapper;
import com.boman.gen.mapper.GenTableMapper;
import com.boman.gen.mapper.TableSqlMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author tjf
 * @Date: 2021/04/14/10:43
 */
@Service
public class TableSqlServiceImpl implements ITableSqlService {

    @Autowired
    private TableSqlMapper tableSqlMapper;

    @Autowired
    private GenTableColumnMapper genTableColumnMapper;

    @Autowired
    private GenTableMapper genTableMapper;

    @Autowired
    private JdbcTemplate jdbcTemplate;


    /**
     * 创建sql语句
     *
     * @param tableSql
     * @return
     */
    @Override
    public AjaxResult insertTableSql(TableSql tableSql) {
        Long tableId = tableSql.getTableId();
        if (tableId == null) {
            return AjaxResult.error("缺少表id");
        }
        GenTable genTable = genTableMapper.selectGenTableById(tableSql.getTableId());
        String tableName = genTable.getTableName();
        tableSql.setCreateSql(createSql(tableSql, tableName));
        tableSql.setCreateBy(SecurityUtils.getUsername());
        tableSql.setCreateLog(DateUtils.getNowDate() + SecurityUtils.getUsername() + " 创建表 " + tableName);
        tableSqlMapper.insertTableSql(tableSql);
        return AjaxResult.success();
    }

    /**
     * 刷新建表语句
     *
     * @param tableSql
     * @return
     */
    @Override
    public AjaxResult reloadTableSql(TableSql tableSql) {
        GenTable genTable = genTableMapper.selectGenTableById(tableSql.getTableId());
        String tableName = genTable.getTableName();
        tableSql.setCreateSql(createSql(tableSql, tableName));
        String createLog = tableSql.getCreateLog();
        StringBuffer sb = new StringBuffer(createLog);
        sb.append("\r\n").append(DateUtils.getNowDate() + SecurityUtils.getUsername() + "刷新创建语句");
        tableSql.setCreateLog(sb.toString());
        tableSql.setUpdateBy(SecurityUtils.getUsername());
        tableSqlMapper.updateTableSql(tableSql);
        return AjaxResult.success();
    }

    /**
     * 执行建表语句
     *
     * @param tableSql
     * @return
     */
    @Override
    public AjaxResult implementSql(TableSql tableSql) {
        String createSql = tableSql.getCreateSql();
        try {
            jdbcTemplate.execute(createSql);
        } catch (DataAccessException e) {
            e.printStackTrace();
            return AjaxResult.error("当前表已存在");
        }
        String createLog = tableSql.getCreateLog();
        StringBuffer sb = new StringBuffer(createLog);
        sb.append(DateUtils.getNowDate() + SecurityUtils.getUsername() +" 执行建表语句");
        tableSqlMapper.updateTableSql(tableSql);
        return AjaxResult.success();
    }

    /**
     * 查询建表SQL
     * @param id
     * @return
     */
    @Override
    public AjaxResult selectTableSqlByTableId(Long id) {
        TableSql tableSql = tableSqlMapper.selectTableSqlByTableId(id);
        return AjaxResult.success(tableSql);
    }


    /**
     * 生成建表语句
     *
     * @param tableSql
     * @param tableName
     * @return
     */
    private String createSql(TableSql tableSql, String tableName) {
        //根据表id查询所有字段
        List<GenTableColumn> genTableColumns = genTableColumnMapper.selectGenTableColumnListByTableId(tableSql.getTableId());
        //定义主键id
        String primaryKey = null;
        //拼接建表语句
        StringBuffer sb = new StringBuffer("create table if not exists ");
        sb.append(tableName).append(" (\r\n");

        for (GenTableColumn genTableColumn : genTableColumns) {
            sb.append(genTableColumn.getColumnName()).append(" " + genTableColumn.getColumnType());
            if (genTableColumn.getIsIncrement().equals(UserConstants.INCREMENT)) {
                sb = genTableColumn.getDefaultValue() == null ? sb.append(" DEFAULT NULL AUTO_INCREMENT COMMENT ") : sb.append(" DEFAULT '" + genTableColumn.getDefaultValue() + "' AUTO_INCREMENT COMMENT '");
            } else {
                sb = genTableColumn.getDefaultValue() == null ? sb.append(" DEFAULT NULL COMMENT ") : sb.append(" DEFAULT '" + genTableColumn.getDefaultValue() + "' COMMENT '");
            }
            sb.append(genTableColumn.getColumnComment() + "'").append(",\r\n");
            if (genTableColumn.getIsPk().equals(UserConstants.INCREMENT)) {
                primaryKey = genTableColumn.getColumnName();
            }
        }
        if (StringUtils.isNotBlank(primaryKey)) {
            sb.append(" PRIMARY KEY (" + primaryKey + " ) USING BTREE\r\n");
        }
        sb.append(") ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci ROW_FORMAT=DYNAMIC COMMENT='" + tableName + "';");
        return sb.toString();
    }

}
