<template>
  <div class='main-content'>
    <baseTable
      ref='defaultMenuTable'
      :tableHeader='tableHeader'
      :tableData='tableData'
      :tableOperate='tableOperate'
      :search='false'
      :many='false'
      :moreOperation='false'
      :isPage='false'
      :rowKey='treeProps.rowKey'
      :treeProps='treeProps.props'
      @searchFn='searchFn'
      @addFn='addFn'
    >
      <el-button slot='nextBtn' type='primary' @click='menuRefresh'>刷新菜单</el-button>
    </baseTable>
    <el-dialog width='800px' :title='formDialog.title' :visible.sync='formDialog.visible' :close-on-click-modal='false'>
      <el-form
        ref='defaultMenuForm'
        size='small'
        label-width='100px'
        :model='formDialog.formData'
        :rules='formDialog.formRules'
      >
        <!-- 菜单属性 -->
        <el-row>
          <el-col :span='12'>
            <el-form-item label='名称' prop='title'>
              <el-input v-model.trim='formDialog.formData.title' />
            </el-form-item>
          </el-col>
          <el-col :span='12'>
            <el-form-item label='父级' prop='parentId'>
              <menu-select
                :width='280'
                :clearable='false'
                :data='treeData'
                :defaultProps='formDialog.treeProps'
                :nodeKey='formDialog.rowKey'
                :checkedKeys='formDialog.defaultCheckedKeys'
                @popoverHide='popoverHide'
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span='12'>
            <el-form-item label='路由路径' prop='path'>
              <el-input v-model.trim='formDialog.formData.path' />
            </el-form-item>
          </el-col>
          <el-col :span='12'>
            <el-form-item label='组件' prop='component'>
              <el-input v-model.trim='formDialog.formData.component' />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span='12'>
            <el-form-item label='图标' prop='icon'>
              <el-popover placement='bottom-start' width='300' trigger='click'>
                <div class='icon-main'>
                  <i v-for='(item, i) in iconsList' :key='i' :class='item' @click='choiceIcon(item)'></i>
                </div>
                <el-input slot='reference' v-model.trim='formDialog.formData.icon' placeholder='点击选择图标'>
                  <el-button slot='append' v-if='formDialog.formData.icon' :icon='formDialog.formData.icon'></el-button>
                </el-input>
              </el-popover>
            </el-form-item>
          </el-col>
          <el-col :span='12'>
            <el-form-item label='排序号'>
              <el-input-number v-model.number='formDialog.formData.ord' :min='1' :max='99' />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span='12'>
            <el-form-item label='路由缓冲' prop='keepAlive'>
              <el-switch
                active-value='1'
                inactive-value='0'
                active-color='#13ce66'
                inactive-color='#ff4949'
                v-model.trim='formDialog.formData.keepAlive'
              />
            </el-form-item>
          </el-col>
          <el-col :span='12'>
            <el-form-item label='是否隐藏' prop='hidden'>
              <el-switch
                active-value='1'
                inactive-value='0'
                active-color='#13ce66'
                inactive-color='#ff4949'
                v-model.trim='formDialog.formData.hidden'
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-divider>权限配置（可选）</el-divider>
        <el-row v-for='(permission, index) in formDialog.formData.permissions' :key='permission.key'>
          <el-col :span='10'>
            <el-form-item
              label='权限名'
              :prop="'permissions.' + index + '.permissionName'"
              :rules='formDialog.formRules.permissionName'
            >
              <el-input v-model='permission.permissionName'></el-input>
            </el-form-item>
          </el-col>
          <el-col :span='10'>
            <el-form-item
              label='权限码'
              :prop="'permissions.' + index + '.permissionCode'"
              :rules='formDialog.formRules.permissionCode'
            >
              <el-input v-model='permission.permissionCode'></el-input>
            </el-form-item>
          </el-col>
          <el-col :span='4'>
            <span style='margin-left: 10px'></span>
            <el-button
              size='small'
              type='danger'
              icon='el-icon-circle-close'
              @click='removePermissionFn(permission)'
            ></el-button>
          </el-col>
        </el-row>
      </el-form>
      <div slot='footer'>
        <el-button type='success' icon='el-icon-circle-plus-outline' @click='addPermissionFn'>增加权限</el-button>
        <el-button type='primary' :loading='formDialog.loading' @click='submitFn'>确认</el-button>
        <el-button @click='cancelFn'>取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { loadMenuPage, refreshMenu, createMenu, removeMenu, updateMenu } from '@api/upms/api-menu';
