<template>
  <div class="app-container">
    <el-row :gutter="20">
      <el-col :span="4" :xs="24">
        <catalogue-tree
          @callback="catalogueCallBack"
          catalogueType="integration"
        />
      </el-col>
      <el-col :span="20" :xs="24">
        <el-form
          :model="queryParams"
          ref="queryForm"
          size="small"
          :inline="true"
          v-show="showSearch"
          label-width="68px"
        >
          <el-form-item label="数据名称" prop="dataName">
            <el-input
              v-model="queryParams.dataName"
              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/integration:data:add']"
              >新增</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="success"
              plain
              icon="el-icon-edit"
              size="mini"
              @click="handleMount"
              v-hasPermi="['system/integration:data:add']"
              >挂载</el-button
            >
          </el-col>
          <right-toolbar
            :showSearch.sync="showSearch"
            @queryTable="getList"
          ></right-toolbar>
        </el-row>

        <el-table v-loading="loading" :data="dataList">
          <el-table-column label="编号" align="center" prop="id" width="80" />
          <el-table-column label="数据名称" prop="dataName" />
          <el-table-column label="表名" prop="tableName" />
          <el-table-column label="标签" prop="tag" />
          <el-table-column
            label="创建时间"
            align="center"
            prop="createTime"
            width="180"
          >
            <template slot-scope="scope">
              <span>{{
                parseTime(scope.row.createTime, "{y}-{m}-{d} {h}:{i}:{s}")
              }}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="更新时间"
            align="center"
            prop="updateTime"
            width="180"
          >
            <template slot-scope="scope">
              <span>{{
                parseTime(scope.row.updateTime, "{y}-{m}-{d} {h}:{i}:{s}")
              }}</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="handleUpdate(scope.row)"
                v-hasPermi="['system/integration:data:edit']"
                >修改</el-button
              >
              <el-button
                size="mini"
                type="text"
                icon="el-icon-delete"
                @click="handleDelete(scope.row)"
                v-hasPermi="['system/integration:data: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-col>
    </el-row>

    <!-- 添加或修改整合数据对话框 -->
    <el-dialog
      :title="title"
      :visible.sync="open"
      width="1000px"
      append-to-body
      :close-on-click-modal="false"
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="数据源" prop="databaseId">
              <el-select
                v-model="form.databaseId"
                placeholder="请选择数据源"
                @change="changeDb"
                filterable
                :disabled="form.id > 0"
              >
                <el-option
                  :label="`${db.databaseName}（${db.aliasName}）`"
                  :value="db.id"
                  v-for="(db, i) in databaseList"
                  :key="i"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="表名" prop="tableId" required>
              <el-select
                v-model="form.tableId"
                placeholder="请选择表"
                @change="changeTb"
                v-if="!form.id"
                filterable
              >
                <el-option
                  :label="`${tb.tableName}`"
                  :value="tb.id"
                  v-for="(tb, i) in tableList"
                  :key="i"
                ></el-option>
              </el-select>
              <span v-else>{{ form.tableName }}</span>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="目录" prop="catalogueId" required>
              <treeselect
                v-model="form.catalogueId"
                :options="treeList"
                :show-count="true"
                placeholder="请选择目录"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="数据名称" prop="dataName">
              <el-input v-model="form.dataName" placeholder="请输入数据名称" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="信息标识符" prop="infoId">
              <el-input v-model="form.infoId" placeholder="请输入信息标识符" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="提供机构" prop="provideOrganization">
              <el-select
                v-model="form.provideOrganization"
                placeholder="请选择提供机构"
                filterable
              >
                <el-option
                  v-for="dict in dict.type.sys_provide_organization"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="标签" prop="tag">
              <el-select
                v-model="form.tag"
                placeholder="请选择"
                multiple
                style="width: 100%"
                filterable
              >
                <el-option
                  v-for="(tag, i) in tagList"
                  :label="tag.tagName"
                  :value="tag.tagName"
                  :key="i"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="描述" prop="remark">
              <el-input
                v-model="form.remark"
                type="textarea"
                placeholder="请输入内容"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <el-table :data="columnList" max-height="350">
        <el-table-column
          label="序号"
          type="index"
          align="center"
        ></el-table-column>
        <el-table-column
          label="英文名称"
          prop="columnName"
          show-overflow-tooltip=""
        ></el-table-column>
        <el-table-column
          label="中文名称"
          prop="columnComment"
        ></el-table-column>
        <el-table-column
          label="数据格式"
          prop="columnType"
          width="150"
        ></el-table-column>
        <!-- <el-table-column
          label="是否必填"
          prop="isRequired"
          width="100"
          align="center"
        ></el-table-column> -->
      </el-table>
      <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>

    <!-- 挂载 -->
    <el-dialog
      title="挂载"
      :visible="true"
      width="800px"
      append-to-body
      v-if="mount"
      @close="cancel"
    >
      <el-form
        ref="mountForm"
        :model="mountForm"
        :rules="rules"
        label-width="80px"
      >
        <el-form-item label="数据源" prop="databaseId">
          <el-select
            v-model="mountForm.databaseId"
            placeholder="请选择数据源"
            filterable
            @change="changeDb"
          >
            <el-option
              :label="`${db.aliasName}（${db.databaseName}）`"
              :value="db.id"
              v-for="(db, i) in databaseList"
              :key="i"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <el-table
        :data="tableList"
        @selection-change="handleSelectionChange"
        :height="500"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="表名" prop="tableName"></el-table-column>
        <el-table-column label="表描述" prop="tableComment"></el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button
          type="primary"
          @click="submitMountForm"
          :loading="submitting"
          :disabled="
            !selectedTableList || selectedTableList.length === 0 ? true : false
          "
          >确 定</el-button
        >
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listData,
  getData,
  delData,
  addData,
  updateData,
  mountData,
  getDataItem,
} from "@/api/system/integration/data";
import { listCatalogue } from "@/api/system/integration/catalogue";
import {
  listDatabase,
  listTable,
  listColumn,
} from "@/api/system/base/database";
import { listTag } from "@/api/system/base/tag";

