<template>
  <el-drawer :title="title" :visible.sync="visible" size="40%" :before-close="onBeforeClose">
    <div class="menus-edit">
      <div class="menus-edit-form">
        <el-form ref="menuFrom" label-width="100px" :model="menuData" :rules="rules">
          <el-form-item label="父级菜单：" prop="parentId">
            <el-cascader
              v-model="menuData.parentId"
              style="width: 100%"
              :options="menuOptions"
              :props="menuProps"
              placeholder="请选择父级菜单，不选默认为顶级菜单"
              clearable
            />
          </el-form-item>
          <el-form-item label="菜单名称：" prop="title">
            <el-input v-model="menuData.title" placeholder="菜单名称" />
          </el-form-item>
          <el-form-item label="路由名称：" prop="name">
            <el-input v-model="menuData.name" placeholder="路由名称" />
          </el-form-item>
          <el-form-item label="显示隐藏：">
            <el-radio-group v-model="menuData.hidden">
              <el-radio :label="0">显示</el-radio>
              <el-radio :label="1">隐藏</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="前端图标：">
            <el-popover v-model="showIcons" placement="bottom" width="400" trigger="click">
              <icon-list @click="onChooseIcon" />
              <div slot="reference">
                <el-input v-model="menuData.icon" style="width: 80%" placeholder="选择图标" clearable>
                  <template><el-button slot="append" icon="el-icon-edit" /></template>
                </el-input>
                <template>
                  <i v-if="isElementIcon(menuData.icon)" :class="menuData.icon" class="preview-icon" />
                  <i v-if="isOurIcon(menuData.icon)" :class="menuData.icon" class="preview-icon" />
                  <svg-icon v-else-if="menuData.icon" :icon-class="menuData.icon" class="preview-icon" />
                </template>
              </div>
            </el-popover>
          </el-form-item>
          <template v-if="!parentMenuData && menuType !== 1">
            <el-form-item label="功能类型：" prop="baseFlag">
              <el-radio-group v-model="menuData.baseFlag">
                <el-radio :label="1">基础功能</el-radio>
                <el-radio :label="0">会员特定</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="功能切换：" prop="moveFlag">
              <el-radio-group v-model="menuData.moveFlag">
                <el-radio :label="1">允许</el-radio>
                <el-radio :label="0">禁止</el-radio>
              </el-radio-group>
            </el-form-item>
          </template>
          <el-form-item label="状态：">
            <el-radio-group v-model="menuData.status">
              <el-radio :label="0">启用</el-radio>
              <el-radio :label="1">停用</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="排序：">
            <el-input v-model="menuData.sort" />
          </el-form-item>
          <el-form-item label="按钮权限：">
            <template>
              <el-input v-show="false" v-model="menuData.permissionJson" />
              <el-table border :data="permissions">
                <el-table-column label="按钮名称" align="center">
                  <template slot-scope="{ row }">
                    <el-input v-model="row.title" size="mini" />
                  </template>
                </el-table-column>
                <el-table-column label="权限标识" align="center">
                  <template slot-scope="{ row }">
                    <el-input v-model="row.name" size="mini" />
                  </template>
                </el-table-column>
                <el-table-column label="操作" align="center">
                  <template slot-scope="{ row }">
                    <el-button type="danger" size="mini" @click="removeOne(row.uuid)">删除按钮</el-button>
                  </template>
                </el-table-column>
              </el-table>
              <div style="text-align: center; margin-top: 24px">
                <el-button type="primary" size="mini" @click="insertOne">添加按钮</el-button>
              </div>
            </template>
          </el-form-item>
        </el-form>
      </div>
      <!-- 确认 取消 -->
      <div class="control-box">
        <el-button type="warning" @click="cancel">取消</el-button>
        <el-button type="primary" @click="submit">保存</el-button>
      </div>
    </div>
  </el-drawer>
</template>

<script>
import { createMenu, getMenu, updateMenu, sysMenuTree } from '@/api/system'
import IconList from '@/components/IconList'
import { deepClone } from '@/utils'
let uuid = 0
const menuData = () => ({
  id: '',
  title: '',
  name: '',
  icon: '',
  hidden: 0,
  status: 0,
  sort: 0,
  childCount: 0,
  permissionJson: '',
  parentId: 0,
  baseFlag: 1,
  moveFlag: 1,
  menuType: 1
})

