<template>
  <div>
    <el-row>
      <el-col>
        <el-button @click="add()" type="success" style="margin-left: 20px;" size="mini"><i
            class="el-icon-plus"></i>
          新增
        </el-button>
        <div style="text-align: right;float:right;">
          <el-select
              v-model="queryTableName"
              placeholder="表名称"
              style="width:150px;margin-left:20px"
              size="mini">
            <el-option
                v-for="option in tableNameOptions"
                :key="option.value"
                :label="option.label"
                :value="option.value">
            </el-option>
          </el-select>
          <el-select
              v-model="queryVisible"
              placeholder="可见性"
              style="width:150px;margin-left:20px"
              size="mini">
            <el-option
                v-for="option in visibleOptions"
                :key="option.value"
                :label="option.label"
                :value="option.value">
            </el-option>
          </el-select>
          <el-button @click="query" type="primary" size="mini" style="margin-left:20px"><i
              class="el-icon-search"></i> 查询
          </el-button>
          <el-button @click="resetSearch" type="info" size="mini" style="margin-left:20px"><i
              class="el-icon-refresh"></i> 重置
          </el-button>
        </div>
        <myTable :metaData="metadata" :tableData="tableData" :isLoading="isLoading"
                 @selection-change="handleSelectionChange">
          <template #default="{ index }">
            <el-button-group>
              <el-button size="small" icon="fa fa-edit" @click="edit(tableData[index])"></el-button>
              <el-button size="small" icon="fa fa-trash" @click="deleteOne(tableData[index].id)"></el-button>
            </el-button-group>
          </template>
        </myTable>
        <el-pagination
            style="padding: 15px"
            background
            layout="total, prev, pager, next, jumper"
            :total="total"
            :current-page="pageIndex"
            @current-change="onPageChange"
        ></el-pagination>
      </el-col>
    </el-row>
    <el-dialog :title="dialogTitle"
               :visible="dialogVisible"
               width="450px"
               center
               :destroy-on-close="true"
               :show-close="false"
    >
      <div class="dialogForm">
        <el-form :model="form" :label-width="formLabelWidth">
          <el-form-item label="列标签">
            <el-input v-model="form.columnLabel" size="small" autocomplete="off"
                      :style="{width:formInputWidth}"></el-input>
          </el-form-item>
          <el-form-item label="列属性">
            <el-input v-model="form.columnProp" size="small" autocomplete="off"
                      :style="{width:formInputWidth}"></el-input>
          </el-form-item>
          <el-form-item label="列数据类">
            <el-select
                v-model="form.columnType"
                placeholder="请选择"
                :style="{width:formInputWidth}"
                size="mini">
              <el-option
                  v-for="option in columnTypeOptions"
                  :key="option.value"
                  :label="option.label"
                  :value="option.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="表名称">
            <el-input v-model="form.tableName" size="small" autocomplete="off"
                      :style="{width:formInputWidth}"></el-input>
          </el-form-item>
          <el-form-item label="可见性">
            <el-select
                v-model="form.columnVisible"
                placeholder="请选择"
                :style="{width:formInputWidth}"
                size="mini">
              <el-option
                  v-for="option in visibleOptions"
                  :key="option.value"
                  :label="option.label"
                  :value="option.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="列宽度">
            <el-input-number :step="5" v-model="form.columnWidth" size="small" autocomplete="off"
                             :style="{width:formInputWidth}"></el-input-number>
          </el-form-item>
          <el-form-item label="排序">
            <el-input-number :step="1" step-strictly v-model="form.columnIndex" size="small" autocomplete="off"
                             :style="{width:formInputWidth}"></el-input-number>
          </el-form-item>
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
          <el-button size="small" type="success" @click="submit" :loading="saveLoading">保存</el-button>
          <el-button style="margin-left: 10px;" size="small" type="primary" @click="btn_close">关闭</el-button>
    </span>
    </el-dialog>
  </div>
</template>

