<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"
          :class="showSearch ? '' : ' hide'"
          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>
          <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="true"
      width="1400px"
      append-to-body
      v-if="open"
      :close-on-click-modal="false"
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="110px">
        <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="databaseId">
              <el-select
                v-model="form.databaseId"
                placeholder="请选择数据源"
                :disabled="form.id > 0"
                filterable
              >
                <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="tableName">
              <el-input
                v-model="form.tableName"
                placeholder="请输入表名"
                v-if="!form.id"
              />
              <span v-else>{{ form.tableName }}</span>
            </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-row>
        <el-col :span="6" style="margin-top: 5px"><b>数据详情</b></el-col>
        <el-col :span="8" v-if="columnData && columnData.length > 0">
          <el-row>
            <el-col :span="14">
              <el-select
                v-model="validateField"
                placeholder="重复校验"
                multiple
                filterable
                size="mini"
              >
                <el-option
                  :label="c"
                  :value="c"
                  v-for="(c, i) in columns"
                  :key="i"
                ></el-option>
              </el-select>
            </el-col>
            <el-col :span="10">
              <el-button type="primary" size="mini" @click="handleValidate"
                >校验</el-button
              ></el-col
            >
          </el-row>
        </el-col>
        <el-col
          :span="columnData && columnData.length > 0 ? 10 : 18"
          style="display: flex; justify-content: flex-end"
        >
          <!-- <el-button type="primary" size="mini" v-if="!form.id">全量导入</el-button> -->
          <excel-read id="all" btnText="全量导入" @callback="callback" />
          <excel-read
            id="add"
            btnText="增量导入"
            @callback="callback"
            style="margin-left: 10px"
          />
          <!-- <el-button type="primary" size="mini" v-if="!form.id">增量导入</el-button> -->
          <el-button
            type="default"
            v-if="form.id > 0"
            size="mini"
            style="margin-left: 10px; height: 28px"
            @click="handleExport"
            >导出</el-button
          >
        </el-col>
      </el-row>
      <el-table
        :data="columnData"
        max-height="350"
        id="integration-table"
        v-if="columns && columns.length > 0"
      >
        <el-table-column
          :label="col"
          :prop="col"
          v-for="(col, i) in columns"
          :key="i"
        />
        <el-table-column
          label="本次导入"
          width="80"
          align="center"
          prop="isNew"
        >
          <template slot-scope="scope">
            <el-tag size="mini" v-if="scope.row.isNew === 1">是</el-tag>
          </template>
        </el-table-column>
        <el-table-column
          label="校验"
          width="80"
          align="center"
          prop="error"
        >
          <template slot-scope="scope">
            <el-tooltip
              v-if="scope.row.error && scope.row.error.length > 0"
              :content="scope.row.error.join(',')"
              placement="top"
            >
              <el-tag size="mini" type="danger">重复</el-tag>
            </el-tooltip>
            <el-tag v-else type="success" size="mini">正常</el-tag>
          </template>
        </el-table-column>

        <el-table-column
          label="操作"
          width="80"
          align="center"
          prop="error"
        >
          <template slot-scope="scope">
            <el-button
              type="text"
              v-if="scope.row.isNew"
              size="mini"
              @click="handleRemove(scope.row)"
              >移除</el-button
            >
          </template>
        </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>
  </div>
</template>

<script>
import {
  listData,
  getData,
  delData,
  addData,
  updateData,
  getDataData,
} from "@/api/system/metadata/data";
import { listCatalogue } from "@/api/system/integration/catalogue";
import { listDatabase } 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";
import ExcelRead from "@/components/ExcelRead";