import CatalogueTree from "@/components/CatalogueTree";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
export default {
  name: "Data",
  dicts: ["sys_provide_organization", "sys_yes_no", "sys_audit_status"],
  components: { CatalogueTree, Treeselect },
  data() {
    return {
      // 遮罩层
      loading: true,
      submitting: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 整合数据表格数据
      dataList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 挂载弹出层
      mount: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        catalogueId: null,
        databaseId: null,
        tableId: null,
        tableName: null,
        infoId: null,
        tag: null,
        provideOrganization: null,
        status: null,
        isMetadata: "N",
        repetitionField: null,
      },
      // 目录树
      treeList: [],
      // 标签
      tagList: [],
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        databaseId: [
          { required: true, message: "数据库id不能为空", trigger: "change" },
        ],
        tableId: [
          { required: true, message: "表id不能为空", trigger: "change" },
        ],
        dataName: [
          { required: true, message: "数据名称不能为空", trigger: "change" },
        ],
        createTime: [
          { required: true, message: "创建时间不能为空", trigger: "change" },
        ],
        catalogueId: [
          { required: true, message: "请选择目录", trigger: "change" },
        ],
      },
      databaseList: [],
      tableList: [],
      selectedTableList: [],
      columnList: [],
      mountForm: {},
    };
  },
  created() {
    this.getCatalogueList();
    this.getDatabaseList();
    this.getTagList();
    this.getList();
  },
  methods: {
    catalogueCallBack(data) {
      this.queryParams.catalogueId = data.id;
      this.handleQuery();
    },
    /** 查询目录列表 */
    getCatalogueList() {
      listCatalogue({
        pageNum: 1,
        pageSize: 100000,
        catalogueType: "integration",
      }).then((response) => {
        let treeList = [];
        if (response.rows && response.rows.length > 0) {
          response.rows.forEach((p) => {
            treeList.push({
              id: p.id,
              parentId: p.parentId,
              label: p.catalogueName,
              children: [],
            });
          });
        }
        this.treeList = this.handleTree(treeList);
      });
    },
    /** 查询整合数据列表 */
    getList() {
      this.loading = true;
      listData(this.queryParams).then((response) => {
        this.dataList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    getDatabaseList() {
      listDatabase({ status: 1 }).then((response) => {
        this.databaseList = response.rows;
      });
    },
    getTagList() {
      listTag({}).then((response) => {
        this.tagList = response.rows;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.mount = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        catalogueId: null,
        databaseId: null,
        tableId: null,
        dataName: null,
        infoId: null,
        tag: null,
        provideOrganization: null,
        status: null,
        isMetadata: null,
        repetitionField: null,
        remark: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        delFlag: null,
      };
      this.resetForm("form");

      this.mountForm = {
        databaseId: null,
      };
      this.columnList = [];
      this.resetForm("mountForm");
    },
    /** 搜索按钮操作 */
    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;
      this.tableList = [];
      this.selectedTableList = [];
      this.columnList = [];
      getData(id).then((response) => {
        this.form = response.data;
        if (this.form.tag && this.form.tag.length > 0) {
          this.form.tag = this.form.tag.split(",");
        }

        getDataItem(id).then((res) => {
          this.columnList = res.data;
        });

        this.open = true;
        this.title = "修改整合数据";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.tag) {
            this.form.tag = this.form.tag.join(",");
          }
          this.submitting = true;
          if (this.form.id != null) {
            updateData(this.form).then((response) => {
              this.submitting = false;
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addData(this.form).then((response) => {
              this.submitting = false;
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal
        .confirm('是否确认删除整合数据编号为"' + ids + '"的数据项？')
        .then(function () {
          return delData(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "system/integration/data/export",
        {
          ...this.queryParams,
        },
        `data_${new Date().getTime()}.xlsx`
      );
    },
    handleMount() {
      this.tableList = [];
      this.selectedTableList = [];
      this.columnList = [];
      this.mount = true;
    },
    changeDb(e) {
      this.tableList = [];
      this.selectedTableList = [];
      listTable(e).then((response) => {
        this.tableList = response.data;
      });
    },
    changeTb(e) {
      listColumn(e).then((response) => {
        this.columnList = response.data;
      });
    },
    handleSelectionChange(selection) {
      this.selectedTableList = selection;
    },
    submitMountForm() {
      this.$refs["mountForm"].validate((valid) => {
        if (valid) {
          // console.log(this.mountForm.databaseId);
          const param = {
            databaseId: this.mountForm.databaseId,
            tableIds: this.selectedTableList.map((p) => p.id),
          };
          this.submitting = true;
          mountData(param)
            .then((response) => {
              this.submitting = false;
              this.getList();
              this.$modal.msgSuccess("挂载成功");
              this.cancel();
            })
            .catch(() => {
              this.submitting = false;
            });
        }
      });
    },
  },
};
</script>
