<template>
  <div>
    <div style="margin-bottom: 20px">
      <el-button
        type="primary"
        class="lake-Blue"
        icon="el-icon-plus"
        @click="handleAddOrEdit('menu', null, 'create')"
        >新增</el-button
      >
    </div>

    <el-table
      v-loading="listLoading"
      :data="menuData"
      row-key="id"
      :expand-row-keys="defaultKeys"
      :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
      @expand-change="rowClick"
    >
      <template slot="empty">
        <img src="@/assets/nopage.png" alt />
        <p>暂无数据</p> </template
      ><el-table-column prop="remark" label="名称"></el-table-column>
      <el-table-column prop="icon" label="图标">
        <template slot-scope="scope"
          ><svg-icon
            v-if="scope.row.icon && scope.row.icon.substr(0, 3) !== 'el-'"
            :iconClass="
              scope.row.menuType === 'FUNCTION' ? 'fun_url' : scope.row.icon
            "
            class="icon"
            style="margin-right: 10px"
          ></svg-icon
          ><i
            v-if="scope.row.icon && scope.row.icon.substr(0, 3) === 'el-'"
            :class="scope.row.icon"
            style="margin-right: 10px"
          ></i>
        </template>
      </el-table-column>
      <el-table-column prop="id" label="编码"></el-table-column>
      <el-table-column prop="sort" label="排序"></el-table-column>
      <el-table-column fixed="right" label="操作" width="300">
        <template slot-scope="scope">
          <el-button
            v-if="
              scope.row.menuType == 'MENU' &&
              (!scope.row.children || scope.row.children[0].menuType == 'MENU')
            "
            @click.native="append('menu', scope.row)"
            style="color: #67c23a"
            type="text"
            icon="el-icon-plus"
            >新增菜单</el-button
          >
          <el-button
            v-if="
              scope.row.menuType == 'MENU' &&
              (!scope.row.children ||
                scope.row.children[0].menuType == 'BUTTON')
            "
            @click.native="append('button', scope.row)"
            style="color: #67c23a"
            type="text"
            icon="el-icon-plus"
            >新增按钮</el-button
          >
          <el-button
            v-if="scope.row.menuType == 'MENU'"
            @click.native="update('menu', scope.row)"
            style="color: #52c8cc"
            type="text"
            icon="el-icon-edit"
            >编辑</el-button
          >
          <el-button
            v-if="scope.row.menuType == 'MENU'"
            @click.native="remove('menu', scope.row)"
            style="color: rgb(245, 108, 108)"
            type="text"
            icon="el-icon-delete"
            >删除</el-button
          >

          <el-button
            v-if="scope.row.menuType == 'BUTTON'"
            @click.native="update('button', scope.row)"
            style="color: #52c8cc"
            type="text"
            icon="el-icon-edit"
            >编辑</el-button
          >
          <el-button
            v-if="scope.row.menuType == 'BUTTON'"
            @click.native="remove('button', scope.row)"
            style="color: rgb(245, 108, 108)"
            type="text"
            icon="el-icon-delete"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <!--添加/修改菜单-->
    <el-dialog
      :title="textMap[dialogStatus]"
      :visible.sync="dialogFormVisible"
      width="420px"
      :close-on-click-modal="false"
    >
      <el-form
        ref="dataForm"
        :model="temp"
        label-width="90px"
        style="width: 370px; margin-left: 10px"
        :rules="rules"
      >
        <el-form-item label="菜单编码" v-if="statue == 'menu'" prop="menuId">
          <el-input v-model.trim="temp.menuId" />
        </el-form-item>
        <el-form-item label="菜单名称" v-if="statue == 'menu'" prop="menuName">
          <el-input v-model.trim="temp.menuName" />
        </el-form-item>
        <el-form-item label="按钮编码" v-if="statue == 'button'" prop="oprtId">
          <el-input v-model.trim="temp.oprtId" />
        </el-form-item>
        <el-form-item
          label="按钮名称"
          v-if="statue == 'button'"
          prop="oprtName"
        >
          <el-input v-model.trim="temp.oprtName" />
        </el-form-item>
        <el-form-item label="排序" v-if="statue == 'menu'">
          <el-input-number
            v-model="temp.sort"
            controls-position="right"
            :min="1"
            :max="99"
          ></el-input-number>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="commitTreeData">确认</el-button>
      </div>
    </el-dialog>
  </div>
