<template>
    <hc-card>
        <template #header>
            <div class="w-40">
                <el-select v-model="searchForm.tenantId" placeholder="选择所属租户" filterable clearable block>
                    <el-option v-for="item in tenantData" :key="item.tenantId" :label="item.name" :value="item.tenantId" />
                </el-select>
            </div>
            <div class="ml-2 w-64">
                <hc-search-input v-model="searchForm.roleName" placeholder="请输入角色名称关键词" @search="searchClick" />
            </div>
        </template>
        <template #extra>
            <el-button hc-btn type="primary" @click="addClick">新增</el-button>
            <el-button hc-btn type="danger" @click="delClick">删除</el-button>
        </template>
        <hc-table
            :column="tableColumn" :datas="tableData" :loading="tableLoading" is-check
            :is-index="false" :check-style="{ width: 29 }" is-children @selection-change="tableCheckChange"
        >
            <template #tenantId="{ row }">{{ getTenantName(row) }}</template>
            <template #action="{ row }">
                <el-link type="primary" @click="authRowClick(row)">权限设置</el-link>
                <el-link type="warning" @click="editRowClick(row)">修改</el-link>
                <el-link type="success" @click="addRowClick(row)">添加</el-link>
                <el-link v-del-com:[delRowClick]="row" type="danger">删除</el-link>
            </template>
        </hc-table>

        <!-- 新增/修改 -->
        <hc-dialog v-model="isDialogShow" widths="400px" is-footer-center :title="iconDialogTitle" @close="dialogClose">
            <el-form ref="formRef" :model="formModel" :rules="formRules" label-position="top" label-width="auto">
                <el-form-item label="角色名称：" prop="roleName">
                    <el-input v-model="formModel.roleName" clearable />
                </el-form-item>
                <el-form-item label="角色别名：" prop="roleAlias">
                    <el-input v-model="formModel.roleAlias" clearable />
                </el-form-item>
                <el-form-item label="上级角色：">
                    <el-tree-select
                        v-model="formModel.parentId" :disabled="isChildForm" :data="levelData" :props="levelDataProps"
                        clearable filterable check-strictly block :render-after-expand="false"
                    />
                </el-form-item>
                <el-form-item label="角色排序：" prop="sort">
                    <el-input-number v-model="formModel.sort" :min="1" block controls-position="right" />
                </el-form-item>
            </el-form>
            <template #footer>
                <el-button hc-btn @click="dialogClose">取消</el-button>
                <el-button hc-btn type="primary" :loading="submitLoading" @click="dialogSubmit">提交</el-button>
            </template>
        </hc-dialog>
        <!-- 权限配置 -->
        <HcRoleAuth v-model="isRoleAuthShow" :info="roleAuthRow" @close="roleAuthClose" />
    </hc-card>
</template>

<script setup>
import { nextTick, onActivated, ref } from 'vue'
import { arrToId, formValidate, getArrValue, isNullES } from 'js-fast-way'
import { HcDelMsg } from 'hc-vue3-ui'
import HcRoleAuth from './modules/role/auth.vue'
import tenantApi from '~api/system/tenant'
import mainApi from '~api/authority/role'

//激活
onActivated(() => {
    getDataApi()
})

const getDataApi = async () => {
    await getTenantData()
    searchClick()
}

//搜索表单
const searchForm = ref({ tenantId: null, roleName: '' })

//所属租户
const tenantData = ref([])
const getTenantData = async () => {
    let newArr = []
    const { data } = await tenantApi.getSelect()
    const res = getArrValue(data)
    for (let i = 0; i < res.length; i++) {
        newArr.push({
            id: res[i]['id'],
            name: res[i]['tenantName'],
            tenantId: res[i]['tenantId'],
        })
    }
    tenantData.value = newArr
}
const getTenantName = ({ tenantId }) => {
    if (isNullES(tenantId)) return '-'
    const item = tenantData.value.find((item) => item.tenantId === tenantId)
    if (isNullES(item)) return tenantId
    return item.name ?? tenantId
}

//搜索
const searchClick = () => {
    getTableData()
}

