<script src="../../../api/tool/table.js"></script>
<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="表名" prop="tableName">
        <el-input
          v-model="queryParams.tableName"
          placeholder="请输入表名"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="创建时间">
        <el-date-picker
          v-model="daterangeCreateTime"
          size="small"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="更新时间">
        <el-date-picker
          v-model="daterangeUpdateTime"
          size="small"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </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="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['tool:table:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['tool:table:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-upload"
          size="mini"
          @click="openImportTable"
        >导入</el-button>
    </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['tool:table:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="tableList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" type="index" align="center">
        <template slot-scope="scope">
            <span>{{ ((queryParams.pageInfo.pageNum - 1) * queryParams.pageInfo.pageSize + scope.$index + 1)}}</span>
        </template>
      </el-table-column>
      <el-table-column label="表名" align="center" prop="tableName" />
      <el-table-column label="表描述" align="center" prop="tableComment" />
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{m}:{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}:{m}:{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="['tool:table:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['tool:table:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

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

    <!-- 添加或修改top万能查询主对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="1200px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="8">
            <el-form-item label="表名:" prop="tableName">
              <span>{{form.tableName}}</span>
            </el-form-item>
            <el-form-item label="角色">
              <el-select v-model="form.roleIds" multiple placeholder="请选择">
                <el-option
                  v-for="item in roleOptions"
                  :key="item.roleId"
                  :label="item.roleName"
                  :value="item.roleId"
                  :disabled="item.status == 1"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="表描述" prop="tableComment">
              <el-input v-model="form.tableComment" type="textarea" placeholder="请输入内容" />
            </el-form-item>
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
            </el-form-item>
          </el-col>
          <el-col :span="16">
            <el-row :gutter="10" class="mb8">
              <el-col :span="1.5">
                <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAddTopSearchColumn">添加</el-button>
              </el-col>
              <el-col :span="1.5">
                <el-button type="danger" icon="el-icon-delete" size="mini" @click="handleDeleteTopSearchColumn">删除</el-button>
              </el-col>
            </el-row>
            <el-table :data="relationalMapList" :row-class-name="rowRelationalMapIndex" @selection-change="handleRelationalMapSelectionChange" ref="relationalMap">
              <el-table-column type="selection" width="50" align="center" prop="index" />
              <el-table-column label="序号" align="center" prop="index" width="50"/>
              <el-table-column label="外键" prop="mainKey">
                <template slot-scope="scope">
                  <el-select v-model="scope.row.mainKey" placeholder="外键">
                    <el-option
                      v-for="item in topSearchColumnList"
                      :key="item.id"
                      :label="item.columnName+':'+item.columnComment"
                      :value="item.columnName">
                    </el-option>
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column label="关联表" prop="childId">
                <template slot-scope="scope">
                  <el-select v-model="scope.row.childId" @change="changeChildList(scope.row.childId,scope.$index)" placeholder="关联表">
                    <el-option
                      v-for="(item,index) in tableInfoList"
                      :key="index"
                      :label="item.tableName+':'+item.tableComment"
                      :value="item.id">
                    </el-option>
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column label="关联字段" prop="childKey">
                <template slot-scope="scope">
                  <el-select v-model="scope.row.childKey" placeholder="关联表">
                    <el-option
                      v-for="(item,index) in scope.row.childListColumn"
                      :key="index"
                      :label="item.columnName+':'+item.columnComment"
                      :value="item.columnName">
                    </el-option>
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column label="关联方式" prop="types">
                <template slot-scope="scope">
                  <el-select v-model="scope.row.types" multiple  placeholder="关联方式">
                    <el-option label="hasOne" :value="1"/>
                    <el-option label="hasMany" :value="2"/>
                    <el-option label="belongsTo" :value="3"/>
                  </el-select>
                </template>
              </el-table-column>
            </el-table>
          </el-col>
        </el-row>
        <el-divider content-position="center">ER可视化查询字段信息</el-divider>
        <el-row :gutter="10" class="mb8">
<!--          <el-col :span="1.5">-->
<!--            <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAddTopSearchColumn">添加</el-button>-->
<!--          </el-col>-->
<!--          <el-col :span="1.5">-->
<!--            <el-button type="danger" icon="el-icon-delete" size="mini" @click="handleDeleteTopSearchColumn">删除</el-button>-->
<!--          </el-col>-->
        </el-row>
        <el-table :data="topSearchColumnList" :row-class-name="rowTopSearchColumnIndex" ref="topSearchColumn">
          <el-table-column label="序号" align="center" prop="index" width="50"/>
          <el-table-column label="列名称" prop="columnName">
            <template slot-scope="scope">
              <span>{{scope.row.columnName}}</span>
            </template>
          </el-table-column>
          <el-table-column label="列描述" prop="columnComment">
            <template slot-scope="scope">
              <el-input v-model="scope.row.columnComment" placeholder="请输入列描述" />
            </template>
          </el-table-column>
          <el-table-column label="列类型" prop="columnType">
            <template slot-scope="scope">
              <span>{{scope.row.columnType}}</span>
            </template>
          </el-table-column>
          <el-table-column label="是否使用" prop="isUse" align="center">
            <template slot-scope="scope">
              <el-checkbox :false-label="0" :true-label="1" v-model="scope.row.isUse"/>
            </template>
          </el-table-column>
          <el-table-column label="创建时间" prop="createTime">
            <template slot-scope="scope">
              <span>{{scope.row.createTime}}</span>
            </template>
          </el-table-column>
<!--          <el-table-column label="更新时间" prop="updateTime">-->
<!--            <template slot-scope="scope">-->
<!--              <span>{{scope.row.updateTime}}</span>-->
<!--            </template>-->
<!--          </el-table-column>-->
        </el-table>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <import-top-table ref="import" @ok="handleQuery" />

  </div>
</template>

<script>
import { listTable,columns, getTable, delTable, addTable, updateTable, exportTable, listInfoTable } from "@/api/tool/table";
import {listRole} from '../../../api/system/role'
import importTopTable from "./importTopTable";
export default {
  name: "Table",
  components: { importTopTable },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 子表选中数据
      checkedRelationalMapList: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // top万能查询主表格数据
      tableList: [],
      // 角色选项
      roleOptions: [],
      // top万能查询字段表格数据
      topSearchColumnList: [],
      relationalMapList: [],
      tableInfoList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 创建时间时间范围
      daterangeCreateTime: [],
      // 更新时间时间范围
      daterangeUpdateTime: [],
      // 查询参数
      queryParams: {
          pageInfo:{
              pageNum: 1,
              pageSize: 10,
          },
        params:{},
        tableName: null,
        tableComment: null,
      },
      // 表单参数
      form: {
      },
      // 表单校验
      rules: {
      }
    };
  },
  created() {
    this.getList();
    this.getRoleList();
  },
  methods: {
    getRoleList(){
      listRole().then(res=>{
        this.roleOptions = res.rows
      })
    },

    /** 查询top万能查询主列表 */
    getList() {
        this.loading = true;
        this.queryParams.params={}
        if (null != this.daterangeCreateTime && '' != this.daterangeCreateTime) {
            this.queryParams.params["beginCreateTime"] = this.daterangeCreateTime[0];
            this.queryParams.params["endCreateTime"] = this.daterangeCreateTime[1];
        }
        this.queryParams.params={}
        if (null != this.daterangeUpdateTime && '' != this.daterangeUpdateTime) {
            this.queryParams.params["beginUpdateTime"] = this.daterangeUpdateTime[0];
            this.queryParams.params["endUpdateTime"] = this.daterangeUpdateTime[1];
        }
        listTable(this.queryParams).then(response => {
            this.tableList = response.rows;
            if(response.total!==undefined){
              this.total = response.total;
            }
            this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        tableName: null,
        tableComment: null,
        remark: null,
        roleIds:[],
      };
      this.topSearchColumnList = [];
      this.relationalMapList = [];
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 打开导入表弹窗 */
    openImportTable() {
      this.$refs.import.show();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.daterangeCreateTime = [];
      this.queryParams.params={}
      this.daterangeUpdateTime = [];
      this.queryParams.params={}
      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
      listInfoTable().then( res=>{
        this.tableInfoList = res.rows
      })
      getTable(id).then(response => {
        this.form = response.data;
        this.topSearchColumnList = response.data.topSearchColumnList;
        let relList = response.data.relationalMapList;
        for (let i = 0; i < relList.length; i++) {
          let item = {
            mainId:relList[i].mainId,
            childId:relList[i].childId,
            mainKey:relList[i].mainKey,
            childKey:relList[i].childKey,
            type:relList[i].type,
            types:[],
          }
          let list = relList[i].type.split(",");
          for (const listKey in list) {
            item.types.push(parseInt(list[listKey]))
          }
          this.relationalMapList.push(item)
        }
        this.open = true;
        this.title = "修改拓扑数据";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.form.topSearchColumnList = this.topSearchColumnList;
          for (let i = 0; i < this.relationalMapList.length; i++) {
            this.relationalMapList[i].type = ""
            for (let j = 0; j < this.relationalMapList[i].types.length; j++) {
              if (j===this.relationalMapList[i].types.length-1){
                this.relationalMapList[i].type+=this.relationalMapList[i].types[j]
              }else {
                this.relationalMapList[i].type+=(this.relationalMapList[i].types[j]+',')
              }
            }
          }
          this.form.relationalMapList = this.relationalMapList;
          this.form.relationalMapList = this.relationalMapList
          if (this.form.id != null) {
            updateTable(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addTable(this.form).then(response => {
              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 delTable(ids);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        })
    },
	/** top万能查询字段序号 */
    rowTopSearchColumnIndex({ row, rowIndex }) {
      row.index = rowIndex + 1;
    },
	/** top万能查询字段序号 */
    rowRelationalMapIndex({ row, rowIndex }) {
      row.index = rowIndex + 1;
    },
    /** top万能查询字段添加按钮操作 */
    handleAddTopSearchColumn() {
      let obj = {
        mainId : this.form.id,
        childId : null,
        mainKey : null,
        childKey : null,
        type : null,
        types : [],
        childListColumn:[],
      };
      this.relationalMapList.push(obj);
    },
    /** top万能查询字段删除按钮操作 */
    handleDeleteTopSearchColumn() {
      if (this.checkedRelationalMapList.length == 0) {
        this.$alert("请先选择要删除的拓扑数据字段数据", "提示", { confirmButtonText: "确定", });
      } else {
        this.relationalMapList.splice(this.checkedRelationalMapList[0].index - 1, 1);
      }
    },
    changeChildList(id,index){
      //todo 获取到该表字段信息
      columns(id).then(res=>{
        this.relationalMapList[index].childListColumn = res.data
      })
    },
    /** 单选框选中数据 */
    handleRelationalMapSelectionChange(selection) {
      if (selection.length > 1) {
        this.$refs.relationalMap.clearSelection();
        this.$refs.relationalMap.toggleRowSelection(selection.pop());
      } else {
        this.checkedRelationalMapList = selection;
      }
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有拓扑数据主数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return exportTable(queryParams);
        }).then(response => {
          this.download(response.msg);
        })
    }
  }
};
</script>
