<template>
  <div class="app-container">
    <!--工具栏-->
    <div class="head-container">
      <div v-if="crud.props.searchToggle">
        <!-- 搜索 -->
        <el-input
          v-model="query.blurry"
          clearable
          size="small"
          placeholder="模糊搜索"
          style="width: 200px"
          class="filter-item"
          @keyup.enter.native="crud.toQuery"
        />
        <date-range-picker v-model="query.createTime" class="date-item" />
        <rrOperation />
      </div>
      <crudOperation :permission="permission" />
    </div>
    <!--表单渲染-->
    <el-dialog
      append-to-body
      :close-on-click-modal="false"
      :before-close="crud.cancelCU"
      :visible.sync="crudCU"
      :title="crud.status.title"
      width="580px"
    >
      <el-form
        ref="form"
        :inline="true"
        :model="form"
        :rules="rules"
        size="small"
        label-width="80px"
      >
        <el-form-item label="菜单类型" prop="type">
          <el-radio-group v-model="form.type" size="mini">
            <el-radio-button label="0">目录</el-radio-button>
            <el-radio-button label="1">菜单</el-radio-button>
            <el-radio-button label="2">按钮</el-radio-button>
            <el-radio-button label="3">大屏</el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="上级类目" prop="pid">
          <treeselect
            v-model="form.pid"
            :options="menus"
            :load-options="loadMenus"
            style="width: 450px"
            placeholder="选择上级类目"
          />
        </el-form-item>
        <el-form-item v-show="['0', '1'].includes(form.type + '')" label="菜单图标" prop="icon">
          <el-popover
            placement="bottom-start"
            width="450"
            trigger="click"
            @show="$refs['iconSelect'].reset()"
          >
            <IconSelect ref="iconSelect" @selected="selected" />
            <el-input
              slot="reference"
              v-model="form.icon"
              style="width: 450px"
              placeholder="点击选择图标"
              readonly
            >
              <svg-icon
                v-if="form.icon"
                slot="prefix"
                :icon-class="form.icon"
                class="el-input__icon"
                style="height: 32px; width: 16px"
              />
              <i v-else slot="prefix" class="el-icon-search el-input__icon" />
              <i
                v-if="form.icon"
                slot="suffix"
                class="el-icon-circle-close"
                style="margin-right: 5px"
                @click="form.icon = ''"
              ></i>
            </el-input>
          </el-popover>
        </el-form-item>
        <el-form-item v-show="['0', '1'].includes(form.type + '')" label="外链菜单" prop="iframe">
          <el-radio-group v-model="form.iframe" size="mini">
            <el-radio-button label="true">是</el-radio-button>
            <el-radio-button label="false">否</el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item v-show="['1'].includes(form.type + '')" label="菜单缓存" prop="cache">
          <el-radio-group v-model="form.cache" size="mini">
            <el-radio-button label="true">是</el-radio-button>
            <el-radio-button label="false">否</el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item v-show="['0', '1'].includes(form.type + '')" label="菜单可见" prop="hidden">
          <el-radio-group v-model="form.hidden" size="mini">
            <el-radio-button label="false">是</el-radio-button>
            <el-radio-button label="true">否</el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item v-if="['0', '1', '3'].includes(form.type + '')" label="菜单标题" prop="title">
          <el-input v-model="form.title" style="width: 178px" placeholder="菜单标题" />
        </el-form-item>
        <el-form-item v-if="['2'].includes(form.type + '')" label="按钮名称" prop="title">
          <el-input v-model="form.title" placeholder="按钮名称" style="width: 178px" />
        </el-form-item>
        <el-form-item
          v-show="['0', '1', '2'].includes(form.type + '')"
          label="权限标识"
          prop="permission"
        >
          <el-input
            v-model="form.permission"
            :disabled="form.iframe.toString() === 'true'"
            placeholder="权限标识"
            style="width: 178px"
          />
        </el-form-item>
        <el-form-item v-if="['0', '1'].includes(form.type + '')" label="路由地址" prop="path">
          <el-input v-model="form.path" placeholder="路由地址" style="width: 178px" />
        </el-form-item>
        <el-form-item label="菜单排序" prop="menuSort">
          <el-input-number
            v-model.number="form.menuSort"
            :min="0"
            :max="999999"
            controls-position="right"
            style="width: 178px"
          />
        </el-form-item>
        <el-form-item
          v-show="form.iframe.toString() !== 'true' && form.type.toString() === '1'"
          label="组件名称"
          prop="componentName"
        >
          <el-input
            v-model="form.componentName"
            style="width: 178px"
            placeholder="匹配组件内Name字段"
          />
        </el-form-item>
        <el-form-item
          v-show="form.iframe.toString() !== 'true' && form.type.toString() === '1'"
          label="组件路径"
          prop="component"
        >
          <el-input v-model="form.component" style="width: 178px" placeholder="组件路径" />
        </el-form-item>
        <el-form-item v-if="['3'].includes(form.type + '')" label="菜单脚本" prop="script">
          <el-input
            v-model="form.script"
            style="width: 450px"
            rows="5"
            type="textarea"
            placeholder="请输入菜单脚本"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="text" @click="crud.cancelCU">取消</el-button>
        <el-button :loading="crud.status.cu === 2" type="primary" @click="crud.submitCU"
          >确认</el-button
        >
      </div>
    </el-dialog>
    <!--表格渲染-->
    <el-table
      ref="table"
      v-loading="crud.loading"
      lazy
      :load="getMenus"
      :data="crud.data"
      :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
      row-key="id"
      @select="crud.selectChange"
      @select-all="crud.selectAllChange"
      @selection-change="crud.selectionChangeHandler"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column
        v-for="item in menuTableOptions"
        :key="item.prop"
        :label="item.label"
        :prop="item.prop"
        :width="item.width"
        :align="item.align"
        :fixed="item.fixed"
        :sortable="item.sortable"
      >
        <template slot-scope="scope">
          <span v-if="item.prop == 'icon'">
            <svg-icon class="svg-color" :icon-class="scope.row.icon ? scope.row.icon : ''" />
          </span>
          <span v-else-if="item.prop == 'iframe'">
            <span v-if="scope.row.iframe">是</span>
            <span v-else>否</span>
          </span>
          <span v-else-if="item.prop == 'cache'">
            <span v-if="scope.row.cache">是</span>
            <span v-else>否</span>
          </span>
          <span v-else-if="item.prop == 'hidden'">
            <el-switch
              v-model="scope.row.hidden"
              active-color="#13ce66"
              :active-value="true"
              :inactive-value="false"
              @change="setVisible(scope.row)"
            >
            </el-switch>
            <!-- <span v-if="scope.row.hidden">是</span>
            <span v-else>否</span> -->
          </span>
          <span v-else>{{ scope.row[item.prop] }}</span>
        </template>
      </el-table-column>
      <el-table-column
        v-if="checkPer(['admin', 'menu:edit', 'menu:del'])"
        label="操作"
        width="130px"
        align="center"
        fixed="right"
      >
        <template slot-scope="scope">
          <udOperation
            :data="scope.row"
            :permission="permission"
            msg="确定删除吗,如果存在下级节点则一并删除，此操作不能撤销！"
          />
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script>
import permission from '@/directive/permission'
import crudMenu, { edit } from '@/api/system/menu'
import CRUD, { presenter, header, form, crud } from '@crud/crud'
// import { crudOperation, rrOperation, udOperation, pagination } from '@crud'
import crudComps from '@crud'
import DateRangePicker from '@/components/DateRangePicker'
import IconSelect from '@/components/IconSelect'