//表格数据
const tableColumn = ref([
    { key: 'roleName', name: '角色名称' },
    { key: 'tenantId', name: '所属租户' },
    { key: 'roleAlias', name: '角色别名' },
    { key: 'sort', name: '排序' },
    { key: 'action', name: '操作', width: 200, align: 'center' },
])
const tableData = ref([])

//获取表格数据
const tableLoading = ref(true)
const getTableData = async () => {
    tableData.value = []
    tableLoading.value = true
    const { data } = await mainApi.page(searchForm.value)
    tableData.value = getArrValue(data)
    tableLoading.value = false
}

//表格被选择
const tableCheckKeys = ref([])
const tableCheckChange = (rows) => {
    tableCheckKeys.value = rows
}

//上级菜单
const levelDataProps = { label: 'title' }
const levelData = ref([])
const getlevelData = async () => {
    const { data } = await mainApi.getRoleTreeById()
    levelData.value = getArrValue(data)
}

//新增/修改 弹窗
const isDialogShow = ref(false)
const iconDialogTitle = ref('')

//表单
const formRef = ref(null)
const formModel = ref({})
const formRules = {
    roleName: {
        required: true,
        trigger: 'blur',
        message: '请输入角色名称',
    },
    roleAlias: {
        required: true,
        trigger: 'blur',
        message: '请输入角色别名',
    },
    sort: {
        required: true,
        trigger: 'blur',
        message: '请输入菜单排序',
    },
}


//新增
const addClick = () => {
    isChildForm.value = false
    iconDialogTitle.value = '新增角色'
    formModel.value = { parentId: null, sort: 1 }
    //显示表单弹窗
    nextTick(() => {
        isDialogShow.value = true
        getlevelData()
    })
}

//修改
const editRowClick = (row) => {
    isChildForm.value = false
    formModel.value = {}
    iconDialogTitle.value = '修改角色'
    formModel.value = { ...row }
    //显示表单弹窗
    nextTick(() => {
        isDialogShow.value = true
        getlevelData()
    })
}

//新增子项
const isChildForm = ref(false)
const addRowClick = (row) => {
    isChildForm.value = true
    iconDialogTitle.value = '新增子项'
    formModel.value = { parentId: row.id, sort: 1 }
    //显示表单弹窗
    nextTick(() => {
        isDialogShow.value = true
        getlevelData()
    })
}

//提交表单
const submitLoading = ref(false)
const dialogSubmit = async () => {
    const formRes = await formValidate(formRef.value)
    if (!formRes) return false
    submitLoading.value = true
    //处理数据
    const form = formModel.value
    form.parentId = form.parentId ?? '0'
    form.tenantId = form.tenantId ?? ''
    //发起请求
    const { isRes } = await mainApi.submit(form)
    submitLoading.value = false
    if (!isRes) return
    dialogClose()
    window?.$message?.success('操作成功')
    getTableData()
}

//关闭弹窗
const dialogClose = () => {
    isDialogShow.value = false
    submitLoading.value = false
    isChildForm.value = false
    formModel.value = {}
}

//删除
const delRowClick = async ({ item }, resolve) => {
    const { isRes } = await mainApi.del(item.id)
    resolve() //关闭弹窗
    if (!isRes) return
    window.$message.success('删除成功')
    getTableData().then()
}


//批量删除
const delClick = () => {
    const rows = tableCheckKeys.value
    if (rows.length <= 0) {
        window.$message.warning('请选择要删除的数据')
        return false
    }
    //确认删除菜单
    HcDelMsg(async (resolve) => {
        //发起请求
        const ids = arrToId(rows)
        const { isRes } = await mainApi.del(ids)
        resolve() //关闭弹窗
        if (!isRes) return
        window.$message.success('删除成功')
        getTableData().then()
    })
}

//权限配置弹窗
const isRoleAuthShow = ref(false)
const roleAuthRow = ref({})
const authRowClick = (row) => {
    roleAuthRow.value = row
    nextTick(() => {
        isRoleAuthShow.value = true
    })
}

//关闭权限配置弹窗
const roleAuthClose = () => {
    isRoleAuthShow.value = false
    roleAuthRow.value = {}
}
</script>
