<template>
  <div class="pa-3 white">
    <m-search :items="searchItems" v-model="searchValues" class="mb-3" @search="search" @reset="search">
      <template #button>
        <el-button type="primary" icon="el-icon-plus" @click="onAdd">
          新增
        </el-button>
      </template>
    </m-search>
    <MTable
      v-loading="loading"
      :items="items"
      :headers="headers"
      :page-size="pageInfo.size"
      :page-current="pageInfo.current"
      :total="pageInfo.total"
      @page-change="handlePageChange"
    >
      <template #createTime="scope">
        {{ dateFormat(scope.row.createTime) }}
      </template>
      <template #actions="scope">
        <m-button type="primary" text @click="onEdit(scope.row)">编辑</m-button>
        <m-button type="primary" text @click="onMenu(scope.row)">菜单权限</m-button>
        <m-button type="primary" text @click="onPermission(scope.row)">数据权限</m-button>
        <m-button type="danger" text @click="onDelete(scope.row)">删除</m-button>
      </template>
    </MTable>
    <MDialog ref="dialog" :title="itemData.id ? '编辑角色' : '新增角色'" @sure="handleSave">
      <MForm ref="roleForm" :items="roleFormItems" v-model="roleFormValue"></MForm>
    </MDialog>
    <MDialog ref="menuDialog" title="菜单权限编辑" @sure="handleSaveMenu">
      <MForm ref="menuForm">
        <el-form-item label="角色名称">
          <el-tag>{{ itemData.roleName }}</el-tag>
        </el-form-item>
        <el-form-item label="菜单权限" required>
          <m-card shadow="never">
            <el-tree
              ref="menuTree"
              :data="menuData"
              show-checkbox
              node-key="id"
              :props="{
                children: 'children',
                label: 'label'
              }"
            >
            </el-tree>
          </m-card>
        </el-form-item>
      </MForm>
    </MDialog>
    <MDialog ref="dataDialog" title="数据权限编辑" @sure="handleSaveData">
      <MForm ref="roleForm" :items="roleFormItems" v-model="roleFormValue"></MForm>
    </MDialog>
  </div>
</template>

<script>
import {
  getRoleList,
  deleteRole,
  getRoleDetails,
  saveRole,
  getMenuTree,
  saveDataPermission
} from '@/api/menu'
import { dateFormat } from '@/utils/date'
export default {
  name: 'role-manage-role',
  data () {
    return {
      itemData: {},
      roleFormItems: [
        {
          label: '角色名称',
          prop: 'roleName',
          type: 'input',
          rules: [
            { required: true, message: '请输入角色名称', trigger: 'blur' }
          ]
        }
      ],
      roleFormValue: {
        roleName: null
      },
      menuFormItems: [
        {
          label: '角色名称'
        }
      ],
      searchValues: {
        roleName: null
      },
      searchItems: [
        {
          label: '角色名称',
          prop: 'roleName',
          type: 'input'
        }
      ],
      menuData: [],
      itemDataPermission: {},
      show: false,
      showMenu: false,
      headers: [
        { label: '角色', align: 'start', prop: 'roleName' },
        { label: '创建时间', align: 'start', prop: 'createTime' },
        { label: '操作', align: 'start', prop: 'actions', fixed: 'right' }
      ],
      items: [],
      total: 0,
      pageInfo: {
        size: 10,
        current: 1
      },
      orders: [],
      loading: false
    }
  },
  // computed: {
  //   defaultCheckedKeys () {
  //     if (Object.keys(this.itemData).length === 0) {
  //       return []
  //     }
  //     return this.itemData.menuIds.split(',').map(e => +e)
  //   }
  // },
  created () {
    this.getMenu()
  },
  methods: {
    async getMenu () {
      try {
        const { data } = await getMenuTree({})
        this.menuData = data.routes
        this.initPage()
      } catch (error) {
        this.$message.error(error)
      }
    },
    async initPage () {
      this.loading = true
      try {
        const { data } = await getRoleList({ ...this.pageInfo, orders: this.orders, entity: this.searchValues })
        this.items = data.records
        this.total = data.total
      } catch (error) {
        this.$message.error(error)
      } finally {
        this.loading = false
      }
    },
    async getDetails (roleId) {
      try {
        const { data } = await getRoleDetails({ roleId })
        this.itemData = data
        Object.assign(this.itemData, data)
        return data
      } catch (error) {
        this.$message.error(error)
      }
    },
    onAdd () {
      this.roleFormValue = {
        roleName: null
      }
      this.itemData = {}
      this.$refs.dialog.open()
    },
    async onEdit (item) {
      const data = await this.getDetails(item.id)
      if (!data) {
        return
      }
      this.roleFormValue = {
        roleName: data.roleName
      }
      this.itemData = data
      this.$refs.dialog.open()
    },
    async onMenu (item) {
      const data = await this.getDetails(item.id)
      if (!data) {
        return
      }
      this.itemData = data
      this.$refs.menuDialog.open()
      this.$nextTick(() => {
        this.$refs.menuTree.setCheckedKeys(data.menuIds.split(',').map(e => +e))
      })
    },
    async onPermission (item) {
      const data = await this.getDetails(item.id)
      if (!data) {
        return
      }
      this.itemData = data
      this.$refs.dataDialog.open()
    },
    onDelete (item) {
      this.$confirm('是否确定删除该选项', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          await deleteRole({ id: item.id })
          this.$message.success('删除成功')
          this.initPage()
        } catch (error) {
          this.$message.error(error)
        }
      }).catch(_ => {})
    },
    handleData (item) {
      this.itemDataPermission = item
      this.showMenu = true
    },
    handleSave () {
      this.$refs.roleForm.validate(async (valid) => {
        if (!valid) {
          return
        }
        const obj = {
          ...this.roleFormValue,
          menuIds: '-9999'
        }
        try {
          await saveRole(obj)
          this.$message.success(this.itemData.id ? '编辑成功' : '添加成功')
          this.$refs.dialog.close()
          this.initPage()
        } catch (error) {
          this.$message.error(error)
        }
      })
    },
    async handleSaveMenu () {
      const menuIds = this.$refs.menuTree.getCheckedKeys(true)
      if (!menuIds.length) {
        this.$message.warning('请选择菜单')
        return
      }
      const obj = {
        id: this.itemData.id,
        menuIds: menuIds.join(',')
      }
      try {
        await saveRole(obj)
        this.$message.success('保存成功')
        this.$refs.menuDialog.close()
        this.initPage()
      } catch (error) {
        this.$message.error(error)
      }
    },
    async handleSaveData () {
      try {
        await saveDataPermission({
          roleId: this.itemData.id
          // menuIds: menuIds.join(',')
        })
        this.$message.success('保存成功')
        this.showMenu = false
        this.initPage()
      } catch (error) {
        this.$message.error(error)
      }
    },
    handlePageChange (page) {
      this.pageInfo.current = page
      this.initPage()
    },
    dateFormat (str) {
      const date = new Date(+str * 1000)
      return dateFormat('YYYY-mm-dd HH:MM:SS', date)
    },
    handleSort (val) {
      this.orders = val
      this.initPage()
    },
    search (val) {
      Object.assign(this.searchValues, val)
      this.pageInfo.current = 1
      this.initPage()
    }
  }
}
</script>

<style lang="scss" scoped>

</style>
