<template>
  <div>
    <el-dialog :model-value="modelValue" title="添加菜单"
               @close="() => $emit('update:modelValue', false)">
      <el-row>
        <el-col :span="10">
          <h5>当前存在的菜单信息参考</h5>
          <el-scrollbar :max-height="500">
            <el-tree :data="menu" @node-click="nodeClick">
            </el-tree>
          </el-scrollbar>
        </el-col>
        <el-col :span="14" style="border-left: #2c3e5033 solid 1px; padding-left: 20px;">
          <el-form
              label-position="left"
              label-width="160px"
              :model="menuData"
              :inline="true"
              class="demo-form-inline"
          >
            <el-form-item label="一级菜单序号：">
              <el-input v-model="menuData.mainMenuIndex"/>
            </el-form-item>
            <el-form-item label="一级菜单名称：">
              <el-input v-model="menuData.mainMenuName"/>
            </el-form-item>
            <el-form-item label="一级菜单图标：">
              <el-input v-model="menuData.mainMenuIco"/>
            </el-form-item>
            <el-form-item label="二级菜单序号：">
              <el-input v-model="menuData.minorMenuIndex">
              </el-input>
            </el-form-item>
            <el-form-item label="二级菜单名称：">
              <el-input v-model="menuData.minorMenuName"/>
            </el-form-item>
            <el-form-item label="二级菜单图标：">
              <el-input v-model="menuData.minorMenuIco"/>
            </el-form-item>
            <el-form-item label="二级菜单路由：">
              <el-input v-model="menuData.minorMenuRouter"/>
            </el-form-item>
            <el-form-item label="菜单状态：">
              <el-switch
                  v-model="menuData.menuStatus"
                  inline-prompt
                  active-text="启用"
                  inactive-text="停用"
                  active-value="1"
                  inactive-value="0"
              />
            </el-form-item>
            <el-form-item label="备注：">
              <el-input v-model="menuData.remark"/>
            </el-form-item>
          </el-form>
        </el-col>
      </el-row>
      <template #footer>
        <div>
          <el-button type="primary" @click="addMenu">添加</el-button>
          <el-button type="danger" @click="$emit('update:modelValue', false)">关闭</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
// import  《组件名称》  from '《组件路径》 ';

import {ElLoading, ElMessage, ElMessageBox} from "element-plus";
import menuApi from "@/axios/menu";

