<template>
  <div>
    <!-- 选择外部数据弹框 -->
    <el-dialog title="选择外部数据库" :visible.sync="isShow" @open="DBDialogOpen" append-to-body :close-on-click-modal="false" class="database-list-dialog">
      <!-- 工具栏 -->
      <el-toolbar>
        <el-button @click="addClick">
          <i class="fa fa-plus"></i>新建</el-button>
      </el-toolbar>
      <!-- 数据库信息表格 -->
      <el-table :data="databaseData" data-read-url="/ui/database/binddata" ref="dataTable" :page-size="10" :auto-get-data="false" tooltip-effect="dark" highlight-current-row @row-click="onRowClick" @row-dblclick="rowDBClick">
        <el-table-column type="index" width="60" align="center" label="序号"></el-table-column>
        <el-table-column label="数据库别名">
          <template slot-scope="scope">
            <el-radio v-model="selectedRow" :label="scope.row">{{scope.row.name}}</el-radio>
          </template>
        </el-table-column>
        <el-table-column prop="DBName" label="数据库名称"></el-table-column>
        <el-table-column prop="serverTypeName" label="服务器类型"></el-table-column>
        <el-table-column prop="address" label="服务器地址"></el-table-column>
        <el-table-column prop="memo" label="备注"></el-table-column>
        <el-table-column label="操作" align="right">
          <template slot-scope="scope">
            <el-button type="text" @click.stop="editClick(scope.row)"><i class="fa fa-edit f16"></i></el-button>
            <el-button type="text" @click.stop="deleteClick(scope.row.ID)"><i class="fa fa-remove f16"></i></el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 底部确认按钮 -->
      <div slot="footer">
        <el-button @click="isShow = false">取 消</el-button>
        <el-button type="primary" @click="externalDatabaseConfirm">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 新建/编辑数据库连接信息弹框 -->
    <el-dialog :title="editMode==1 ? '编辑数据库连接信息':'新建数据库连接信息' " :visible.sync="DBConnectModal" @open="DBConnectDialogOpen" append-to-body
      class="database-item-dialog">
      <el-form :model="tmpDBConnect" ref="DBConnectDataForm" label-suffix="：" label-width="140px">
        <el-form-item label="数据库别名" prop="name" :verify="['NotNull']">
          <el-input v-model="tmpDBConnect.name" class="form-input"></el-input>
        </el-form-item>
        <el-form-item label="服务器类型" prop="serverType" :verify="['NotNull']">
          <el-select v-model="tmpDBConnect.serverType" class="form-input">
            <el-option v-for="str in serverTypeOptions" :key="str.codeValue" :label="str.codeName" :value="str.codeValue">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="服务器地址" prop="address" :verify="['NotNull']">
          <el-input v-model="tmpDBConnect.address" class="form-input"></el-input>
        </el-form-item>
        <el-form-item label="服务器端口" prop="port" :verify="['NotNull']">
          <el-input-number v-model="tmpDBConnect.port" class="form-input"></el-input-number>
        </el-form-item>
        <el-form-item label="用户名" prop="userName" :verify="['NotNull']">
          <el-input v-model="tmpDBConnect.userName" class="form-input"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password" :verify="['NotNull']">
          <el-input type="password" v-model="tmpDBConnect.password" class="form-input"></el-input>
        </el-form-item>
        <el-form-item label="数据库名称" prop="DBName" :verify="['NotNull']">
          <el-input v-model="tmpDBConnect.DBName" class="form-input"></el-input>
        </el-form-item>
        <el-form-item label="测试表名" prop="testTable" :verify="['NotNull']">
          <el-input v-model="tmpDBConnect.testTable" class="form-input"></el-input>
        </el-form-item>
        <el-form-item label="备注" prop="memo">
          <el-input v-model="tmpDBConnect.memo" class="form-input"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部测试/确认按钮 -->
      <div slot="footer">
        <el-button @click="databaseConnectTest">测试连接</el-button>
        <el-button type="primary" @click="databaseConnectConfirm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>

import util from '@src/common/util.js'