export default {
  name: 'EditPage',
  components: {
    IconList
  },
  props: {
    show: {
      type: Boolean,
      default: false
    },
    title: {
      type: String,
      default: 'add'
    },
    // 编辑类型
    editType: {
      type: String,
      default: 'add'
    },
    // 菜单类型
    menuType: {
      type: Number,
      default: 1
    },
    // 菜单id
    menuId: {
      type: Number,
      default: 0
    }
  },
  data() {
    return {
      menuOptions: [],
      visible: false,
      showIcons: false,
      // 上级菜单信息
      parentMenuData: null,
      // 表单参数
      menuData: menuData(),
      // 按钮权限列表
      permissions: [],
      // 验证规则
      rules: {
        title: [{ required: true, message: '菜单名称不能为空', trigger: 'blur' }],
        name: [{ required: true, message: '路由名称不能为空', trigger: 'blur' }]
      },
      menuProps: {
        value: 'id',
        label: 'title',
        children: 'subMenus',
        emitPath: false,
        checkStrictly: true
      }
    }
  },
  watch: {
    show(nval) {
      if (nval) {
        this.visible = nval
        this.init()
      }
    },
    visible(nval) {
      if (!nval) this.$emit('close')
    }
  },
  methods: {
    onChooseIcon(item) {
      this.showIcons = false
      this.menuData.icon = item
    },
    // 选择图标
    handleChooseIcon() {
      this.showIcons = true
    },

    // 初始化
    init() {
      this.menuData = menuData()
      this.parentMenuData = null
      this.permissions = []
      console.log('menuId', this.menuId)

      this.menuData.menuType = this.menuType
      this.fetchMenuList()
      // 编辑修改菜单
      if (this.editType === 'edit') {
        this.menuData.id = this.menuId
        this.fetchMenuInfo()
      } else if (this.editType === 'child') {
        this.menuData.parentId = this.menuId.toString()
      }
    },

    // 获取父菜单信息
    fetchParentMenuInfo() {
      getMenu(this.menuData.parentId).then((res) => {
        this.parentMenuData = res.data
        this.menuData.baseFlag = res.data.baseFlag
      })
    },

    // 获取父级菜单列表
    async fetchMenuList() {
      try {
        const res = await sysMenuTree({ menuType: this.menuType })
        this.menuOptions = res.data
      } catch (error) {
        console.log(error)
      }
    },

    // 获取菜单数据
    fetchMenuInfo() {
      getMenu(this.menuData.id).then((res) => {
        this.setMenuData(res.data)
      })
    },

    // 设置菜单数据(编辑时调用)
    setMenuData(data) {
      for (const key in this.menuData) {
        if (Object.hasOwnProperty.call(data, key)) {
          this.menuData[key] = data[key]
        }
      }
      // 按钮权限列表
      if (this.permissionJson) {
        this.permissions = JSON.parse(this.permissionJson)
      }
      // 父级菜单信息
      if (this.menuData.parentId > 0) {
        this.menuData.parentId = this.menuData.parentId.toString()
      }
    },

    // 判断图标类型
    isElementIcon(value) {
      return value && value.substr(0, 7) === 'el-icon'
    },

    // 判断自定义图标
    isOurIcon(value) {
      return value && value.startsWith('iconfont')
    },

    // 提交
    submit() {
      console.log(this.menuData)
      this.menuData.permissionJson = JSON.stringify(this.permissions)
      this.$refs.menuFrom.validate((valide) => {
        if (!valide) return
        if (this.editType === 'add' || this.editType === 'child') {
          this.createMenu()
        } else {
          this.updateMenu()
        }
      })
    },

    // 修改菜单
    async updateMenu() {
      try {
        const menuData = deepClone(this.menuData)
        menuData.parentId = parseInt(menuData.parentId)
        await updateMenu(this.menuData.id, this.menuData)
        this.$message.success('修改菜单成功')
        this.$emit('success')
        this.$refs.menuFrom.clearValidate()
        this.visible = false
      } catch (error) {
        this.$emit('error')
      }
    },

    // 添加菜单
    async createMenu() {
      try {
        const menuData = deepClone(this.menuData)
        menuData.parentId = parseInt(menuData.parentId)
        await createMenu(this.menuData)
        this.$message.success('添加菜单成功')
        this.$emit('success')
        this.$refs.menuFrom.clearValidate()
        this.visible = false
      } catch (error) {
        this.$emit('error')
      }
    },

    cancel() {
      this.visible = false
    },

    // 添加按钮权限
    insertOne() {
      this.permissions.push({
        uuid: ++uuid,
        name: '',
        title: ''
      })
    },

    // 移除一条按钮权限
    removeOne(uuid) {
      const index = this.permissions.findIndex((item) => item.uuid === uuid)
      this.permissions.splice(index, 1)
    },

    onBeforeClose(done) {
      this.$confirm('您有数据未保存, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.$refs.menuFrom.clearValidate()
          done()
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消关闭'
          })
        })
    }
  }
}
</script>

<style scoped lang="scss">
.menus-edit {
  position: relative;
  height: calc(100vh - 45px);

  .menus-edit-form {
    overflow-y: auto;
    height: 100%;
    box-sizing: border-box;
    padding: 24px 12px 60px;
  }

  .preview-icon {
    font-size: 24px;
    margin-left: 8px;
  }
}
.control-box {
  position: absolute;
  bottom: 0;
  left: 0;
  width: 100%;
  text-align: center;
  background: #fff;
  border-top: 1px solid #ebebeb;
  padding: 12px 0;
  z-index: 9;
  .el-button {
    width: 120px;
    margin: 0 8px;
  }
}
</style>