<script>
import {mapState, mapActions, mapMutations} from 'vuex'
import Vue from 'vue'
import {
  Card,
  Col,
  Button,
  Input,
  InputNumber,
  Checkbox,
  Radio,
  Select,
  Option,
  Pagination,
  Message,
  MessageBox
} from 'element-ui'
import myTable from "../components/CustomTable";
import metaDataApi from "../../js/api/metaDataApi"
import metaDictApi from "../../js/api/metaDictApi";

Vue.use(Card);
Vue.use(Button);
Vue.use(Input);
Vue.use(InputNumber);
Vue.use(Checkbox);
Vue.use(Col);
Vue.use(Radio);
Vue.use(Select);
Vue.use(Option);
Vue.use(Pagination);

export default {
  name: "MetaDataTab",
  components: {
    'myTable': myTable
  },
  data() {
    return {
      modify: false,
      pageIndex: 1,
      queryTableName: "",
      queryVisible: "",
      colNameOptions: [],
      columnTypeOptions: [],
      tableNameOptions: [],
      visibleOptions: [],
      multipleSelection: [],
      dialogVisible: false,
      dialogTitle: "",
      form: {
        columnLabel: "",
        columnProp: "",
        columnWidth: 50,
        columnType: "",
        tableName: "",
        columnVisible: "1",
        columnIndex: 1
      },
      formLabelWidth: "100px",
      formInputWidth: "200px",
      saveLoading: false,
      deleteLoading: false
    }
  },
  methods: {
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    setDataBody() {
      let dataBody = {}
      if (this.queryTableName.length > 0) {
        dataBody.tableName = this.queryTableName;
      }
      if (this.queryVisible.length > 0) {
        dataBody.columnVisible = this.queryVisible;
      }
      return dataBody;
    },
    onPageChange(index) {
      this.pageIndex = index;
      let dataBody = this.setDataBody()
      this.queryPageable({
        index: index - 1,
        size: 10,
        data: dataBody
      });
    },
    add() {
      this.dialogTitle = "添加记录";
      this.saveLoading = false;
      this.dialogVisible = true;
      this.resetFormData();
    },
    edit(data) {
      this.dialogTitle = "修改记录";
      this.form = data;
      this.saveLoading = false;
      this.dialogVisible = true;
    },
    submit() {
      this.saveLoading = true;
      if (this.form.id === undefined) {
        metaDataApi.add(this.form, (response) => {
          if (response.data.code === 200) {
            this.closeDialog();
            Message.success("添加成功")
          } else {
            this.closeDialog();
            Message.error("添加失败")
          }
        })
      } else {
        metaDataApi.update(this.form, (response) => {
          if (response.data.code === 200) {
            this.closeDialog();
            Message.success("更新成功")
          } else {
            this.closeDialog();
            Message.error("更新失败")
          }
        })
      }
    },
    deleteOne(id) {
      MessageBox.confirm("是否删除？", "提示", {
        confirmButtonText: "确认",
        cancelButtonText: "取消",
        type: "warning",
      })
          .then(() => {
            metaDataApi.delete({id: id}, (response) => {
              if (response.data.code === 200) {
                Message.success("删除成功")
                this.refreshPage()
              } else {
                this.refreshPage()
              }
            })
          })
          .catch(() => {
          });
    },
    closeDialog() {
      this.saveLoading = false;
      this.dialogVisible = false;
      this.refreshPage();
    },
    query() {
      this.pageIndex = 1;
      let dataBody = this.setDataBody();
      this.queryPageable({
        index: 0,
        size: 10,
        data: dataBody,
      });
    },
    buildDictTree(data, columnString) {
      let siteOptions = []
      let nodeList = []
      data.forEach(e => {
        if (e.columnName === columnString)
          nodeList.push({
            value: e.dictCode,
            label: e.dictValue,
            children: undefined,
            parentDictCode: e.parentDictCode
          });
      })
      nodeList.forEach(e1 => {
        if (e1.parentDictCode !== undefined) {
          nodeList.forEach(e2 => {
            if (e1.parentDictCode === e2.value) {
              if (e2.children === undefined) {
                e2.children = []
              }
              e2.children.push(e1);
            }
          })
        } else {
          siteOptions.push(e1);
        }
      })
      return siteOptions;
    },
    resetSearch() {
      this.pageIndex = 1;
      this.queryVisible = ""
      this.queryTableName = ""
      this.queryPageable({
        index: 0,
        size: 10,
        data: {},
      });
    },
    resetFormData() {
      this.form = {
        columnLabel: "",
        columnProp: "",
        columnWidth: 50,
        columnType: "",
        tableName: "",
        columnVisible: "1",
        columnIndex: 1
      }
    }
    ,
    btn_close() {
      this.dialogVisible = false;
      this.resetFormData();
    },
    refreshPage() {
      this.saveLoading = false;
      let dataBody = this.setDataBody();
      this.queryPageable({
        index: this.pageIndex - 1,
        size: 10,
        data: dataBody,
      });
    }
    ,
    ...
        mapMutations({}),
    ...
        mapActions({
          queryPageable: 'metadata/queryPageable',
        })
  }
  ,
  computed: {
    metadata: function () {
      const temp = [];
      this.$store.state.metadata.metadata.forEach((element) => {
        if (element.tableName === "meta_data") {
          let tempElement = {...element};
          tempElement.minWidth = tempElement.columnWidth + "%";
          tempElement.columnWidth = 0;
          temp.push(tempElement);
        }
      });
      return temp;
    },
    ...
        mapState({
          tableData: (state) => state.metadata.table,
          total: (state) => state.metadata.count,
          isLoading: (state) => state.metadata.isLoading
        })
  },
  mounted() {
    this.refreshPage();
    metaDictApi.queryByTableName('meta_data', (response) => {
      if (response.data.code === 200) {
        this.columnTypeOptions = this.buildDictTree(response.data.content, 'columnType');
        this.visibleOptions = this.buildDictTree(response.data.content, 'columnVisible');
      }
    })
    metaDataApi.getTableNameList(response => {
      if (response.data.code === 200) {
        const content = response.data.content;
        for (let i = 0; i < content.length; ++i) {
          this.tableNameOptions.push({value: content[i], label: content[i]})
        }
      }
    })
  }
}
</script>

