<template>
  <el-card>
    <div class="menu">
      <el-card class="treeData">
        <div>
          <el-input placeholder="输入关键字进行过滤" v-model="filterText">
          </el-input>
          <el-tree
            class="tree"
            :data="treeList"
            :accordion="true"
            :expand-on-click-node="false"
            :props="defaultProps"
            :filter-node-method="filterNode"
            @node-click="checkClick"
            ref="tree"
          >
          </el-tree>
        </div>
      </el-card>
      <el-card class="newData">
        <el-card class="buttonCard">
          <div v-if="firstMenu">
            <el-button type="primary" @click="addMenu(0)"
              >添加一级菜单</el-button
            >
            <el-button
              type="warning"
              icon="el-icon-refresh-right"
              @click="refresh"
              >刷新</el-button
            >
          </div>
          <div v-else>
            <el-button type="danger" @click="delMenu">删除此菜单</el-button>
            <el-button type="primary" @click="addMenu(1)">添加子菜单</el-button>
            <el-button
              type="warning"
              icon="el-icon-refresh-right"
              @click="refresh"
              >刷新</el-button
            >
          </div>
        </el-card>
        <div class="contentCard">
          <el-form
            class="form"
            ref="form"
            :model="form"
            label-width="100px"
            :disabled="formDisabled"
            
          >
            <el-form-item label="菜单名称：">
              <el-input v-model="form.menuName"></el-input>
            </el-form-item>
            <el-form-item label="菜单路径：">
              <el-input v-model="form.menuUrl"></el-input>
            </el-form-item>
            <el-form-item label="排列序号：">
              <el-input v-model="form.sequence"></el-input>
            </el-form-item>
          </el-form>
          <div class="submit">
            <el-button type="primary" :disabled="formDisabled" @click="putMenu">提交</el-button>
          </div>
        </div>
      </el-card>
      <el-dialog
        title="添加菜单"
        :visible.sync="dialogVisible"
        width="40%"
        :before-close="handleClose"
        :close-on-click-modal="false"
      >
        <el-form class="form" ref="form1" :model="form1" label-width="100px">
          <el-form-item label="菜单名称：">
            <el-input v-model="form1.menuName"></el-input>
          </el-form-item>
          <el-form-item label="菜单路径：">
            <el-input v-model="form1.menuUrl"></el-input>
          </el-form-item>
          <el-form-item label="排列序号：">
            <el-input v-model="form1.sequence"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="handleClose">取 消</el-button>
          <el-button type="primary" @click="createMenu">确 定</el-button>
        </span>
      </el-dialog>
    </div>
  </el-card>
</template>

<script>
import { listAllSimple, createMenu, deleteMenu, updateMenu } from "@/api/menu";
import { listMenus } from "@/api/login";
import { getToken,setMenuList } from "@/utils/auth.js";
export default {
  data() {
    return {
      filterText: "",
      treeList: [],
      defaultProps: {
        children: "children",
        label: "menuName",
      },
      firstMenu: true,
      form: {
        parentId: null,
        menuName: "",
        menuUrl: "",
        sequence: "",
      },
      form1: {
        parentId: null,
        menuName: "",
        menuUrl: "",
        sequence: "",
      },
      dialogVisible: false,
      formDisabled: true,
    };
  },
  watch: {
    filterText(val) {
      this.$refs.tree.filter(val);
    },
  },
  methods: {
    filterNode(value, data) {
      if (!value) return true;
      return data.menuName.indexOf(value) !== -1;
    },
    init() {
      listAllSimple().then((res) => {
        if (res.code == 200) {
          this.initTree(res.data);
        }
      });
    },
    initTree(list) {
      let map = {};
      this.treeList = [];
      list.forEach((item) => {
        item.children = [];
        map[item.id] = item;
      });
      list.forEach((item) => {
        const obj = map[item.parentId];
        if (obj) {
          obj.children.push(item);
        } else {
          this.treeList.push(item);
        }
      });
      this.treeList.sort((x,z)=> Number(x.sequence)-Number(z.sequence) )
    },
    addMenu(type) {
      if (type == 0) {
        this.form1.parentId = 0;
      }
      this.dialogVisible = true;
    },
    handleClose() {
      this.dialogVisible = false;
      this.form1 = {};
    },
    checkClick(obj) {
      this.form = obj;
      this.formDisabled = false;
      this.firstMenu = false;
      this.form1.parentId = obj.id;
    },
    refresh() {
      this.firstMenu = true;
      this.formDisabled = true;
      this.form = {};
      this.form1 = {};
    },
    createMenu() {
      if (!this.form1.menuName && !this.form1.menuUrl && !this.form1.sequence ) {
        this.$message({
            type: "warning",
            message: '请填写完整表单',
        });
        return
      }
      let params = {
        parentId: this.form1.parentId,
        menuName: this.form1.menuName,
        menuUrl: this.form1.menuUrl,
        sequence: this.form1.sequence,
      };
      createMenu(params).then((res) => {
        if (res.code == 200) {
          this.$message({
            type: "success",
            message: "创建成功!",
          });
          this.dialogVisible = false;
          this.refresh();
          this.init();
        }
      });
    },
    putMenu() {
      console.log(this.form)
      updateMenu(this.form).then((res) => {
        console.log(res.data+'menu');
        if (res.code == 200) {
          this.$message({
            type: "success",
            message: "修改成功!",
          });
          this.dialogVisible = false;
          this.refresh();
          this.init();
        }
      })
    },
    delMenu() {
      this.$confirm("此操作将永久删除该菜单, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          deleteMenu({ id: this.form1.parentId }).then((res) => {
            if (res.success == true) {
              listMenus({ tokenValue: getToken() }).then((res) => {
                if (res.success == true) {
                    setMenuList(JSON.stringify(res.data));
                    location.reload();
                }
              })
              // this.$message({
              //   type: "success",
              //   message: "删除成功!",
              // });
              // this.refresh();
              // this.init();
            } else {
                this.$message({
                    type: "warning",
                    message: res.msg || '删除失败，请联系管理员',
                }); 
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
  },
  created() {
    this.init();
  },
};
</script>

<style lang="stylus" scoped>
.menu {
  width: 100%;
  height: calc(100vh - 150px);
  display: flex;
  align-items: flex-start;
  justify-content: space-between;

  .treeData {
    width: 20%;
    height: 100%;
    overflow: auto;

    .tree {
      margin-top: 10px;
    }
  }

  .newData {
    width: 78%;
    height: 100%;
    overflow: auto;

    .buttonCard {
      display: flex;
      justify-content: flex-end;
    }

    .contentCard {
      width: 100%;
      margin-top: 10px;
      display: flex;
      flex-direction: column;
      justify-content: center;

      .submit {
        width: 100%;
        display: flex;
        justify-content: center;
      }
    }
  }
}
</style>