<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" :inline="true" :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" @change="getMysql">
            <el-option v-for="item in namespaces" :value="item" :label="item" :key="item" />
          </el-select>
        </el-form-item>
        <el-form-item label="服务名" prop="mysqlName">
          <el-select v-model="temp.mysqlName" placeholder="请选择数据库环境" filterable clearable style="width: 300px">
            <el-option v-for="item in sqlList" :value="item.serviceName" :label="item.serviceName" :key="item.serviceName" />
          </el-select>
        </el-form-item>
        <el-form-item label="数据库名称" prop="dbname">
          <el-select :disabled="disableBool" v-model="temp.dbname" filterable clearable style="width: 300px" placeholder="要同步表结构及配置数据的数据库名称">
            <el-option v-for="item in dbnames" :value="item" :label="item" :key="item" />
          </el-select>
        </el-form-item>
      </el-form>
      <el-form :inline="true" :model="temp" label-width="150px">
        <el-form-item label="保留业务数据">
          <el-switch :disabled="disableBool" v-model="temp.not_delete_business_data" style="margin-right:280px" />
          <span 是否保留当前已经存在的测试数据/>
        </el-form-item>
        <el-form-item label="使用备份数据">
          <el-switch :disabled="disableBool" v-model="temp.use_cache"/>
        </el-form-item>
      </el-form>

      <div style="margin-left:420px">
        <el-button @click="goBack()">{{ $t('table.cancel') }}</el-button>
        <el-button :disabled="disableBool" type="primary" @click="sync()">{{ $t('table.confirm') }}
        </el-button>
      </div >
    </div >
    <div style="padding:10px 20px 0px">
      <!-- <div v-if="desc" style="padding:10px 20px 0px"> -->
      <textarea v-if="desc" v-model="desc" style="min-height:600px;background-color:black;width:-webkit-fill-available;color:white"/>
    </div>
  </div>
</template>

<script>
import { getNamespaceTke, getDBName, dbSyncTke, dbSyncQuery } from '@/api/dbconfig'
import { fetchK8sdetail } from '@/api/docker'
import Pagination from '@/components/Pagination' // Secondary package based on el-pagination
import JsonEditor from '@/components/JsonEditor'

export default {
  name: 'DBSync',
  components: { Pagination, JsonEditor },
  filters: {
  },
  data() {
    return {
      dialogFormVisible: false,
      dialogDeleteVisible: false,
      dialogStatus: '',
      rules: {
        dbname: [{ required: true, message: '请输入', trigger: 'change' }],
        namespace: [{ required: true, message: '请输入', trigger: 'change' }],
        mysqlName: [{ required: true, message: '请输入', trigger: 'change' }]
      },
      configs: [],
      namespace: undefined,
      sqlList: undefined,
      namespaces: [],
      dbname: undefined,
      dbnames: [],
      temp: {
        namespace: '',
        dbname: '',
        not_delete_business_data: true,
        use_cache: true,
        mysqlName: ''
      },
      desc: '',
      location: '',
      time: undefined,
      disableBool: false
    }
  },
  computed: {

  },
  watch: {
  },
  created() {
    this.temp.namespace = this.$route.query.namespace === undefined ? '' : this.$route.query.namespace
    this.getNamespace()
    if (this.temp.namespace !== '') {
      this.getMysql()
    }
    this.getDBName()
  },
  methods: {
    goBack() {
      this.$router.go(-1)
    },
    getMysql() {
      this.temp.mysqlName = ''
      fetchK8sdetail({ 'namespace': this.temp.namespace }).then(res => {
        const servicelist = res.data.services
        const mysqlList = servicelist.filter((item) => {
          return item.serviceName.indexOf('mysql') > -1
        })
        this.sqlList = mysqlList
        this.temp.mysqlName = this.sqlList[0].serviceName
      })
    },
    getNamespace() {
      getNamespaceTke().then(res => {
        this.namespaces = res.data && res.data.namespaces.map(item => item.name)
      })
    },

    getDBName() {
      getDBName().then(res => {
        this.dbnames = res.data.map(item => item.dbname)
      })
    },

    resetTemp() {
      this.temp = {
        namespace: '',
        dbname: '',
        not_delete_business_data: false,
        use_cache: false,
        mysqlName: ''
      }
    },

    syncQuery(location) {
      dbSyncQuery({ location }).then(res => {
        res = res.data
        if (this.timer > 300) {
          this.$notify({
            title: '超时',
            message: '同步超时!',
            type: 'error',
            duration: 2000
          })
          return true
        }
        if (res.status === 'complete') {
          this.desc = new Date().toLocaleTimeString() + ' 完成同步: ' + res.msg.result + '; ID: ' + res.msg.number + '\n\n\n' + res.log.body
          this.disableBool = false
          this.$notify({
            title: '成功',
            message: '完成同步!',
            type: 'success',
            duration: 2000
          })
          return true
        }
        this.timer = this.timer + 3
        this.desc = new Date().toLocaleTimeString() + ` 测试环境 ${this.temp.namespace} 正在同步 ${this.temp.dbname} 数据库，已等待 ${this.timer}s...\n\n\n` + res.log.body
        setTimeout(() => {
          this.syncQuery(location)
        }, 5000)
      })
    },

    sync() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          dbSyncTke(this.temp).then((res) => {
            this.dialogFormVisible = false
            this.location = res.data.location
            this.$notify({
              message: '正在同步',
              type: 'success',
              duration: 2000
            })
            this.desc = ''
            this.timer = 0
            this.disableBool = true
            this.syncQuery(this.location)
          }).catch(err => {
            // eslint-disable-next-line no-empty
            if (err) {}
          })
        }
      })
    }
  }
}
</script>
