import com.sdtool.common.api.BusinessExecutor
import com.sdtool.common.datas.ERPModule
import com.sdtool.common.entity.base.InvokeCallParams
import com.sdtool.common.entity.base.InvokeCallResult
import com.dySweetFishPlugin.sql.DBService
import com.dySweetFishPlugin.sql.dao.OperatorWait
import com.sweetfish.service.RetResult
import groovy.json.JsonSlurper
import org.apache.logging.log4j.LogManager
import org.apache.logging.log4j.Logger
import org.rex.RMap
import org.rex.db.exception.DBException

import javax.annotation.Resource

/**
 * 修改数据库中的表和视图名称，方便创建一个新库出来
 * 调用AdminRest的execAdminAsync方法即可
 * businessCode = DataBase_Rename
 * execParams = {destSource:'erp002', tableSchema:'zmerp20230523', oldSupplier:'1000', newSupplier:'2000'}
 * PostMap的地址全部为
 * http://192.168.1.24:8000/apis/admin/v1/execAdminAsync?businessCode=DataBase_Rename&execParams={destSource:'erp002', tableSchema:'zmerp20230523', oldSupplier:'1000', newSupplier:'2000'}
 * 需要先在rexdb的配置中添加erp002的数据源
 * tableSchema对应为数据库
 *
 */
class BE_DataBase_Rename implements BusinessExecutor<InvokeCallParams, InvokeCallResult> {

    protected final Logger logger = LogManager.getLogger(this.getClass().getSimpleName())

    @Resource
    DBService dbService

    @Override
    String scriptName() {
        return "数据库表名视图名批量修改-用于新建一个ERP库"
    }

    @Override
    ERPModule module() {
        return ERPModule.DATA_SYNC
    }

    @Override
    OperatorWait getAWait(InvokeCallParams source) {
        return OperatorWait.ASNYC
    }

    @Override
    boolean needLogin(InvokeCallParams source) {
        return true
    }

    @Override
    RetResult<InvokeCallResult> execute(InvokeCallParams source) {
        JsonSlurper jsonSlurper = new JsonSlurper()
        def invokeData = jsonSlurper.parseText(source.params)

        String destSource = invokeData["destSource"] as String
        String tableSchema = invokeData["tableSchema"] as String
        String oldSupplier = invokeData["oldSupplier"] as String
        String newSupplier = invokeData["newSupplier"] as String

        List<RMap> tableList = dbService.getMapList(destSource, "select * from information_schema.TABLES where table_schema = '" + tableSchema + "'")
        tableList.each { map ->
            String tableName = map.getString("tableName")
            String newTableName = tableName.replace(oldSupplier, newSupplier)

            if (map.getString("tableType").equalsIgnoreCase("base table")) {
                String sql = "rename table " + tableName + " to " + newTableName
                logger.info(sql)
                try {
                    dbService.update(destSource, sql)
                } catch (DBException e) {
                    logger.error(e.getMessage())
                }
            } else if (map.getString("tableType").equalsIgnoreCase("view")) {
                //视图里面的语句也需要修改
                RMap viewMap = dbService.getMap(destSource, "show create table  " + tableName)
                String viewCreateSql = viewMap.getString("create view")
                String sql1 = "drop view if exists " + tableName
                logger.info(sql1)
                String sql2 = viewCreateSql.replace(oldSupplier, newSupplier)
                logger.info(sql2)

                try {
                    dbService.update(destSource, sql1)
                    dbService.update(destSource, sql2)
                } catch (DBException e) {
                    logger.error(e.getMessage())
                }
            }
        }

        return RetResult.successT()
    }
}