import { formatDict } from '@utils/global';
import iconsList from '@utils/icons.js';
import menuSelect from '@views/system/components/menu-select';

export default {
  name: 'Menu',
  components: {
    menuSelect

  },
  computed: {
    dictResourceType() {
      return this.$store.getters.dict.dictResourceType;
    },
    dictYesOrNo() {
      return this.$store.getters.dict.dictYesOrNo;
    }
  },
  data() {
    return {
      iconsList: iconsList,
      treeData: [],
      treeProps: {
        rowKey: 'id',
        props: {
          children: 'children',
          hasChildren: 'leaf'
        }
      },
      tableHeader: [
        {
          label: '名称',
          prop: 'title',
          align: 'left',
          minWidth: 200
        },
        {
          label: '图标',
          align: 'center',
          type: 'render',
          width: 80,
          render: (h, params) => {
            return h('i', { class: params.row.icon });
          }
        },
        {
          label: '排序号',
          prop: 'ord',
          align: 'center',
          width: 80
        },
        {
          label: '隐藏菜单',
          align: 'center',
          width: 100,
          type: 'render',
          render: (h, params) => {
            return h(
              'el-tag',
              {
                props: {
                  size: 'mini',
                  type: params.row.hidden === '1' ? 'success' : 'danger'
                }
              },
              formatDict(this.dictYesOrNo, params.row.hidden)
            );
          }
        },
        {
          label: '路由缓冲',
          align: 'center',
          width: 100,
          type: 'render',
          render: (h, params) => {
            return h(
              'el-tag',
              {
                props: {
                  size: 'mini',
                  type: params.row.keepAlive === '1' ? 'success' : 'danger'
                }
              },
              formatDict(this.dictYesOrNo, params.row.keepAlive)
            );
          }
        },
        {
          label: '组件',
          prop: 'component',
          align: 'left',
          minWidth: 150
        },
        {
          label: '权限',
          align: 'left',
          minWidth: 150,
          type: 'render',
          render: (h, params) => {
            let permissions = [];
            for (let i in params.row.permissions) {
              permissions.push(
                h(
                  'el-tag',
                  {
                    props: {
                      size: 'mini'
                    },
                    style: {
                      marginLeft: '5px'
                    }
                  },
                  params.row.permissions[i].permissionName + ' '
                )
              );
            }
            return h('span', permissions);
          }
        }
      ],
      tableData: [],
      tableOperate: [
        {
          label: '编辑',
          type: 'primary',
          icon: 'el-icon-edit',
          func: (row) => {
            this.editFn(row);
          }
        },
        {
          label: '删除',
          type: 'danger',
          icon: 'el-icon-delete',
          func: (row) => {
            this.delFn(row);
          }
        }
      ],
      formDialog: {
        title: '',
        visible: false,
        loading: false,
        rowKey: 'id',
        treeProps: {
          label: 'title',
          children: 'children'
        },
        defaultCheckedKeys: [],
        type: '1',
        isEdit: true,
        formData: {},
        defaultData: {
          parentId: '0',
          scope: '1',
          allPath: '0|',
          deepLevel: 1,
          keepAlive: '1',
          hidden: '0',
          ord: 99,
          permissions: []
        },
        formRules: {
          title: [{ required: true, message: '请输入名称', trigger: 'blur' }],
          path: [{ required: true, message: '请输入路由路径', trigger: 'blur' }],
          component: [{ required: true, message: '请输入组件', trigger: 'blur' }],
          permissionName: [{ required: true, message: '权限名不能为空', trigger: 'blur' }],
          permissionCode: [{ required: true, message: '权限码不能为空', trigger: 'blur' }]
        }
      }
    };
  },
  methods: {
    // 选择图标
    choiceIcon(item) {
      this.$set(this.formDialog.formData, 'icon', item);
    },
    searchFn() {
      let vm = this;
      let params = {
        scope: '1'
      };
      loadMenuPage(params).then(
        (res) => {
          vm.tableData = res.data;
          let root = {
            id: '0',
            parentId: null,
            title: '根节点',
            children: [...res.data]
          };
          vm.treeData = [root];
        },
        (error) => {
          vm.$notify.error({
            title: error.data.msg,
            message: error.data.data
          });
        }
      );
    },
    menuRefresh() {
      let vm = this;
      refreshMenu().then(res => {
        vm.$message.success(res.msg);
        this.searchFn();
      });
    },
    addFn() {
      let vm = this;
      vm.formDialog.title = '新增';
      vm.formDialog.visible = true;
      vm.formDialog.loading = false;
      vm.formDialog.isEdit = false;
      vm.formDialog.type = '1';
      vm.formDialog.formData = Object.assign({}, vm.formDialog.defaultData);
      vm.formDialog.defaultCheckedKeys = ['0'];
      vm.formDialog.formData.permissions = [];
    },
    editFn(row) {
      let vm = this;
      vm.formDialog.title = '编辑';
      vm.formDialog.visible = true;
      vm.formDialog.loading = false;
      vm.formDialog.isEdit = true;
      vm.formDialog.type = row.type;
      vm.formDialog.formData = Object.assign({}, row);
      vm.formDialog.formData.children = [];
      vm.formDialog.defaultCheckedKeys = [row.parentId];
      let permissions = [];
      for (let i in row.permissions) {
        permissions.push(Object.assign({}, row.permissions[i], { key: row.permissions[i].id }));
      }
      vm.formDialog.formData.permissions = permissions;
    },
    submitFn() {
      let vm = this;
      vm.formDialog.loading = true;
      vm.$refs.defaultMenuForm.validate((valid) => {
        if (!valid) {
          vm.formDialog.loading = false;
          return;
        }
        let formData = vm.formDialog.formData;
        if (formData.id) {
          updateMenu(formData).then(
            (res) => {
              vm.$message.success('修改成功');
              vm.formDialog.visible = false;
              vm.formDialog.loading = false;
              vm.searchFn();
            },
            (error) => {
              vm.$notify.error({
                title: error.data.msg,
                message: error.data.data
              });
              vm.formDialog.loading = false;
            }
          );
        } else {
          createMenu(formData).then(
            (res) => {
              vm.$message.success('新增成功');
              vm.formDialog.visible = false;
              vm.formDialog.loading = false;
              vm.searchFn();
            },
            (error) => {
              vm.$notify.error({
                title: error.data.msg,
                message: error.data.data
              });
              vm.formDialog.loading = false;
            }
          );
        }
      });
    },
    cancelFn() {
      let vm = this;
      vm.formDialog.visible = false;
      vm.formDialog.loading = false;
      vm.formDialog.formData = Object.assign({}, vm.formDialog.defaultData);
      vm.$refs.defaultMenuForm.resetFields();
    },
    delFn(row) {
      let vm = this;
      this.$confirm('此操作将删除该记录, 是否继续?', '提示', {
        type: 'warning'
      }).then(() => {
        removeMenu({ id: row.id }).then(
          (res) => {
            vm.$message.success('删除成功');
            vm.searchFn(true);
          },
          (error) => {
            vm.$notify.error({
              title: error.data.msg,
              message: error.data.data
            });
          }
        );
      });
    },
    popoverHide(checkedIds, checkedData) {
      if (!checkedIds) {
        return;
      }
      let vm = this;
      vm.formDialog.formData.parentId = checkedIds;
      vm.formDialog.formData.deepLevel = checkedData.deepLevel + 1;
      vm.formDialog.formData.allPath = checkedData.allPath + checkedData.id + '|';
    },
    selectIcon() {
      // TODO 选择图标
      let vm = this;
      vm.formDialog.formData.icon = 'el-icon-menu';
    },
    addPermissionFn() {
      let vm = this;
      vm.formDialog.formData.permissions.push({
        key: new Date().getTime(),
        permissionName: '',
        permissionCode: ''
      });
    },
    removePermissionFn(item) {
      let vm = this;
      let index = vm.formDialog.formData.permissions.indexOf(item);
      if (index !== -1) {
        vm.formDialog.formData.permissions.splice(index, 1);
      }
    }
  },
  created() {
    this.searchFn();
  }
};
</script>

<style scoped lang='less'>
.check {
  margin-left: 10px;
  margin-bottom: 10px;
}

.icon-main {
  width: 100%;
  height: 300px;
  overflow-y: auto;

  i {
    font-size: 24px;
    padding: 8px;
    cursor: pointer;

    &:hover {
      background: #eff1f4;
      border-radius: 4px;
    }
  }
}
</style>
