<template>
  <div class="app-container">
    <el-button type="primary" icon="plus" size="small" style="margin-bottom: 10px" @click="addRole">添加
    </el-button>
    <el-table :data="roleData" border fit highlight-current-row>
      <el-table-column align="center" label="角色编码" prop="roleCode" width="400" />
      <el-table-column align="center" label="角色名称" prop="roleName" width="400" />
      <el-table-column align="center" label="角色描述" prop="roleDesc" />
      <el-table-column align="center" label="创建时间" prop="fdate" />
      <el-table-column align="center" label="操作" width="200">
        <template #default="scope">
          <el-link type="primary" :underline="false" @click="drawerData.handleShow(scope)" style="margin-right: 10px;">
            授权</el-link>
          <el-link type="primary" :underline="false" @click="editRole(scope.row)" style="margin-right: 10px;">
            编辑</el-link>
          <el-link type="primary" :underline="false" @click="deleteRole(scope.row.id)">删除</el-link>

        </template>
      </el-table-column>
    </el-table>
    <pagination :page-data="roleQuery" :total="total" @size-change="sizeChange" @current-change="currentChange" />

    <el-drawer v-model="drawerData.drawerShow" title="授权" direction="rtl" :before-close="drawerData.handleClose">
      <el-tree ref="tree" :data="drawerData.treeData" node-key="key" :default-expand-all="true" :check-strictly="true"
        show-checkbox />
      <el-button type="primary" @click="drawerData.onSubmit">保存</el-button>
      <el-button @click="drawerData.handleClose">取消</el-button>
    </el-drawer>
  </div>

  <el-drawer v-model="showDialog" size="25%" :title="title" @before-close="handleClose">
    <el-form :model="drawerformData" ref="roleFormRef" :rules="rules" label-width="100px">
      <el-form-item v-for="(item, index) in tableTitle" :key="index" :label="item.label" :prop="item.prop">
        <el-input v-model="drawerformData[item.prop]" :type="item.type" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button type="primary" @click="onSubmit">保存</el-button>
      <el-button @click="handleClose">取消</el-button>
    </template>
  </el-drawer>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue'
import { Scope } from '@/table/type'
import { getQueryRoleMenu, getQueryTreeList, saveRole, getRoleList, deleteRoleList, editRoleList, addRoleList } from '@/services/api/role/roleAPI'
import type { ElTree } from 'element-plus';
import { ElNotification, ElMessageBox, ElMessage } from 'element-plus'
import pagination from '@/components/pagination/index.vue'

const roleFormRef = ref()
const showDialog = ref(false)
let title = ref('新增')
let total = ref(0)
const roleQuery = ref({
  pageNo: 1,
  pageSize: 10
})
const drawerformData = ref({
  id: '',
  roleCode: '',
  roleName: '',
  roleDesc: ''
} as any)
const roleData = ref()
const tableTitle = ref([
  {
    label: '角色编码',
    prop: 'roleCode',
    type: 'input'
  },
  {
    label: '角色名称',
    prop: 'roleName',
    type: 'input'
  },
  {
    label: '角色描述',
    prop: 'roleDesc',
    type: 'input',
    inputType: 'textarea'
  }
])
const tree = ref<InstanceType<typeof ElTree>>()
const rules = reactive({
  roleCode: [
    { required: true, message: '请输入角色编码', trigger: 'blur' }
  ],
  roleName: [
    { required: true, message: '请输入角色名称', trigger: 'blur' }
  ]
})
const permissionParams: { permissionIds: Array<any>, lastPermissionIds: Array<any>, roleId: string } = {
  permissionIds: [],
  lastPermissionIds: [],
  roleId: ''
}
// 授权抽屉数据
const drawerData = reactive({
  drawerShow: false,
  treeData: [],
  handleClose: () => {
    drawerData.drawerShow = false
  },
  handleShow: (scope: Scope) => {
    drawerData.drawerShow = true
    permissionParams.roleId = scope.row.id
    getQueryRoleMenu({ id: scope.row.id }).then((res: any) => {
      if (res.code === 200) {
        permissionParams.lastPermissionIds = res.data
        tree.value!.setCheckedKeys(res.data as Node[], true)
      }
    })
  },
  onSubmit: () => {
    permissionParams.permissionIds = tree.value!.getCheckedKeys(false)
    saveRole(permissionParams).then((res: any) => {
      if (res.code === 200) {
        drawerData.handleClose()
        ElNotification({
          title: '温馨提示',
          message: '保存成功！',
          type: 'success'
        })
      }
    })
  }
})

let sizeChange = (val: number) => {
  roleQuery.value.pageSize = val
  init()
}

let currentChange = (val: number) => {
  roleQuery.value.pageNo = val
  init()
}

let onSubmit = () => {
  roleFormRef.value?.validate((valid: any, fields: any) => {
    if (valid) {
      if (title.value === '新增') {
        addRoleList(drawerformData.value).then((res: any) => {
          if (res.code === 200) {
            init()
            handleClose()
            ElMessage({
              type: 'success',
              message: res.msg,
            })
          }
        })
      } else {
        editRoleList(drawerformData.value).then((res: any) => {
          if (res.code === 200) {
            init()
            handleClose()
            ElMessage({
              type: 'success',
              message: res.msg,
            })
          }
        })
      }
    } else {
      console.log(fields);
    }
  })
}

let addRole = () => {
  showDialog.value = true
  title.value = '新增'
}
let editRole = (row: any) => {
  showDialog.value = true
  title.value = '编辑'
  drawerformData.value = row
}
let deleteRole = (id: number) => {
  ElMessageBox.confirm(
    '确认删除?',
    '提示',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(() => {
      deleteRoleList(id).then((res: any) => {
        if (res.code === 200) {
          init()
          ElMessage({
            type: 'success',
            message: res.data,
          })
        }
      })
    }).catch(() => { return false })
}

let handleClose = () => {
  drawerformData.value = {
    id: '',
    roleCode: '',
    roleName: '',
    roleDesc: ''
  }
  showDialog.value = false
}

getQueryTreeList().then((res: any) => {
  if (res.code === 200) {
    drawerData.treeData = res.data.treeList
  }
})

let init = () => {
  getRoleList(roleQuery.value).then((res: any) => {
    if (res.code === 200) {
      roleData.value = res.data.records
      total.value = res.data.total
    }
    console.log(roleData.value);
  })
}
init()
</script>

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