<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      :class="showSearch ? '' : ' hide'"
      label-width="90px"
    >
      <el-form-item label="数据源别名" prop="aliasName">
        <el-input
          v-model="queryParams.aliasName"
          placeholder="请输入数据源别名"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="数据库名" prop="databaseName">
        <el-input
          v-model="queryParams.databaseName"
          placeholder="请输入数据库名"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system/base:database:add']"
          >新增</el-button
        >
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="databaseList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column
        label="编号"
        align="center"
        prop="id"
        width="80"
      ></el-table-column>
      <el-table-column label="数据源别名" prop="aliasName" />
      <el-table-column label="数据库名" prop="databaseName" />
      <el-table-column label="数据库类型" align="center" prop="databaseType">
        <template slot-scope="scope">
          <dict-tag
            :options="dict.type.sys_database_type"
            :value="scope.row.databaseType"
          />
        </template>
      </el-table-column>
      <el-table-column
        label="最后更新时间"
        align="center"
        prop="updateTime"
        width="180"
      >
        <template slot-scope="scope">
          <span v-if="scope.row.updateTime">{{
            parseTime(scope.row.updateTime, "{y}-{m}-{d} {h}:{i}:{s}")
          }}</span>
          <span v-else>
            {{ parseTime(scope.row.createTime, "{y}-{m}-{d} {h}:{i}:{s}") }}
          </span>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status" width="120">
        <template slot-scope="scope">
          <el-tag type="success" v-if="scope.row.status === '1'" size="small"
            >正常</el-tag
          >
          <el-tag type="info" v-if="scope.row.status === '0'" size="small"
            >同步中</el-tag
          >
          <el-tag type="danger" v-if="scope.row.status === '9'" size="small"
            >同步失败</el-tag
          >
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
        min-width="100"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system/base:database:edit']"
            >修改</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system/base:database:remove']"
            >删除</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-refresh"
            @click="handleSync(scope.row)"
            v-hasPermi="['system/base:database:edit']"
          >
            更新表结构
            <el-tooltip content="从当前数据源中更新所有表结构" placement="left"
              ><i class="el-icon-warning"></i
            ></el-tooltip>
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-refresh"
            @click="handleSyncData(scope.row)"
            v-hasPermi="['system/base:database:edit']"
          >
            同步到整合数据
            <el-tooltip
              content="将最新的数据表结构同步到整合数据"
              placement="left"
              ><i class="el-icon-warning"></i
            ></el-tooltip>
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改数据源对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="700px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="数据源别名" prop="aliasName">
          <el-input v-model="form.aliasName" placeholder="请输入数据源别名" />
        </el-form-item>
        <el-form-item label="数据库名" prop="databaseName">
          <el-input
            v-model="form.databaseName"
            placeholder="请输入数据库名"
            :disabled="form.id > 0"
          />
        </el-form-item>
        <el-form-item label="数据库类型" prop="databaseType">
          <el-select
            v-model="form.databaseType"
            placeholder="请选择数据库类型"
            :disabled="form.id > 0"
          >
            <el-option
              v-for="dict in dict.type.sys_database_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="是否可写入" prop="cacheFlag">
          <el-select v-model="form.cacheFlag" placeholder="请选择是否可写入">
            <el-option
              v-for="dict in dict.type.sys_yes_no"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="连接字符串" prop="connectionString">
          <el-input
            v-model="form.connectionString"
            type="textarea"
            placeholder="请输入内容"
            :disabled="form.id > 0"
          />
          <div v-if="form.databaseType">
            <span v-if="form.databaseType === 'dm8'"
              >示例：dm://用户名:密码@数据库ip:端口</span
            >
            <span v-if="form.databaseType === 'mysql'"
              >示例：用户名:密码@(IP:PORT)/数据库名?charset=utf8</span
            >
            <span v-if="form.databaseType === 'postgres' || form.databaseType === 'kingbase'"
              >示例：host=数据库ip port=数据库端口 user=用户名 password=密码 dbname=数据库名称 sslmode=disable</span
            >
          </div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm" :loading="submitting"
          >确 定</el-button
        >
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listDatabase,
  getDatabase,
  delDatabase,
  addDatabase,
  updateDatabase,
  syncDatabase,
  syncToData,
} from "@/api/system/base/database";

export default {
  name: "Database",
  dicts: ["sys_yes_no", "sys_database_type"],
  data() {
    return {
      // 遮罩层
      loading: true,
      submitting: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 数据源表格数据
      databaseList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        aliasName: null,
        databaseName: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        aliasName: [
          { required: true, message: "数据源别名不能为空", trigger: "change" },
        ],
        databaseName: [
          { required: true, message: "数据库名不能为空", trigger: "change" },
        ],
        databaseType: [
          { required: true, message: "数据库类型不能为空", trigger: "change" },
        ],
        connectionString: [
          { required: true, message: "连接字符串不能为空", trigger: "change" },
        ],
        cacheFlag: [
          { required: true, message: "是否可写入不能为空", trigger: "change" },
        ],
      },
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询数据源列表 */
    getList() {
      this.loading = true;
      listDatabase(this.queryParams).then((response) => {
        this.databaseList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        aliasName: null,
        databaseName: null,
        databaseType: null,
        cacheFlag: null,
        connectionString: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        delFlag: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加数据源";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getDatabase(id).then((response) => {
        this.form = response.data;
        this.open = true;
        this.title = "修改数据源";
      });
    },
    handleSync(row) {
      const self = this;
      this.$modal
        .confirm("是否重新获取当前数据源的数据结构，同步将采用异步方式？")
        .then(function () {
          const id = row.id;
          syncDatabase(id).then((response) => {
            self.$modal.msgSuccess("同步成功，请刷新查看同步结果");
            self.getList();
          });
        })
        .catch(() => {});
    },
    handleSyncData(row) {
      const self = this;
      this.$modal
        .confirm(
          "是否将当前数据源最新数据结构同步到整合数据，同步将采用异步方式？"
        )
        .then(function () {
          const id = row.id;
          syncToData(id).then((response) => {});
          self.$modal.msgSuccess("同步成功，请前往整合数据查案同步结果");
          self.getList();
        })
        .catch(() => {});
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          this.submitting = true;
          if (this.form.id != null) {
            updateDatabase(this.form)
              .then((response) => {
                this.submitting = false;
                this.$modal.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              })
              .catch(() => {
                this.submitting = false;
              });
          } else {
            addDatabase(this.form)
              .then((response) => {
                this.submitting = false;
                this.$modal.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              })
              .catch(() => {
                this.submitting = false;
              });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal
        .confirm('是否确认删除数据源编号为"' + ids + '"的数据项？')
        .then(function () {
          return delDatabase(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "system/base/database/export",
        {
          ...this.queryParams,
        },
        `database_${new Date().getTime()}.xlsx`
      );
    },
  },
};
</script>