<style scoped>
.height {
  margin-top: 20px;
}

.table {
  margin-top: 20px;
}

.dialogForm {
  display: flex;
  justify-content: center;
}

.demo-form {
  width: 400px;
}

.box-card .text_label {
  text-align: right;
  vertical-align: middle;
  float: left;
  font-size: 14px;
  color: #606266;
  padding: 0 12px 0 0;
  box-sizing: border-box;
  width: 100%;
  line-height: 28px;
}

.box-card {
  background-color: #f8f8f8;
  margin-bottom: 10px;
  padding-bottom: 15px;
}

.box-card .title {
  text-align: center;
  font-size: 18px;
  padding: 10px;
  color: #666;
}

.box-card .dot {
  display: inline-block;
  vertical-align: middle;
  width: 6px;
  height: 6px;
  margin: 0 15px;
  background-color: #0080e5;
}

.el-input__inner {
  height: 28px !important;
  line-height: 28px !important;
}

.card-item {
  height: 41px;
  margin-top: 10px;
}

.el-cascader--mini {
  width: 100%;
}

.logintype_content {
  margin: 5px;
  border: 1px solid rgb(221, 221, 221);
  background-color: rgb(242, 242, 242);
  padding: 10px 10px 0 10px;
}

.el-page-header, .el-page-header__content {
  color: #666 !important;
}

.parse-button-icon {
  text-align: center;
  color: #409EFF;
}

.el-radio {
  margin-top: 5px;
}

.el-button:focus, .el-button:hover {
  margin-right: 0px;
}

.el-pagination {
  display: flex;
  justify-content: center;
}

</style>