<template>
  <div>
    <el-alert :closable="false" title="同步说明" type="info" style="font-size: 13px;" show-icon>
      <slot name="description">
        <p>1. 同步数据库是将线上的表结构和配置数据同步到测试库；</p>
        <p>2. 保留业务数据的意思是仅将线上的表结构同步到测试库，但仍保留测试环境的业务数据；</p>
        <p>3. 如果测试环境没有对应的库或者表，同步数据库时，请不要勾选保留业务数据，否则会导致同步失败；</p>
      </slot>
    </el-alert>
    <div class="app-container" style="width:1000px; margin:0 auto;">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-width="150px" style="margin-bottom:15px">
        <el-form-item label="Namespace：" prop="namespace">
          <el-select v-model="temp.namespace" placeholder="要同步的数据库所在环境" filterable clearable style="width: 300px">
            <el-option v-for="item in namespaceList" :value="item.name" :label="item.name" :key="item.name" />
          </el-select>
        </el-form-item>
        <el-form-item label="数据库名：" prop="dbName">
          <el-select v-model="temp.dbName" filterable clearable @clear="setValueNull" style="width: 300px"
            placeholder="要同步的数据库名称" @change="dbChange">
            <el-option v-for="item in dbNameList" :value="item" :label="item" :key="item" />
          </el-select>
        </el-form-item>
        <el-form-item label="表名：" prop="tableName">
          <el-select v-model="temp.tableName" placeholder="要同步的表名" style="width:300px" filterable clearable>
            <el-option v-for="item in tableList" :key="item" :label="item" :value="item">
            </el-option>
          </el-select>
        </el-form-item>
        <el-tooltip class="item" effect="dark" content="是否仅将线上的表结构同步到测试库，且仍保留测试环境的业务数据" placement="bottom-start">
          <el-form-item label="是否保留业务数据：" prop="notDeleteBusinessData">
            <el-switch v-model="temp.notDeleteBusinessData" style="margin-right:280px" active-text="是"
              inactive-text="否" />
          </el-form-item>
        </el-tooltip>
      </el-form>

      <div style="margin-left:420px">
        <el-button @click="goBack()">取消</el-button>
        <el-button type="primary" @click="sync()">确认
        </el-button>
      </div>
    </div>
    <div style="padding:10px 20px 0px">
      <!-- <div v-if="desc" style="padding:10px 20px 0px"> -->
      <textarea v-if="descVisible" v-model="desc"
        style="min-height:600px;background-color:black;width:-webkit-fill-available;color:white" />
    </div>
  </div>
</template>

<script>
import { getNamespaceList, dbsyncQuery } from '@/api/k8s'
import { getDataBaseList, getTableByDataBase, dbsyncNew } from '@/api/effect'
import { getFormData } from '@/utils/tool'
export default {
  data() {
    return {
      namespaceList: [],
      // 数据库同步接口参数
      syncData: {
        namespace: '',
        targetHost: '',
        targetPort: '',
        database: '',
        table: '',
        businessData: ''
      },
      temp: {
        namespace: '',
        dbName: '',
        tableName: '',
        notDeleteBusinessData: false
      },
      desc: '',
      dbNameList: [],
      tableList: [],
      rules: {
        namespace: [{ required: true, message: '请选择环境', trigger: 'blur' }],
        dbName: [
          { required: true, message: '请输入数据库名称', trigger: 'blur' }
        ],
        tableName: [{ required: true, message: '请输入表名', trigger: 'blur' }],
        notDeleteBusinessData: [
          { required: true, message: '请选择是否保留业务数据', trigger: 'blur' }
        ]
      },
      buildNum: undefined,
      descVisible: false,
      timer: undefined,
      tLoading: undefined,
      loadingOptions: {
        text: '数据库同步中...',
        lock: true,
        spinner: 'el-icon-loading',
        background: 'rgba(0,0,0,0.7)'
      }
    }
  },
  created() {
    this.getNamespaces()
    this.getDatabases()
  },
  methods: {
    goBack() {
      this.$router.go(-1)
    },
    // 获取环境列表
    getNamespaces() {
      getNamespaceList({ env: 'all' }).then((resp) => {
        this.namespaceList = resp.data.data
      })
    },
    getDatabases() {
      getDataBaseList().then((resp) => {
        this.dbNameList = resp.data.data
        this.dbNameList.unshift('all')
      })
    },
    // 数据库变更时
    dbChange() {
      this.tableList = []
      if (this.temp.dbName === 'all') {
        this.tableList.push('all')
      } else {
        getTableByDataBase({ dbName: this.temp.dbName }).then((resp) => {
          this.tableList = resp.data.data
        })
      }
    },
    // 同步数据库
    sync() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.syncData.namespace = this.temp.namespace
          this.namespaceList.forEach((namespace) => {
            if (namespace.name === this.temp.namespace) {
              this.syncData.targetHost = namespace.mysqlHost
              this.syncData.targetPort = namespace.mysqlPort
            }
          })
          this.syncData.database = this.temp.dbName
          this.syncData.table = this.temp.tableName
          this.syncData.businessData = this.temp.notDeleteBusinessData
          dbsyncNew(getFormData(this.syncData)).then((resp) => {
            this.descVisible = true
            if (resp.data.data !== 0) {
              this.buildNum = resp.data.data
              this.$message.success(resp.data.msg)
              this.tLoading = this.$loading.service(this.loadingOptions)
              // 查询结果
              this.timer = window.setInterval(this.syncQuery, 3000)
            } else {
              this.$message.error(resp.data.msg)
            }
          })
        }
      })
    },
    // 查询数据库同步进度
    syncQuery() {
      dbsyncQuery({
        jobName: 'db_sync',
        buildNum: this.buildNum
      }).then((resp) => {
        if (resp.data.data.status === 'SUCCESS') {
          this.$message({
            showClose: true,
            message: '数据库同步完成！',
            type: 'success'
          })
          this.desc = resp.data.data.text
          // 清除定时器
          window.clearInterval(this.timer)
          this.tLoading.close()
        } else if (resp.data.data.status === 'BUILDING') {
          this.desc = resp.data.data.text
          this.$message.success('数据库同步中...')
        }
      })
    },
    // 清空时间
    setValueNull() {
      this.temp.tableName = ''
    }
  }
}
</script>

<style lang="less" scoped>
.app-container {
  padding: 20px;
}
</style>
