<template>
    <div class="roleManagement">
        <el-dialog v-model="dialogVisible" :title="dialogTitle" width="600">
            <el-form :model="formModel" ref="formRef">
                <template v-for="item in formColumnList" :key="item.prop">
                    <el-form-item :label="item.label" :rules="item.rule" :label-width="80" :prop="item.prop">
                        <template v-if="item.type === 'input'">
                            <el-input v-model="formModel[item.prop] as string" :placeholder="'请输入' + item.label"></el-input>
                        </template>
                        <template v-if="item.type === 'custom'">
                            <template v-if="item.prop === 'authList'">
                                <el-select v-model="formModel[item.prop]" multiple :placeholder="'请选择' + item.label">
                                    <el-option
                                        v-for="item in authorityListOptions"
                                        :key="item.id"
                                        :label="item.authorityName"
                                        :value="item.id"
                                    ></el-option>
                                </el-select>
                            </template>
                        </template>
                    </el-form-item>
                </template>
            </el-form>
            <template #footer>
                <el-button type="primary" @click="submitForm">提交</el-button>
                <el-button @click="cancelSubmitForm">取消</el-button>
            </template>
        </el-dialog>
        <el-container class="container">
            <el-header class="containerHeader">
                <div class="searchPart">
                    <el-input class="searchInput" v-model="searchInputValue" :placeholder="searchInputPlacehoder"></el-input>
                    <el-button type="primary" :icon="Search" class="defaultBtn" @click="searchClick">{{ t('management.search') }}</el-button>
                </div>
                <el-button type="primary" :icon="Plus" class="defaultBtn" @click="addClick">{{ t('management.add') }}</el-button>
            </el-header>
            <el-main class="containerMain">
                <el-table :data="tableData" class="tablePart">
                    <el-table-column
                        v-for="item in tableColumn"
                        :key="item.key"
                        :prop="item.prop"
                        :label="item.label"
                        :fixed="item.fixed"
                        :align="item.align ?? 'center'"
                    ></el-table-column>
                    <el-table-column fixed="right" label="操作" align="center">
                        <template #default="scope">
                            <div class="tableOperate">
                                <a @click="editForm(scope.row)">编辑</a>
                                <a>|</a>
                                <el-popconfirm title="确定删除么？" @confirm="delForm(scope.row)">
                                    <template #reference>
                                        <a>删除</a>
                                    </template>
                                </el-popconfirm>
                            </div>
                        </template>
                    </el-table-column>
                </el-table>
                <div class="mainFooter">
                    <el-pagination
                        v-model:current-page="currentPage"
                        v-model:page-size="currentPageSize"
                        :total="pageTotal"
                        :page-sizes="pagePagination"
                        background
                        :pager-count="7"
                        layout="prev, pager, next, jumper,sizes,total"
                    ></el-pagination>
                </div>
            </el-main>
        </el-container>
    </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import {
    ElContainer,
    ElHeader,
    ElMain,
    ElInput,
    ElButton,
    ElTable,
    ElTableColumn,
    ElDialog,
    ElForm,
    ElFormItem,
    ElMessage,
    ElPopconfirm,
    ElPagination,
} from 'element-plus'
import type { FormInstance } from 'element-plus'
import { Plus, Search } from '@element-plus/icons-vue'
import {
    tableDataType,
    tableColumnType,
    formDataEnum,
    formDataEnumKeyJointType,
    formColumnListType,
    formDataType,
    authorityDataListType,
    tableDataColumnTypeJointType,
    tableDataEnum,
} from './type'
import { useI18n } from 'vue-i18n'
import { getRoleListReq, changeRoleListReq, addRoleListReq, delRoleListReq, getAllRoleListReq } from '/@/api/backend/role/request'

const { t } = useI18n()
const dialogTitle = ref('新增角色')
const dialogVisible = ref(false)
const defaultFormModel = {
    id: '',
    authList: [],
    roleName: '',
    roleCode: '',
}
const formModel = ref<formDataType>(JSON.parse(JSON.stringify(defaultFormModel)))
const formColumnList: formColumnListType<formDataEnumKeyJointType>[] = [
    { type: 'input', label: formDataEnum['roleName'], prop: 'roleName', rule: [{ required: true, message: '请输入角色名称', trigger: 'blur' }] },
    { type: 'input', label: formDataEnum['roleCode'], prop: 'roleCode', rule: [{ required: true, message: '请输入角色编码', trigger: 'blur' }] },
    {
        type: 'custom',
        label: formDataEnum['authList'],
        prop: 'authList',
        rule: [{ required: true, message: '请选择权限列表', trigger: 'change' }],
    },
]
const authorityListOptions = ref<authorityDataListType[]>([])

