package com.boman.gen.service;

import com.boman.domain.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.domain.dto.AjaxResult;
import com.boman.domain.GenTable;
import com.boman.domain.GenTableColumn;
import com.boman.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 tableComment = genTable.getTableComment();
        String tableName = genTable.getTableName();
        tableSql.setCreateSql(createSql(tableSql, tableComment,tableName));
        tableSql.setCreateBy(SecurityUtils.getUsername());
        tableSql.setCreateLog(DateUtils.getTime() + " " + 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 tableComment = genTable.getTableComment();
        String tableName = genTable.getTableName();
        tableSql.setCreateSql(createSql(tableSql, tableComment,tableName));
        String createLog = tableSql.getCreateLog();
        StringBuffer sb = new StringBuffer(createLog);
        sb.append("\r\n").append(DateUtils.getTime()).append(" ").append(SecurityUtils.getUsername()).append("刷新创建语句");
        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();
        GenTable genTable = genTableMapper.selectGenTableById(tableSql.getTableId());
        try {
            int i = tableSqlMapper.testExists(genTable.getTableName());
            if (i >= 0){
                return AjaxResult.error("当前表已存在");
            }
        } catch (DataAccessException e) {
            try {
                jdbcTemplate.execute(createSql);
                String createLog = tableSql.getCreateLog();
                StringBuffer sb = new StringBuffer(createLog);
                sb.append("\r\n").append(DateUtils.getTime()).append(" ").append(SecurityUtils.getUsername()).append(" 执行建表语句");
                tableSql.setCreateLog(sb.toString());
                tableSqlMapper.updateTableSql(tableSql);
            } catch (DataAccessException ex) {
                ex.printStackTrace();
                return AjaxResult.error("语句有误");
            }
        }
        return AjaxResult.success();
    }

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

    /**
     * 删除建表语句
     * @param ids
     * @return
     */
    @Override
    public int deleteTableSqlByTableIds(Long[] ids) {
        return  tableSqlMapper.deleteTableSqlByTableIds(ids);
    }


    /**
     * 生成建表语句
     *
     * @param tableSql
     * @param tableComment
     * @return
     */
    private String createSql(TableSql tableSql,String tableComment,String tableName) {
        //根据表id查询所有字段
        List<GenTableColumn> genTableColumns = genTableColumnMapper.selectGenTableColumnListByTableId(tableSql.getTableId());
        //定义主键id
        String primaryKey = null;
        //拼接建表语句
        StringBuffer sb = new StringBuffer("create table if not exists ");
        String trimName = StringUtils.trim(tableComment);
        String tableNameTrim = StringUtils.trim(tableName);
        sb.append(tableNameTrim).append(" (\r\n");
        for (GenTableColumn genTableColumn : genTableColumns) {
            if (!"HR".equals(genTableColumn.getHtmlType())){
                sb.append("`").append(StringUtils.trim(genTableColumn.getColumnName())).append("` ").append(StringUtils.trim(genTableColumn.getColumnType()));
                if (genTableColumn.getIsPk().equals(UserConstants.INCREMENT)) {
                    primaryKey = genTableColumn.getColumnName();
                    sb.append(" NOT NULL COMMENT '");
                }else {
                    sb = genTableColumn.getDefaultValue() == null ? sb.append(" DEFAULT NULL COMMENT '") : sb.append(" DEFAULT '").append(StringUtils.trim(genTableColumn.getDefaultValue())).append("' COMMENT '");
                }
                sb.append(StringUtils.trim(genTableColumn.getColumnComment())).append("'").append(",").append("\r\n");
            }
        }
        if (StringUtils.isNotBlank(primaryKey)) {
            sb.append(" PRIMARY KEY (").append(primaryKey).append(" ) USING BTREE\r\n");
        }else {
            sb.replace(sb.lastIndexOf(","),sb.length(),"\r\n");
        }
        sb.append(") ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci ROW_FORMAT=DYNAMIC COMMENT='").append(trimName).append("';");
        return sb.toString();
    }

}