// vue-treeselect
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import { LOAD_CHILDREN_OPTIONS } from '@riophae/vue-treeselect'

// 表头配置
import { menuTableOptions } from '../tableConfig'

// crud交由presenter持有
const defaultForm = {
  id: '',
  title: '',
  menuSort: 0,
  path: '',
  component: '',
  componentName: '',
  iframe: false,
  roles: [],
  pid: 0,
  icon: '',
  cache: false,
  hidden: false,
  type: 0,
  permission: '',
  script: '',
}
export default {
  name: 'Menu',
  directives: { permission },
  mixins: [presenter(), header(), form(defaultForm), crud()],
  components: {
    ...crudComps,
    DateRangePicker,
    Treeselect,
    IconSelect,
  },
  cruds() {
    return CRUD({ title: '菜单', url: 'system/menu/getList', crudMethod: { ...crudMenu } })
  },
  data() {
    return {
      menuTableOptions,
      menus: [],
      permission: {
        add: ['admin', 'menu:add'],
        edit: ['admin', 'menu:edit'],
        del: ['admin', 'menu:del'],
      },
      rules: {
        title: [{ required: true, message: '请输入标题', trigger: 'blur' }],
        path: [{ required: true, message: '请输入地址', trigger: 'blur' }],
        permission: [{ required: true, message: '请输入权限标识', trigger: 'blur' }],
      },
    }
  },
  computed: {
    crudCU() {
      return this.crud.status.cu > 0
    },
  },
  methods: {
    // 新增与编辑前做的操作
    [CRUD.HOOK.afterToCU](crud, form) {
      // this.getSupMenus()
      this.menus = []
      if (form.id != '') {
        if (form.pid === '') {
          form.pid = 0
        }
        this.getSupMenus(form.id)
      } else {
        this.menus.push({ id: 0, label: '顶级类目', children: null })
      }
    },
    // 提交前的验证
    [CRUD.HOOK.afterValidateCU]() {
      if (this.form.type == '0' && !this.form.component) {
        this.form.component = 'Layout'
      }
    },
    getMenus(tree, treeNode, resolve) {
      const params = { pid: tree.id }
      setTimeout(() => {
        crudMenu.getMenus(params).then((res) => {
          resolve(res.data.content)
        })
      }, 100)
    },
    getSupMenus(id) {
      crudMenu.getMenusTree({ pid: '0' }).then((res) => {
        const data = res.data.content
        this.buildMenus(data)
        console.log(data)
        this.menus = [{ id: 0, label: '顶级类目', children: data }]
      })
    },
    buildMenus(menus) {
      menus.forEach((data) => {
        // if (!data.hasChildren) {
        //   delete data.children
        // }
        if (data.children) {
          this.buildMenus(data.children)
        }
      })
    },
    // getSupMenus(id) {
    //   crudMenu.getMenusTree({ pid: id }).then(res => {
    //     const children = res.data.content.map(function(obj) {
    //       if (!obj.leaf && !obj.children) {
    //         obj.children = null
    //       }
    //       return obj
    //     })
    //     this.menus = [{ id: 0, label: '顶级类目', children: children }]
    //   })
    // },
    loadMenus({ action, parentNode, callback }) {
      if (action === LOAD_CHILDREN_OPTIONS) {
        crudMenu.getMenus({ pid: parentNode.id }).then((res) => {
          parentNode.children = res.data.content.map(function (obj) {
            if (!obj.leaf) {
              obj.children = null
            }
            return obj
          })
          setTimeout(() => {
            callback()
          }, 100)
        })
      }
    },
    // 选中图标
    selected(name) {
      this.form.icon = name
    },
    setVisible(row) {
      edit(row)
        .then((res) => {
          console.log('修改成功')
        })
        .catch((err) => {
          console.log(err)
        })
    },
  },
}
</script>

<style lang="scss" scoped></style>