const formRef = ref<FormInstance>()
const submitForm = () => {
    if (!formRef.value) return
    formRef.value.validate((valid) => {
        if (valid) {
            if (dialogTitle.value === '新增角色') {
                console.log(formModel.value)

                addRoleListReq(formModel.value)
                    .then((res) => {
                        if (res.success) {
                            getRoleList()
                            ElMessage.success('新增成功')
                            dialogVisible.value = false
                        } else {
                            ElMessage.error(res?.msg ?? '新增失败')
                        }
                    })
                    .catch((err) => {
                        ElMessage.error(err?.response?.data?.msg ?? '新增失败')
                    })
            } else if (dialogTitle.value === '编辑角色') {
                changeRoleListReq(formModel.value)
                    .then((res) => {
                        if (res.success) {
                            getRoleList()
                            ElMessage.success('编辑成功')
                            dialogVisible.value = false
                        } else {
                            ElMessage.error(res?.msg ?? '编辑失败')
                        }
                    })
                    .catch((err) => {
                        ElMessage.error(err?.response?.data?.msg ?? '编辑失败')
                    })
            }
        }
    })
}
const cancelSubmitForm = () => {
    dialogVisible.value = false
}

const searchInputPlacehoder = t('management.Query roles by name')
const searchInputValue = ref<string>('')
const searchClick = () => {
    currentPage.value = 1
    getRoleList(searchInputValue.value)
}

const tableColumn = ref<tableColumnType<tableDataColumnTypeJointType>[]>([
    {
        key: 'roleName-table',
        prop: 'roleName',
        label: tableDataEnum['roleName'],
    },
    {
        key: 'roleCode_table',
        prop: 'roleCode',
        label: tableDataEnum['roleCode'],
    },
    {
        label: tableDataEnum['listName'],
        prop: 'listName',
        key: 'authList-table',
    },
])
const tableData = computed(() => {
    const start = (currentPage.value - 1) * currentPageSize.value
    const end = start + currentPageSize.value
    return originData.value?.slice(start, end)
})

const pagePagination = [5, 10, 20, 30]
const currentPage = ref(1)
const currentPageSize = ref(pagePagination[0])
const pageTotal = ref(0)
const originData = ref<tableDataType<authorityDataListType>[]>()
const addClick = () => {
    // 新增角色
    dialogTitle.value = '新增角色'
    formModel.value = JSON.parse(JSON.stringify(defaultFormModel))
    formRef.value && formRef.value.resetFields()
    dialogVisible.value = true
}
const editForm = (formData: formDataType) => {
    formRef.value?.resetFields()
    const data = JSON.parse(JSON.stringify(formData))
    dialogTitle.value = '编辑角色'
    formModel.value = data
    dialogVisible.value = true
}
const delForm = (formData: formDataType) => {
    delRoleListReq({ id: formData.id })
        .then((res) => {
            if (res.success) {
                ElMessage.success('删除成功')
                getRoleList()
            } else {
                ElMessage.error(res?.msg ?? '删除失败')
            }
        })
        .catch((err) => {
            ElMessage.error(err?.response?.data?.msg ?? '删除失败')
        })
}

const getRoleList = (roleName = '') => {
    getRoleListReq({
        roleName,
    }).then((res) => {
        console.log(res)

        pageTotal.value = res.total
        originData.value = res.rows.map((item) => {
            return {
                roleCode: item.roleCode,
                roleName: item.roleName,
                listName: item.list.map((item) => item.authorityName).join(','),
                authList: item.list.map((item) => parseInt(item.id)),
                id: item.id,
                revision: item.revision,
            }
        })
    })
}
onMounted(() => {
    getRoleList()
    getAllRoleListReq().then((res) => {
        authorityListOptions.value = [...res.data]
    })
})
</script>

<style scoped lang="scss">
$defaultHeaderHeight: 60px;
$defaultMainHeight: calc(100% - 60px);
$paginationHeight: 32px;
.roleManagement {
    width: 100%;
    height: 100%;
    .container {
        width: 100%;
        height: 100%;
        .containerHeader {
            display: flex;
            align-items: center;
            justify-content: space-between;
            height: $defaultHeaderHeight;
            .searchInput {
                margin-right: 10px;
                width: 220px;
                height: 40px;
            }
            .defaultBtn {
                width: 88px;
                height: 40px;
            }
        }
        .containerMain {
            width: 100%;
            height: $defaultMainHeight;
            .tablePart {
                height: calc(100% - $paginationHeight);
                .tableOperate {
                    display: flex;
                    justify-content: center;
                    align-items: center;
                    a {
                        margin: 5px;
                        color: #0064aa;
                        font-weight: 600;
                        &:hover {
                            cursor: pointer;
                        }
                    }
                }
            }
            .mainFooter {
                display: flex;
                justify-content: right;
                background-color: #fff;
            }
        }
    }
}
</style>