import FileSaver from "file-saver";
import * as XLSX from "xlsx";
export default {
  name: "Data",
  dicts: ["sys_provide_organization", "sys_yes_no", "sys_audit_status"],
  components: { CatalogueTree, Treeselect, ExcelRead },
  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: null,
        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" },
        ],
        tableName: [
          { required: true, message: "表名不能为空", trigger: "change" },
        ],
        catalogueId: [
          { required: true, message: "请选择目录", trigger: "change" },
        ],
      },
      databaseList: [],
      tableList: [],
      selectedTableList: [],
      columnList: [], // 持久化后列数据
      mountForm: {},
      validateField: [],
      mode: null, // 导入模式
      columns: [], // 动态列
      columnData: [], // 动态列数据
      fileUrl: null, // 上传文件远程url
    };
  },
  created() {
    this.getCatalogueList();
    this.getDatabaseList();
    this.getTagList();
    this.getList();
  },
  methods: {
    callback(data) {
      // console.log(data);
      if (!data || !data.column || data.column.length === 0) {
        this.$modal.msgError("未读取到EXCEL数据");
        return;
      }

      if (data.column.find((p) => p === "id")) {
        this.$modal.msgError("Excel标题不能包含id关键字");
        return;
      }

      data.column.unshift("id");

      // 如果是编辑，则校验格式是否一致
      if (this.form.id > 0) {
        if (!this.compareArray(data.column, this.columns)) {
          this.$modal.msgError("导入的数据格式与原有格式不一致");
          return;
        }
      }
      this.mode = data.id;
      this.columns = data.column;
      let maxId = 0;
      if (this.columnData && this.columnData.length > 0) {
        maxId = Math.max.apply(
          null,
          this.columnData.map((i) => i.id)
        );
      }

      data.data.forEach((p, i) => {
        p.id = maxId + i + 1;
        p.isNew = 1;
        p.error = null;
      });
      console.log(this.mode);
      if (this.mode === "all") {
        this.columnData = data.data;
      } else {
        this.columnData = data.data.concat(this.columnData);
      }

      this.fileUrl = data.url;
      this.handleValidate();
    },
    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 , cacheFlag: 'Y' }).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,
        repetitionField: null,
        remark: null,
      };
      this.resetForm("form");

      this.columns = [];
      this.columnData = [];
      this.validateField = [];
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加元数据";
    },
    handleRemove(row) {
      // console.log(row);
      this.columnData = this.columnData.filter((p) => p.id !== row.id);
      this.handleValidate();
    },
    /** 修改按钮操作 */
    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(",");
        }

        if (this.form.repetitionField && this.form.repetitionField.length > 0) {
          this.validateField = this.form.repetitionField.split(",");
        }

        if (this.form.dataItems && this.form.dataItems.length > 0) {
          this.columns = this.form.dataItems.map((p) => p.columnName);
        }

        getDataData(id, 1, 100000).then((res) => {
          // this.columnList = res.data;
          // console.log(res)
          this.columnData = res.data.list;
        });

        this.open = true;
        this.title = "修改元数据";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.handleValidate();
      this.$refs["form"].validate((valid) => {
        if (valid) {
          const form = JSON.parse(JSON.stringify(this.form));
          if (form.tag) {
            form.tag = form.tag.join(",");
          }
          if (this.validateField !== null && this.validateField.length > 0) {
            form.repetitionField = this.validateField.join(","); // 验重字段
          }

          if (!this.columnData || this.columnData.length === 0) {
            this.$modal.msgError("请导入数据");
            return;
          }

          let validateFlag = true;
          for (let i = 0; i < this.columnData.length; i++) {
            const p = this.columnData[i];
            if (p.error && p.error.length > 0) {
              validateFlag = false;
            }
          }

          if (!validateFlag) {
            this.$modal.msgError("本次导入数据校验未通过，请处理数据");
            return;
          }

          const addedData = this.columnData.filter((k) => k.isNew);
          if (!addedData || addedData.length === 0) {
            this.$modal.msgError("本次未导入数据");
            return;
          }

          addedData.forEach((p) => {
            p = JSON.stringify(p).replace(
              /(['"])?(\d{4})-(\d{1,2})-(\d{1,2})?\s*,/g,
              '"$2-$3-$4",'
            );
          });

          form.data = JSON.parse(JSON.stringify(addedData)); // 本次导入的数据
          if (form.data && form.data.length > 0) {
            form.data.forEach((p) => {
              delete p.error;
              delete p.isNew;
              delete p.id;
            });
          }
          form.column = this.columns; // 本次导入的列
          form.mode = this.mode; // 导入模式

          console.log(form);
          this.submitting = true;
          if (form.id != null) {
            updateData(form).then((response) => {
              this.submitting = false;
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            }).catch(() => {
              this.submitting = false;
            });
          } else {
            addData(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 delData(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      // console.log(XLSX);
      /* 从表生成工作簿对象 */
      let wb;
      let fix = document.querySelector(".el-table__fixed");
      if (fix) {
        wb = XLSX.utils.table_to_book(
          document.querySelector("#table").removeChild(fix)
        );
        document.querySelector("#table").appendChild(fix);
      } else {
        wb = XLSX.utils.table_to_book(
          document.querySelector("#integration-table")
        );
      }

      // console.log(wb);
      /* 获取二进制字符串作为输出 */
      var wbout = XLSX.write(wb, {
        bookType: "xlsx",
        bookSST: true,
        type: "array",
      });
      console.log(wbout);
      try {
        // Blob 对象表示一个不可变、原始数据的类文件对象。
        // Blob 表示的不一定是JavaScript原生格式的数据。
        // File 接口基于Blob，继承了 blob 的功能并将其扩展使其支持用户系统上的文件。
        // 返回一个新创建的 Blob 对象，其内容由参数中给定的数组串联组成。
        FileSaver.saveAs(
          new Blob([wbout], { type: "application/octet-stream" }),
          // 设置导出文件名称
          this.form.dataName + ".xlsx"
        );
      } catch (e) {
        if (typeof console !== "undefined") console.log(e, wbout);
      }
      return wbout;
    },
    handleValidate() {
      if (!this.validateField || this.validateField.length === 0) {
        // this.$modal.msgError("请选择验重字段");
        return;
      }

      this.columnData.forEach((o) => {
        o.error = [];
      });

      // 找到验重字段数据
      this.columnData.forEach((o) => {
        this.validateRow(o);
      });

      this.columnData = JSON.parse(JSON.stringify(this.columnData));
      // this.$modal.msgSuccess("校验完成");
    },
    validateRow(row) {
      this.validateField.forEach((colName) => {
        const v = row[colName];

        // 其他是否包含这个值
        const repeat = this.columnData.filter(
          (k) => k.id !== row.id && k[colName] === v
        );

        if (repeat && repeat.length > 0) {
          if (!row.error) {
            row.error = [];
          }

          row.error.push(`${colName}与id=${repeat.map((j) => j.id)}的值重复`);
        }
      });
    },
  },
};
</script>
