<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="68px">
      <el-form-item label="连接名" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入连接名"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="主机域名" prop="host">
        <el-input
          v-model="queryParams.host"
          placeholder="请输入主机域名"
          clearable
          size="small"
          @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"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['setting:tsconfig:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['setting:tsconfig:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          icon="el-icon-delete"
          size="mini"
          :disabled="single"
          @click="handleDelete"
          v-hasPermi="['setting:tsconfig:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['setting:tsconfig:export']"
        >导出</el-button>
      </el-col>
    </el-row>

    <el-table
      v-loading="loading"
      :data="tsconfigList"
      :default-sort="{prop: 'createTime', order: 'descending'}"
      @sort-change="sortChange"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <!-- <el-table-column label="主键ID" align="center" prop="id" /> -->
      <el-table-column label="序号" type="index" align="center" width="50" />
      <el-table-column label="连接名" align="center" sortable="custom" prop="name" />
      <el-table-column label="主机域名" align="center" sortable="custom" prop="host" />
      <el-table-column label="端口" align="center" prop="port" />
      <el-table-column label="用户名" align="center" sortable="custom" prop="username" />
      <el-table-column label="数据库类型" align="center" sortable="custom" prop="dataBaseTypeName" />
      <el-table-column label="默认使用" align="center" prop="defaultUse">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.defaultUse"
            active-color="#13ce66"
            inactive-color="#ff4949"
            @change="handleUpdateDefault(scope.row)"
            v-hasPermi="['setting:tsconfig:default']"
          ></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" sortable="custom" align="center" prop="createTime" width="160">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleTestConnect(scope.row)"
            v-hasPermi="['setting:tsconfig:test']"
          >测试连接</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['setting:tsconfig:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['setting:tsconfig:remove']"
          >删除</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="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="连接名" prop="name">
          <el-input v-model="form.name" placeholder="请输入连接名" />
        </el-form-item>
        <el-form-item label="主机域名" prop="host">
          <el-input v-model="form.host" placeholder="请输入主机域名" />
        </el-form-item>
        <el-form-item label="端口" prop="port">
          <el-input v-model="form.port" placeholder="请输入端口" />
        </el-form-item>
        <el-form-item label="用户名" prop="username">
          <el-input v-model="form.username" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="form.password" placeholder="请输入密码" />
        </el-form-item>
        <el-form-item label="数据库类型">
          <el-select style="width: 100%;" v-model="form.dataBaseType" placeholder="请选择类型">
            <el-option
              v-for="(item, value) in dbBaseTypeOpt"
              :label="item"
              :key="value"
              :value="value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="默认使用" prop="defaultUse">
          <el-switch active-color="#13ce66" inactive-color="#ff4949" v-model="form.defaultUse" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="handleTestConnect(form)">测试连接</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listTsconfig,
  getTsconfig,
  delTsconfig,
  addTsconfig,
  updateTsconfig,
  updateDefaultTsconfig,
  testTsconfig
} from "@/api/setting/tsconfig";

export default {
  name: "TsConfig",
  props: {
    tenantId: {
      type: Number,
      default: null
    }
  },
  data() {
    return {
      // 数据库type
      dbBaseTypeOpt: {
        INFLUXDB: "InfluxDb",
        TDENGINE: "TDengine"
      },
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 总条数
      total: 0,
      // 设备时序数据库配置表格数据
      tsconfigList: [],
      // 数据库类型
      DBTOptions: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: undefined,
        host: undefined,
        orderByColumn: "createTime",
        isAsc: "desc"
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        tenantId: [
          { required: true, message: "租户ID不能为空", trigger: "blur" }
        ]
      }
    };
  },
  created() {
    this.getList();
    this.getDicts("data_base_type").then(response => {
      this.DBTOptions = response.data;
    });
  },
  methods: {
    sortChange(column) {
      const sort = {
        isAsc: column.order === "descending" ? "desc" : "asc",
        orderByColumn: column.prop
      };
      this.queryParams = Object.assign(this.queryParams, sort);
      this.handleQuery();
    },
    /** 查询设备时序数据库配置列表 */
    getList() {
      this.loading = true;
      listTsconfig(
        Object.assign(
          {
            tenantId: this.tenantId
          },
          this.queryParams
        )
      ).then(response => {
        this.tsconfigList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        name: undefined,
        host: undefined,
        port: undefined,
        username: undefined,
        password: undefined,
        dataBaseType: "INFLUXDB",
        defaultUse: undefined,
        tenantId: this.tenantId
      };
      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;
      getTsconfig(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改设备时序数据库配置";
      });
    },
    /** 提交按钮 */
    submitForm: function() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != undefined) {
            updateTsconfig(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              }
            });
          } else {
            addTsconfig(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              }
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm(
        // '是否确认删除设备时序数据库配置编号为"' + ids + '"的数据项?',
        "是否删除该数据",
        "警告",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }
      )
        .then(function() {
          return delTsconfig(ids);
        })
        .then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        })
        .catch(function() {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "setting/tsconfig/export",
        {
          ...this.queryParams
        },
        `setting_tsconfig.xlsx`
      );
    },
    /** 修改默认按钮操作 */
    handleUpdateDefault(row) {
      updateDefaultTsconfig(row).then(response => {
        if (response.code === 200) {
          this.msgSuccess("修改成功");
          this.open = false;
          this.getList();
        }
      });
    },
    /** 测试连接 */
    handleTestConnect(row) {
      testTsconfig(row).then(response => {
        if (response.code === 200) {
          this.msgSuccess("测试连接成功");
        }
      });
    }
  }
};
</script>
