<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>
        <p>4. 哪些表是配置数据参见 https://qa2.liangkebang.com/dbconfig/manager 中的Tables列；</p>
        <p>5. 有特殊的配置数据需求可以联系测试组（比如需要将某个渠道的MD5 key修改成一个特殊值）。</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 style="width: 300px" placeholder="要同步表结构及配置数据的数据库名称">
            <el-option v-for="item in dbNameList" :value="item" :label="item" :key="item" />
          </el-select>
        </el-form-item>
        <el-form-item label="保留业务数据">
          <el-switch v-model="temp.notDeleteBusinessData" style="margin-right:280px" />
          <span 是否保留当前已经存在的测试数据 />
        </el-form-item>
        <el-form-item label="使用备份数据">
          <el-switch v-model="temp.useCache" />
        </el-form-item>
      </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, dbsync, dbsyncQuery } from '@/api/k8s'
import { getDataBaseList } from '@/api/effect'
import { getFormData } from '@/utils/tool'
export default {
  data() {
    return {
      namespaceList: [],
      // 数据库同步接口参数
      syncData: {
        dbName: '',
        host: '',
        port: '',
        replaceDomain: true,
        notDeleteBusinessData: true,
        useCache: true
      },
      temp: {
        namespace: '',
        dbName: '',
        notDeleteBusinessData: true,
        useCache: true
      },
      desc: '',
      dbNameList: [],
      rules: {
        namespace: [{ required: true, message: '请选择环境', trigger: 'blur' }],
        dbName: [
          { required: true, message: '请输入数据库名称', trigger: 'blur' }
        ]
      },
      buildNum: undefined,
      descVisible: false,
      timer: undefined
    }
  },
  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
      })
    },
    // 同步数据库
    sync() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.namespaceList.forEach((namespace) => {
            if (namespace.name === this.temp.namespace) {
              this.syncData.host = namespace.mysqlHost
              this.syncData.port = namespace.mysqlPort
            }
          })
          this.syncData.dbName = this.temp.dbName
          this.syncData.notDeleteBusinessData = this.temp.notDeleteBusinessData
          this.syncData.useCache = this.temp.useCache
          dbsync(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.timer = window.setInterval(this.syncQuery, 3000)
            } else {
              this.$message.error(resp.data.msg)
            }
          })
        }
      })
    },
    // 查询数据库同步进度
    syncQuery() {
      dbsyncQuery({
        jobName: 'sync_database_schema',
        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)
        } else if (resp.data.data.status === 'BUILDING') {
          this.desc = resp.data.data.text
          this.$message.success('数据库同步中...')
        }
      })
    }
  }
}
</script>

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