<template>
  <div class="app-container">
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
        >
          新增
        </el-button>
      </el-col>
    </el-row>

    <el-table
      v-if="refreshTable"
      v-loading="loading"
      :data="dataList"
      row-key="id"
      :default-expand-all="isExpandAll"
      :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
    >
      <el-table-column prop="name" label="领域名称"></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)"
            >修改</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            >删除</el-button
          >
          <el-button
            v-if="scope.row.level < 3"
            size="mini"
            type="text"
            icon="el-icon-plus"
            @click="handleAdd(scope.row)"
            >新增子领域</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加或修改领域对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="680px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="上级领域" prop="parent_id">
          <treeselect
            v-model="form.parent_id"
            :options="menuOptions"
            :normalizer="normalizer"
            :show-count="true"
            placeholder="选择上级领域"
          />
        </el-form-item>
        <el-form-item label="领域名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入领域名称" />
        </el-form-item>
      </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>
  </div>
</template>

<script>
import {
  industryList,
  industryAdd,
  industryEdit,
  industryDelete,
} from "@/api/platform/industry";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";

export default {
  components: { Treeselect },
  data() {
    return {
      is_super: this.$store.getters.is_super,
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      // 领域表格树数据
      dataList: [],
      // 领域树选项
      menuOptions: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否展开，默认全部折叠
      isExpandAll: false,
      // 重新渲染表格状态
      refreshTable: true,
      // 查询参数
      queryParams: {
        name: undefined,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        name: [
          { required: true, message: "领域名称不能为空", trigger: "blur" },
        ],
      },
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询领域列表 */
    getList() {
      this.loading = true;
      industryList(this.queryParams).then((response) => {
        this.setTreeLevel(response.data);
        this.getTreeselect(response.data);
        this.dataList = response.data;
        this.loading = false;
      });
    },
    setTreeLevel(node, index = 1) {
      node.forEach((item) => {
        item["level"] = index;
        if (item.children && item.children.length) {
          item.children = this.setTreeLevel(item.children, index + 1);
        }
      });
      return node;
    },
    /** 转换领域数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.id,
        label: node.name,
        children: node.children,
      };
    },
    /** 查询领域下拉树结构 */
    getTreeselect(options) {
      const data = this.setThreeLevelTree(options);
      this.menuOptions = [];
      const menu = { id: "", name: "主类目", level: 0, children: [] };
      menu.children = data;
      this.menuOptions.push(menu);
    },
    setThreeLevelTree(node) {
      return node.map((item) => {
        const result = { ...item };
        if (item.children && item.children.length && item.level < 2) {
          result.children = this.setThreeLevelTree(item.children);
        } else {
          delete result.children;
        }
        return result;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        parent_id: undefined,
        name: undefined,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.getList();
    },
    /** 新增按钮操作 */
    handleAdd(row) {
      this.reset();
      if (row != null && row.parent_id != undefined && row.id !== undefined) {
        this.form.parent_id = row.id;
      } else {
        this.form.parent_id = "";
      }
      this.open = true;
      this.title = "添加领域";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.form = Object.assign({}, row);
      this.open = true;
      this.title = "修改领域";
    },
    /** 提交按钮 */
    submitForm: function () {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.id) {
            industryEdit(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            industryAdd(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      this.$modal
        .confirm('是否确认删除名称为"' + row.name + '"的数据项？')
        .then(function () {
          return industryDelete(row);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
  },
};
</script>