export default {
  // import 引入的组件需要注入到对象中才能使用
  components: {},
  props: ['modelValue', 'menuList'],
  emits: ['update:modelValue'],
  data() {
    // 这里存放数据
    return {
      menuData: {
        mainMenuIndex: '',
        mainMenuName: '',
        mainMenuIco: '',
        minorMenuIndex: '',
        minorMenuName: '',
        minorMenuIco: '',
        minorMenuRouter: '',
        menuStatus: '1',
        remark: ''
      },
      // 显示在树形控件里的值
      menu: []

    }
  },
  // 计算属性 类似于 data 概念
  computed: {},
  // 监控 data 中的数据变化
  watch: {
    modelValue(newValue, oldValue) {
      if(newValue === true) {
        this.showMenuTree()
      }
    }
  },
  // 方法集合
  methods: {
    // 添加菜单
    addMenu() {
      ElMessageBox.confirm(
          '确定添加该菜单?添加后只能在数据库删除',
          '警告',
          {
            confirmButtonText: '确定添加',
            cancelButtonText: '取消',
            type: 'warning',
          }
      ).then(() => {
        const loading = ElLoading.service({
          lock: true,
          text: '加载中...',
        })
        const menuDto = {
          mainMenuIndex: this.menuData.mainMenuIndex,
          mainMenuName: this.menuData.mainMenuName,
          mainMenuIco: this.menuData.mainMenuIco,
          minorMenuIndex: this.menuData.minorMenuIndex,
          minorMenuName: this.menuData.minorMenuName,
          minorMenuIco: this.menuData.minorMenuIco,
          minorMenuRouter: this.menuData.minorMenuRouter,
          menuStatus: this.menuData.menuStatus,
          remark: this.menuData.remark
        }
        menuApi.addMenu(menuDto).then((response) => {
          const responseData = response.data
          if (responseData.code === 0) {
            ElMessage({
              message: '添加菜单信息成功',
              type: 'success',
            })
            this.showMenuTree()
          } else {
            ElMessage({
              message: '更新失败',
              type: 'warning',
            })
          }
        }).catch((ex) => {
          ElMessage({
            message: '请求服务器失败：' + ex,
            type: 'error',
          })
        })
        loading.close()
      }).catch(() => {
      })
    },
    resetMenuData() {
      this.menuData.mainMenuIndex = ''
      this.menuData.mainMenuName = ''
      this.menuData.mainMenuIco = ''
      this.menuData.minorMenuIndex = ''
      this.menuData.minorMenuName = ''
      this.menuData.minorMenuIco = ''
      this.menuData.minorMenuRouter = ''
      this.menuData.menuStatus = '1'
      this.menuData.remark = ''
    },
    // 树形控件被点击的时候
    nodeClick(node) {
      this.resetMenuData()
      const menuLabel = node.label
      const menuInfo = menuLabel.split('*')
      const mainMenu = this.menuList.filter(f=>f.mainMenuIndex === menuInfo[0])
      if(mainMenu !== undefined && mainMenu.length > 0) {
        this.menuData.mainMenuIndex = mainMenu[0].mainMenuIndex
        this.menuData.mainMenuIco = mainMenu[0].mainMenuIco
        this.menuData.mainMenuName = mainMenu[0].mainMenuName
        return
      }
      const minorMenu = this.menuList.filter(f=>f.minorMenuIndex === menuInfo[0])
      if(minorMenu !== undefined && minorMenu.length > 0) {
        this.menuData.mainMenuIndex = minorMenu[0].mainMenuIndex
        this.menuData.mainMenuName = minorMenu[0].mainMenuName
        this.menuData.mainMenuIco = minorMenu[0].mainMenuIco
        this.menuData.minorMenuIndex = minorMenu[0].minorMenuIndex
        this.menuData.minorMenuIco = minorMenu[0].minorMenuIco
        this.menuData.minorMenuName = minorMenu[0].minorMenuName
      }
    },
    // 启动时加载树形控件的信息
    showMenuTree() {
      if(this.menuList === undefined || this.menuList.length < 1) {
        return
      }
      let menuTree = []
      this.menuList.forEach((value)=> {
        const filterResult = menuTree.filter(f=>f.mainMenuIndex === value.mainMenuIndex)
        if(filterResult === undefined || filterResult.length < 1) {
          menuTree.push({
            mainMenuIndex: value.mainMenuIndex,
            mainMenuName: value.mainMenuName,
          })
        }
      })
      if(menuTree.length > 1) {
        menuTree.forEach((value) => {
          value.minorMenu = [];
          const filterResult =  this.menuList.filter(f=>f.mainMenuIndex === value.mainMenuIndex)
          if(filterResult !== undefined && filterResult.length > 0) {
            filterResult.forEach((minorValue)=>{
              value.minorMenu.push({
                minorMenuIndex: minorValue.minorMenuIndex,
                minorMenuName: minorValue.minorMenuName,
              })
            })
          }
        })
      }
      // 添加到树型控件
      if(menuTree.length > 1) {
        let treeItems = []
        menuTree.forEach((value)=>{
          let treeItem = {}
          treeItem.label = `${value.mainMenuIndex}*${value.mainMenuName}`
          treeItem.children = []
          value.minorMenu.forEach((minorValue)=>{
            treeItem.children.push({
              label: `${minorValue.minorMenuIndex}*${minorValue.minorMenuName}`
            })
          })
          treeItems.push(treeItem)
        })
        this.menu = treeItems
      }
    }
  },
  // 组合式 API
  setup() {
  },
  // 创建之前
  beforeCreate() {
  },
  // 创建完成(可以访问 this 实例)
  created() {
  },
  // 生命周期 - 挂载之前
  beforeMount() {
  },
  // 生命周期 - 挂载完成（可以访问 DOM 元素）
  mounted() {

  },
  // 更新之前
  beforeUpdate() {
  },
  // 更新之后
  updated() {
  },
  // 销毁之前
  beforeUnmount() {
  },
  // 销毁完成
  unmounted() {
  }
}
</script>

<style scoped>
.demo-form-inline {
  width: 100%;
  .el-input {
    --el-input-width: 100%;
  }
  .el-form-item {
    width: 100%;
  }
}


.demo-form-inline .el-select {
  --el-select-width: 100%;
}

</style>