<template>
  <div class="pa-3 white">
    <menu-list
      :headers="header"
      :items="items"
      :total="total"
      :loading="loading"
      :show-select="false"
      @edit="handleEdit"
      @add="handleAdd"
      @copy="handleCopy"
      @delete="handleDelete"
    >
      <template v-slot:navBtn>
        <div style="flex: 1">
          <m-btn :loading="uploadLoading" class="elevation-5 buttons" color="primary" @change="importMenu">
            <v-icon left>mdi-cloud-upload</v-icon>
            导入菜单
          </m-btn>
          <v-btn :loading="downloadLoading" class="ml-2 elevation-5 buttons" rounded   color="primary" @click="exportMenu">
            <v-icon left>mdi-download</v-icon>
            导出菜单
          </v-btn>
        </div>
      </template>
    </menu-list>
    <edit-dialog :title="title" :visible.sync="show" @submit="handleSave">
      <menu-edit v-if="show" ref="menuEdit" :items="itemsParents" :menu-list="dictionary" :item-data="itemData"></menu-edit>
    </edit-dialog>
  </div>
</template>

<script>
import MBtn from '@/components/UploadBtn'
import MenuList from './components/list.vue'
import EditDialog from '@/components/Dialog'
import MenuEdit from './components/edit'
import FileSaver from 'file-saver'
import { getRouters, getRoutersDetail, saveMenu, importMenu, exportMenu } from '@/api/menu'
export default {
  name: 'route-manage',
  components: { EditDialog, MenuEdit, MenuList, MBtn },
  data () {
    return {
      itemsParents: [],
      showParents: false,
      show: false,
      title: '',
      header: [],
      items: [],
      total: 0,
      orders: [],
      loading: true,
      itemData: {},
      dictionary: [
        { label: '目录', value: 0 },
        { label: '菜单', value: 1 },
        { label: '按钮', value: 2 },
        { label: '组件', value: 3 }
      ],
      uploadLoading: false,
      downloadLoading: false
    }
  },
  created () {
    this.initHeader()
  },
  methods: {
    initHeader () {
      const header = {
        'data-table-expand': '菜单名称',
        // id: 'ID',
        // dataTableExpand: '',
        // label: '名字',
        // enName: '英文名字',
        icon: '图标',
        sort: '排序',
        // name: '路由',
        // type: '类型',
        hidden: '状态',
        component: '组件路径',
        code: '权限标识',
        // active: '激活',
        remark: '备注',
        // path: '路径',
        actions: '操作'
      }
      const keys = Object.keys(header)
      const centerKeys = ['hidden', 'sort', 'icon']
      this.header = keys.map(key => {
        return {
          text: header[key],
          align: centerKeys.includes(key) ? 'center' : 'start',
          value: key
        }
      })
      this.initPage()
    },
    async initPage () {
      this.loading = true
      try {
        const { data } = await getRouters({})
        this.itemsParents = [{ label: '根菜单', id: 0, children: data }]
        this.items = this.changeData(data)
        this.total = data.length
        this.loading = false
      } catch (error) {
        this.$snackbar.error(error)
      }
    },
    changeData (data) {
      return data.map(item => {
        item.type = this.dictionary.find(e => e.value === item.type).label
        if (item.children && item.children.length) item.children = this.changeData(item.children)
        return item
      })
    },
    handleChangeRedirect (val, index) {
      this.formConfig.options[index + 1].hide = !val
    },
    async handleSave () {
      const queryData = this.$refs.menuEdit.getQuery()
      if (!queryData) {
        return
      }
      try {
        await saveMenu(queryData)
        this.show = false
        this.$snackbar.success('保存成功')
        await this.$store.dispatch('menu/getMenu2')
        this.initPage()
      } catch (error) {
        this.$snackbar.error(error)
      }
    },
    handleAdd () {
      this.title = '添加路由'
      this.itemData = {}
      this.show = true
    },
    handleDelete (ids) {
      if (Array.isArray(ids)) return this.$snackbar.info('该项只支持单项删除')
      this.$confirm('消息', `是否确定删除该选项 ${ids.toString()} 包括所以子项`)
        .then(async () => {
          try {
            await this.$store.dispatch('menu/deleteMenu', { id: ids.toString() })
            this.$snackbar.success('删除成功')
            this.initPage()
          } catch (error) {
            this.$snackbar.error(error)
          }
        })
    },
    async handleEdit ({ id }) {
      try {
        const { data } = await getRoutersDetail({ id })
        this.title = '编辑'
        this.show = true
        this.itemData = data
      } catch (error) {
        this.$snackbar.error(error)
      }
    },
    async handleCopy ({ id }) {
      try {
        const { data } = await getRoutersDetail({ id })
        const { id: _id, ...obj } = data
        this.title = '复制'
        this.show = true
        this.itemData = obj
      } catch (error) {
        this.$snackbar.error(error)
      }
    },
    // 导出菜单 数据有问题
    async exportMenu () {
      const date = new Date()
      const time = date.toLocaleString()
      try {
        this.downloadLoading = true
        const { data } = await exportMenu()
        const blob = new Blob([JSON.stringify(data, null, 2)], { type: 'application/json' })
        FileSaver.saveAs(blob, `菜单${time}`)
      } catch (error) {
        this.$snackbar.error(error)
      } finally {
        this.downloadLoading = false
      }
    },
    // 导入菜单
    async importMenu (file) {
      // console.log(file)
      const formData = new FormData()
      formData.append('file', file)
      this.uploadLoading = true
      try {
        await importMenu(formData)
        this.$snackbar.success('导入成功')
      } catch (error) {
        this.$snackbar.error(error)
      } finally {
        this.uploadLoading = false
      }
    }
  }
}
</script>

<style lang="scss" scoped>

</style>