</template>


<script>
import { getFunData, setFun, setButton } from "@/api/system/function";
import { functionObj } from "@/utils/functionObj";
export default {
  props: {
    defaultMenu: {
      //默认选中菜单
      type: Array,
      default: []
    }
  },
  watch: {},
  data() {
    return {
      // 菜单还是按钮
      statue: "",
      listLoading: false,
      defaultKeys: [], //tree默认展开
      menuData: [], //菜单tree
      dialogFormVisible: false, //是否对话框
      dialogStatus: "",
      textMap: {
        update: "编辑",
        create: "添加"
      },
      temp: {}, //菜单表单提交
      rules: {
        menuId: [
          { required: true, message: "请输入菜单编码", trigger: "blur" }
        ],
        menuName: [
          { required: true, message: "请输入菜单名称", trigger: "blur" }
        ],
        oprtId: [
          { required: true, message: "请输入按钮编码", trigger: "blur" }
        ],
        oprtName: [
          { required: true, message: "请输入按钮名称", trigger: "blur" }
        ]
      }
    };
  },
  created() {
    // 菜单管理页面
    this.getMenuData();
  },
  mounted() {},
  methods: {
    rowClick(row, event, column) {
      Array.prototype.remove = function (val) {
        let index = this.indexOf(val);
        if (index > -1) {
          this.splice(index, 1);
        }
      };

      if (this.defaultKeys.indexOf(row.id) < 0) {
        this.defaultKeys.push(row.id);
      } else {
        this.defaultKeys.remove(row.id);
      }
    },

    sortIndex(a, b) {
      return a.sort - b.sort;
    },

    getNewMenuData(datas) {
      let data = [];
      if (datas) {
        datas.forEach((item1) => {
          functionObj.forEach((item2) => {
            if (
              item1.menuId == item2.id &&
              item2.menuType.toLowerCase() == "menu"
            ) {
              item1 = {
                idd: item1.id,
                parentId: item1.parentId,
                sort: item1.sort,
                remark: item1.menuName,
                id: item2.id,
                component: item2.component,
                icon: item2.icon,
                menuType: item2.menuType,
                name: item2.name,
                redirect: item2.redirect,
                router: item2.router,
                hidden: item2.hidden
              };
              data.push(item1);
            }
            if (
              item1.menuId == item2.id &&
              item2.menuType.toLowerCase() == "button"
            ) {
              item1 = {
                idd: item1.id,
                id: item2.id,
                menuType: item2.menuType,
                remark: item1.menuName,
                parentId: item1.parentId,
                sort: item1.sort
              };
              data.push(item1);
            }
          });
        });
      }
      data.sort(this.sortIndex);
      if (data && data.length > 0) {
        for (let i = 0; i < this.defaultMenu.length; i++) {
          this.defaultKeys.push(this.defaultMenu[i].menuId);
        }
        let resultDate = [];
        this.setMenuDate(resultDate, data, 0);
        this.menuData = resultDate;
      }
      this.listLoading = false;
    },

    // 获取菜单列表
    getMenuData() {
      this.listLoading = true;
      // this.defaultKeys = [];
      this.menuData = [];
      //获取菜单
      getFunData().then((response) => {
        let datas = response.data;
        this.getNewMenuData(datas);
      });
    },

    setMenuDate(resultDate, data, index) {
      //获取接口数据生成tree数据
      if (data.length == 0) {
        return;
      }
      if (index == 0) {
        for (let i = 0; i < data.length; i++) {
          if (data[i].parentId == 0) {
            resultDate.push(data[i]);
            data.splice(i, 1);
            i--;
          }
        }
      }
      for (let i = 0; i < data.length; i++) {
        for (let j = 0; j < resultDate.length; j++) {
          if (data.length > 0 && resultDate[j].id == data[i].parentId) {
            if (!resultDate[j].hasOwnProperty("children")) {
              resultDate[j].children = [];
            }

            if (resultDate[j].children.length > 0) {
              find = resultDate[j].children.filter(function (key) {
                return key.id === data[i].id;
              });
            }
            let find = resultDate[j].children.filter((item) => {
              return item.id == data[i].id;
            });
            if (find.length == 0) resultDate[j].children.push(data[i]);
            // data.splice(i, 1)
            // i--
          }
          if (resultDate[j].hasOwnProperty("children")) {
            this.setMenuDate(resultDate[j].children, data, 1, i);
          }
        }
      }
      return resultDate;
    },

    // 添加菜单
    append(statue, data) {
      //修改对话框
      this.handleAddOrEdit(statue, data, "create");
    },

    // 修改菜单
    update(statue, data) {
      this.handleAddOrEdit(statue, data, "update");
    },

    // 删除菜单
    remove(type, row) {
      if (type == "menu") {
        this.temp = {
          id: row.idd,
          menuId: row.id,
          menuName: row.remark,
          sort: row.sort,
          type: "del",
          parentId: row.parentId
        };
      } else {
        this.temp = {
          id: row.idd,
          menuId: row.parentId,
          oprtId: row.id,
          oprtName: row.remark,
          // sort: row.sort,
          type: "del",
          parentId: row.parentId
        };
      }

      this.$confirm("确认提交", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        if (type == "menu") {
          setFun(this.temp).then((response) => {
            this.getMenuData();
            //菜单删除
            // const parent = node.parent;
            // const children = parent.data.children || parent.data;
            // const index = children.findIndex((d) => d.id === data.idd);
            // children.splice(index, 1);
          });
        } else {
          setButton(this.temp).then((response) => {
            this.getMenuData();
            //菜单删除
            // const parent = node.parent;
            // const children = parent.data.children || parent.data;
            // const index = children.findIndex((d) => d.id === data.idd);
            // children.splice(index, 1);
          });
        }
      });
    },

    //菜单提交
    commitTreeData(dataType) {
      this.$refs["dataForm"].validate((valid) => {
        if (valid) {
          this.$confirm("确认提交", "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning"
          }).then(() => {
            if (this.dialogStatus === "create") {
              this.$emit("commitMenu", this.temp, "create", this.statue);
            } else if (this.dialogStatus === "update") {
              this.$emit("commitMenu", this.temp, "update", this.statue);
            }
          });
        }
      });
    },

    // 新增修改菜单
    handleAddOrEdit(statue, row, type) {
      this.statue = statue;
      //修改对话框
      if (type === "update") {
        if (statue == "menu") {
          this.temp = {
            id: row.idd,
            menuId: row.id,
            menuName: row.remark,
            sort: row.sort,
            type: "updt",
            parentId: row.parentId
          };
        } else {
          this.temp = {
            id: row.idd,
            menuId: row.parentId,
            oprtId: row.id,
            oprtName: row.remark,
            type: "updt",
            parentId: row.parentId
          };
        }
      } else {
        if (statue == "menu") {
          this.temp = {
            id: "",
            menuId: "",
            menuName: "",
            sort: "",
            type: "add",
            parentId: row ? row.id : 0
          };
        } else {
          this.temp = {
            id: "",
            menuId: row.id,
            oprtId: "",
            oprtName: "",
            type: "add",
            parentId: row ? row.id : 0
          };
        }
      }
      this.dialogStatus = type;
      this.dialogFormVisible = true;
      this.$nextTick(() => {
        this.$refs["dataForm"].clearValidate();
      });
    }
  }
};
</script>

<style type="scss" scoped >
::v-deep .el-table th.el-table__cell.is-leaf,
::v-deep .el-table td.el-table__cell {
  border-bottom: 1px solid #ebeef5 !important;
}
</style>
