<!--  -->
<template>
  <div class="m-container">
    <h2>
      <div class="squrt"></div>
      功能字典
    </h2>
    <div class="m-core">
      <save-form
        :inline="true"
        :model="searchForm"
        @submit="search"
        @reset="onReSet"
      >
        <el-form-item>
          <el-input
            v-model.trim="searchForm.search"
            clearable
            @keyup.enter.native="search"
            placeholder="请输入功能名称"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button native-type="submit" type="primary">搜索</el-button>
          <!-- <el-button native-type="reset" type="danger">重置</el-button> -->
        </el-form-item>
      </save-form>
      <div class="btnList">
        <el-button
          type="primary"
          v-permission="'memberPrivilegesItem/add'"
          @click="createDiction()"
          >添加按钮</el-button
        >
      </div>

      <div class="tableWrap">
        <el-table
          :data="tableList"
          :header-cell-style="{ background: '#EDEEF0', color: '#444' }"
          style="width: 100%; margin-bottom: 20px; margin-top: 40px"
          row-key="id"
          border
          :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
        >
          <el-table-column width="300px" prop="name" label="功能名称">
          </el-table-column>
          <el-table-column prop="id" width="100px" label="功能ID">
          </el-table-column>

          <el-table-column prop="code" width="200px" label="功能标识">
          </el-table-column>
          <el-table-column prop="desc" label="功能描述"> </el-table-column>
          <el-table-column label="操作" width="200px">
            <template slot-scope="scope">
              <el-button
                @click="resetDiction(scope.row)"
                v-permission="'memberPrivilegesItem/update'"
                type="text"
                >修改</el-button
              >
              <el-button
                @click="onDelete(scope.row)"
                v-permission="'memberPrivilegesItem/del'"
                type="text"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>

    <el-dialog
      :title="title"
      :close-on-click-modal="false"
      :visible.sync="branchStatus"
      default-expand-all
      @close="onFormClose('ruleForm')"
      width="500px"
    >
      <el-form :model="form" :rules="rules" ref="ruleForm">
        <el-form-item
          label="功能名称"
          prop="name"
          :label-width="formLabelWidth"
        >
          <el-input v-model.trim="form.name" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item
          label="功能标识"
          prop="code"
          :label-width="formLabelWidth"
        >
          <el-input v-model.trim="form.code" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item
          label="父元素ID"
          prop="parentId"
          :label-width="formLabelWidth"
        >
          <el-cascader
            v-model="form.parentId"
            style="width: 100%"
            :options="cascaderList"
            :props="optionProps"
          ></el-cascader>
        </el-form-item>
        <el-form-item
          label="功能描述"
          :label-width="formLabelWidth"
          prop="desc"
        >
          <el-input
            type="textarea"
            v-model.trim="form.desc"
            autocomplete="off"
            :rows="3"
          ></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="branchStatus = false">取 消</el-button>
        <el-button @click="onBranchSubmit" type="primary">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import axios from "axios";
import { getToken } from "@/utils/auth";
import load from "@/utils/loading";
import { getMemberPrivilegesItem, addMemberPrivilegesItem,resetMemberPrivilegesItem } from "./api";
export default {
  data() {
    return {
      searchForm: {
        search: null,
      },
      branchStatus: false,
      tableList: [],
      optionProps: {
        value: "id",
        label: "name",
        children: "children",
        checkStrictly: true,
      },
      cascaderList: [], // 父级元素
      form: {
        id: null,
        name: null,
        parentId: null,
        code: null,
        desc: null,
      },
      formLabelWidth: "100px",
      title: "",
      rules: {
        name: [{ required: true, message: "请输入功能", trigger: "blur" }],
        desc: [{ required: true, message: "请输入功能描述", trigger: "blur" }],
        code: [{ required: true, message: "请输入功能标识", trigger: "blur" }],
        parentId: [
          { required: true, message: "请输入父元素ID", trigger: "blur" },
        ],
      },
      disctionStatus: "create",
    };
  },
  //生命周期 - 创建完成（可以访问当前this实例）
  created() {},
  //生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {
    // 获取分部

    this.init();
  },
  methods: {
    init() {
      this.getList();
    },
    async getList() {
      try {
        const res = await getMemberPrivilegesItem();
        this.tableList = this.setTableData(res.data);
        this.cascaderList = this.setTableData(res.data);
        this.cascaderList.unshift({
          id: 0,
          name: "根结点",
          children: [],
        });
      } catch (e) {
        console.log(e);
      }
    },
    search() {
      // this.rules.page = 1;
      // this.getList();
    },
    onReSet() {},
    createDiction() {
      this.title = "添加字典";
      this.branchStatus = true;
      this.disctionStatus = "create";
    },
    resetDiction(row) {
      this.title = "修改字典";
      this.disctionStatus = "update";
      this.form = {
        id: row.id,
        name: row.name,
        parentId: row.parentId,
        code: row.code,
        desc: row.desc,
      };
      this.branchStatus = true;
    },
    onDelete(row) {},
    onBranchSubmit() {
      this.$refs["ruleForm"].validate(async (valid) => {
        if (valid) {
          let form = this.form;

          if (this.disctionStatus == "create") {
            try {
              const res = await addMemberPrivilegesItem({
                name: form.name,
                parentId: form.parentId.pop(),
                code: form.code,
                desc: form.desc,
              });
              this.$message.success("添加成功");
              this.getList();
              this.branchStatus = false;
            } catch (e) {
              console.log(e);
            }
          } else if (this.disctionStatus == "update") {
            if (typeof form.parentId === "object") {
              form.parentId = form.parentId.pop();
            }
            try{
              const res = await resetMemberPrivilegesItem(form)
                this.$message.success("修改成功");
              this.getList();
              this.branchStatus = false;
            }catch(e){
              console.log(e)
            }
          }
        } else {
          return false;
        }
      });
    },
    setTableData(result) {
      let list = [];
      list = result.map((res) => {
        let tempList = {};
        tempList = {
          id: res.id,
          name: res.name,
          parentId: res.parentId,
          code: res.code,
          desc: res.desc,
        };
        if (res.memberPrivilegesItems && res.memberPrivilegesItems.length > 0) {
          tempList.children = this.setTableData(res.memberPrivilegesItems);
        }
        return tempList;
      });
      return list;
    },
    onFormClose(formName) {
      // 关闭弹窗重置验证
      this.form = {
        id: null,
        name: null,
        parentId: null,
        code: null,
        desc: null,
      };
      this.$refs[formName].resetFields();
    },
  },
};
</script>
<style lang='scss' scoped>
.btnList {
  margin-bottom: 20px;
}
</style>