export default {
  props: {
    show: [Boolean]
  },
  data() {
    return {
      selectedRow: {}, // 选中的数据库列表行
      DBConnectModal: false, // 控制数据库表单弹框
      databaseData: [],
      editMode: 1, // 区分新建和编辑
      tmpDBConnect: {}, // 数据库表单对象
      serverTypeOptions: [] // 服务器类型选项
    }
  },
  computed: {
    isShow: {
      get() {
        return this.show
      },
      set(val) {
        this.$emit('update:show', val)
      }
    }
  },
  methods: {
    /**
       * 弹框打开回调
       */
    DBDialogOpen() {
      this.selectedRow = {}
      this.$nextTick(() => {
        this.getDBConnectData()
      })
    },
    /**
       * 数据库表单弹框打开回调
       */
    async DBConnectDialogOpen() {
      let res = await axios.get('/ui/codes/Database.Type/items')
      this.serverTypeOptions = res.data.data
    },
    rowDBClick(row) {
      this.tmpDBConnect = Object.assign({}, row)
      this.editMode = 1
      this.DBConnectModal = true
    },
    /**
       * 获取数据库列表数据
       */
    getDBConnectData() {
      this.$refs.dataTable.getData()
    },
    // 外部数据库连接表格改变选中行触发事件
    onRowClick(row) {
      this.selectedRow = row
    },
    // 添加外部数据库数据
    addClick() {
      this.tmpDBConnect = {
        port: '',
        serverType: ''
      }
      this.editMode = 0
      this.DBConnectModal = true
    },
    // 编辑外部数据库数据
    editClick(row) {
      this.tmpDBConnect = Object.assign({}, row)
      this.editMode = 1
      this.DBConnectModal = true
    },
    // 新建/编辑数据库连接信息弹框测试链接按钮
    async databaseConnectTest() {
      try {
        await util.validateForm(this.$refs['DBConnectDataForm'])
      } catch (e) {
        util.showErrorMessageBox(e)
        return
      }
      let res = await axios.put(
        `/ui/database/testconnect`,
        this.tmpDBConnect
      )
      util.showResponseMessage(res.data)
    },
    // 新建/编辑数据库连接信息弹框确认按钮
    async databaseConnectConfirm() {
      try {
        await util.validateForm(this.$refs['DBConnectDataForm'])
      } catch (e) {
        util.showErrorMessageBox(e)
        return
      }
      // 判断是新建框还是编辑框
      if (this.editMode === 1) {
        let res = await axios.put(
          `/ui/database/${this.tmpDBConnect.ID}`,
          this.tmpDBConnect
        )
        util.showResponseMessage(res.data)
        if (res.data.status === 1) {
          this.DBConnectModal = false
          this.getDBConnectData()
        }
      }
      if (this.editMode === 0) {
        let res = await axios.post('/ui/database', this.tmpDBConnect)
        util.showResponseMessage(res.data)
        if (res.data.status === 1) {
          this.DBConnectModal = false
          this.getDBConnectData()
        }
      }
    },
    // 删除外部数据库数据
    async deleteClick(ID) {
      try {
        await this.$confirm('确认删除？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
      } catch (e) {
        return
      }
      let res = await axios.delete(`/ui/database/${ID}`)
      util.showResponseMessage(res.data)
      if (res.data.status === 1) {
        this.getDBConnectData()
      }
    },
    // 选择外部数据库弹框底部确认按钮
    externalDatabaseConfirm() {
      // 判断是否有选中的记录
      if (!this.selectedRow.ID) {
        this.$alert('请先选择一条记录', '提示', {
          confirmButtonText: '确定'
        })
        return
      }
      this.$emit('callback', this.selectedRow)
      this.isShow = false
    }
  }
}
</script>
<style>
  /* 在一般情况下dialog宽为800像素，在逻辑分辨率480像素以下dialog宽为96% */

  .database-list-dialog .el-dialog {
    width: 800px;
  }

  @media (max-width: 480px) {
    .database-list-dialog.el-dialog {
      width: 96%;
    }
  }

  .database-item-dialog .el-dialog {
    width: 550px;
  }

  @media (max-width: 480px) {
    .database-item-dialog.el-dialog {
      width: 96%;
    }
  }
</style>

<style scoped>
  .form-input {
    width: 80%;
  }

  .input-330 {
    width: 330px;
  }

  .pageBar {
    text-align: right;
    margin-top: 10px;
    padding-right: 20px;
  }
</style>
