<!--  -->
<template>
    <div class="hc-layout-box role-page">
        <hc-card :scrollbar="false" action-size="lg">
            <template #extra>
                <el-button color="#20C98B" type="primary" @click="addClick">
                    <hc-icon name="add" class="text-white" />
                    <span class="text-white">新增</span>
                </el-button>
                <el-button color="#FF6C6C" :disabled="tableCheckedKeys.length === 0" @click="batchDelClick">
                    <hc-icon name="delete-bin-2" class="text-white" />
                    <span class="text-white">删除</span>
                </el-button>
            </template>
            <template #header>
                <div class="relative w-[300px]">
                    <hc-search-input v-model="searchForm.roleName" color="#151921" text="搜索" @search="searchClick" />
                </div>
            </template>
            <hc-table
                :check-style="{ fixed: true, width: 29 }" :index-style="{ fixed: true, width: 60 }" is-check is-index is-children
                class="role-page-table" :column="tableColumn" :datas="tableData" @selection-change="tableSelectionChange"
            >
                <template #action="{ row }">
                    <el-link type="success" @click="rowEditClick(row)">
                        <hc-icon name="edit" />编辑
                    </el-link>
                    <el-link type="success" @click="rowDelClick(row)">
                        <hc-icon name="delete-bin-2" />删除
                    </el-link>
                </template>
            </hc-table>
            <template #action>
                <hc-pages :pages="searchForm" @change="pageChange" />
            </template>
        </hc-card>
    </div>
    <hc-dialog v-model="addModal" :title="modalTitle" widths="50rem" :loading="addsaveLoading" @save="modalSave">
        <div class="hc-flex">
            <hc-icon name="user" style="font-size: 18px;" class="font-bold" />
            <span class="ml-1 font-bold">基础信息</span>
        </div>
        <el-divider style="margin-top: 10px;" />
        <el-form ref="formRef" :inline="true" :model="baseForm" label-width="auto" :rules="baseFormRules">
            <div class="hc-form-item">
                <el-form-item label="角色名称:" prop="roleName">
                    <el-input v-model="baseForm.roleName" placeholder="请输入" clearable />
                </el-form-item>
            </div>
        </el-form>
        <div class="hc-flex mt-4">
            <hc-icon name="user-settings" style="font-size: 18px;" class="font-bold" />
            <span class="ml-1 font-bold">权限设置</span>
        </div>
        <el-divider class="mt-[10px]" />
        <el-tree ref="treeRef" style="max-width: 600px" :data="roleTreedata" show-checkbox node-key="id" highlight-current :props="defaultProps" :default-checked-keys="defaultCheckedKeys" />
    </hc-dialog>
</template>

<script setup>
import { onMounted, ref } from 'vue'
import { HcDelMsg } from 'hc-vue3-ui'
import { getList, getRole, grant, remove } from '~api/system/role.js'
import { arrToId, formValidate, getArrValue } from 'js-fast-way'
import menuApi from '~api/system/menu'

onMounted(()=>{
    getTableData()
})

const tableColumn = [
   { key: 'roleName', name: '角色名称' },
   { key: 'action', name: '操作', align:'center', width: 200 },
]
const tableData = ref([])

const addModal = ref(false)
const modalTitle = ref('新增')
const addClick = ()=>{
modalTitle.value = '新增'
   addModal.value = true
   baseForm.value = {}
   defaultCheckedKeys.value = []
   getRoleTreedata()
}
const baseForm = ref({ roleName:'' })
const baseFormRules = {
    roleName: {
        required: true,
        trigger: 'blur',
        message: '请输入角色名称',
    },
}
const tableCheckedKeys = ref([])
 //多选事件
const tableSelectionChange = (rows) => {
    tableCheckedKeys.value = rows
}
//搜索表单
//搜索表单
const searchForm = ref({ roleName: null, current: 1, size: 20 })
const tableLoading = ref(false)
const getTableData = async () => {
    tableLoading.value = true
    const { error, code, data } = await getList({
        ...searchForm.value,
    })
    tableLoading.value = false
    if (!error && code === 200) {
        tableData.value = getArrValue(data)
    } else {
        tableData.value = []
    }

}
const searchClick = () => {
    getTableData()
}
//分页被点击
const pageChange = ({ current, size }) => {
    searchForm.value.current = current
    searchForm.value.size = size
    getTableData()
}
const rowEditClick = (row)=>{
    modalTitle.value = '编辑'
    addModal.value = true
    baseForm.value = { ...row }
    getRoleDetail(row.id)
    getRoleTreedata()
}
const getRoleDetail = async (id)=>{
    const { error, code, data } = await getRole(id)
    if (!error && code === 200) {
        defaultCheckedKeys.value = data['menu']
    } else {
        defaultCheckedKeys.value = []
    }
}
const rowDelClick = (row)=>{
    HcDelMsg( async ( resolve) => {
        await removeRole(row.id)
        resolve() //关闭弹窗的回调
    })
}
const batchDelClick = ()=>{
    let ids = arrToId(tableCheckedKeys.value)
    HcDelMsg(async (resolve) => {
        await removeRole(ids)
        resolve() //关闭弹窗的回调
    })
}
const removeRole = async (ids) => {
    const { error, code, msg } = await remove(ids)
    if (!error && code === 200) {
        window?.$message?.success('删除成功')
       getTableData()
    } else {
        window.$message.error(msg ?? '操作失败')
    }
}
const treeRef = ref(null)
const defaultProps = {
  children: 'children',
  label: 'title',
}
const defaultCheckedKeys = ref([])
const roleTreedata = ref([])
const getRoleTreedata = async () => {
    const { error, code, data } = await menuApi.getMenuTree()
    if (!error && code === 200) {
      roleTreedata.value = getArrValue(data)
    } else {
      roleTreedata.value = []
    }
}
const addsaveLoading = ref(false)
const formRef = ref(null)

const modalSave = async ()=>{
    let menuIds = treeRef.value.getCheckedKeys()
    const isValidate = await formValidate(formRef.value)
    if (!isValidate) return false
    addsaveLoading.value = true
    const { error, code, msg } = await grant({
        roleName:baseForm.value.roleName,
        roleIds:[baseForm.value.id],
        menuIds:menuIds,
    })
    //判断状态
    addsaveLoading.value = false
    if (!error && code === 200) {
        window?.$message?.success(msg)
        addModal.value = false
        getTableData()
    } else {
        window.$message.error(msg ?? '操作失败')
    }
}
</script>

 <style lang='scss' scoped>
.hc-layout-box{
    position: relative;
    height: 100%;
    width: 100%;
}
</style>
