
<template>
  <el-dialog
    v-dialog-drag
    :close-on-press-escape="false"
    :close-on-click-modal="false"
    :title="`${readonly ? '查看' : '编辑'}菜单`"
    :visible.sync="dialogVisible"
    width="550px"
    append-to-body
    @close="handleCancel"
  >
    <el-form ref="form" class="full-form" :model="formState" :rules="rules" label-width="80px" :disabled="readonly">
      <el-form-item label="菜单权限">
        <el-checkbox v-model="menuExpand" @change="handleCheckedTreeExpand($event)">展开/折叠</el-checkbox>
        <el-checkbox v-model="menuNodeAll" @change="handleCheckedTreeNodeAll($event)">全选/全不选</el-checkbox>
        <el-tree
          ref="menu"
          class="tree-border"
          :data="menuOptions"
          show-checkbox
          node-key="id"
          :check-strictly="menuCheckStrictly"
          empty-text="加载中，请稍后"
          :props="defaultProps"
        />
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="handleSubmit">确 定</el-button>
      <el-button @click="handleCancel">取 消</el-button>
    </div>
  </el-dialog>
</template>
<script>
import { listSimpleMenus } from '@/api/system/menu'
import { editAdminMenu, fetchAdminMenuInfo } from '@/api/system/adminMenu'

const initForm = {
  name: null,
  menuIds: null
}
export default {
  name: 'MenuDialog',
  data() {
    return {
      dialogVisible: false,
      loading: false,
      readonly: false,
      menuExpand: false, // 是否展开
      menuNodeAll: false, // 是否全选
      menuOptions: [], // 菜单列表
      menuCheckStrictly: true, // 是否联动
      defaultProps: {
        label: 'name',
        children: 'children'
      },
      formState: Object.assign({}, initForm),
      rules: {
        menuIds: [{ required: true, message: '关联的菜单编号不能为空', trigger: 'blur' }]
      }
    }
  },
  created() {
    this.getMenus()
  },
  methods: {
    getMenus() {
      listSimpleMenus().then(response => {
        // 处理 menuOptions 参数
        this.menuOptions = []
        // 只需要配置
        this.menuOptions.push(...this.handleTree(response.data, 'id'))
      })
    },
    handleEdit(row, readonly) {
      this.readonly = readonly
      this.onReset()
      this.dialogVisible = true
      fetchAdminMenuInfo(row.id).then(response => {
        this.formState = response.data
        // 设置菜单项
        // 设置为严格，避免设置父节点自动选中子节点，解决半选中问题
        this.menuCheckStrictly = true
        // 设置选中
        this.$refs.menu.setCheckedKeys(response.data.menuIds.split(','))
        // 设置为非严格，继续使用半选中
        this.menuCheckStrictly = false
      })
    },
    getMenuAllCheckedKeys() {
      // 目前被选中的菜单节点
      const checkedKeys = this.$refs.menu.getCheckedKeys()
      // 半选中的菜单节点
      const halfCheckedKeys = this.$refs.menu.getHalfCheckedKeys()
      checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys)
      return checkedKeys
    },
    // 树权限（展开/折叠）
    handleCheckedTreeExpand(value, type) {
      const treeList = this.menuOptions
      for (let i = 0; i < treeList.length; i++) {
        this.$refs.menu.store.nodesMap[treeList[i].id].expanded = value
      }
    },
    // 树权限（全选/全不选）
    handleCheckedTreeNodeAll(value) {
      this.$refs.menu.setCheckedNodes(value ? this.menuOptions : [])
    },
    onReset() {
      this.menuExpand = false
      this.menuNodeAll = false
      this.menuCheckStrictly = true
      this.$refs.menu && this.$refs.menu.setCheckedKeys([])
    },
    handleSubmit() {
      this.$refs.form.validate(valid => {
        if (valid) {
          this.loading = true
          this.formState.menuIds = this.getMenuAllCheckedKeys().join(',')
          editAdminMenu(this.formState).then(() => {
            this.$modal.msgSuccess('保存成功')
            this.$emit('ok')
            this.handleCancel()
          }).finally(() => {
            this.loading = false
          })
        }
      })
    },
    handleCancel() {
      this.onReset()
      this.dialogVisible = false
      this.readonly = false
    }
  }
}
</script>
<style scoped lang="scss">

</style>
