<template>
    <hc-card>
        <template #header>
            <div class="w-60">
                <hc-search-input v-model="searchForm.clientId" placeholder="请输入应用id关键词" @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
            ref="tableRef" :column="tableColumn" :datas="tableData" :loading="tableLoading"
            is-new is-check :check-style="{ width: 29 }" :index-style="{ width: 60 }"
            @selection-change="tableCheckChange"
        >
            <template #action="{ row }">
                <el-link type="warning" @click="editRowClick(row)">修改</el-link>
                <el-link v-del-com:[delRowClick]="row" type="danger">删除</el-link>
            </template>
        </hc-table>
        <template #action>
            <hc-pages :pages="searchForm" @change="pageChange" />
        </template>

        <!-- 新增/修改 -->
        <hc-dialog v-model="isDialogShow" widths="800px" is-footer-center :title="dialogTitle" @close="dialogClose">
            <el-form ref="formRef" :model="formModel" :rules="formRules" label-position="top" label-width="auto">
                <el-row :gutter="20">
                    <el-col :span="8">
                        <el-form-item label="应用名称：" prop="name">
                            <el-input v-model="formModel.name" clearable placeholder="请输入应用名称" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="应用id：" prop="clientId">
                            <el-input v-model="formModel.clientId" clearable placeholder="请输入应用id" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="应用密钥：" prop="clientSecret">
                            <el-input v-model="formModel.clientSecret" clearable placeholder="请输入应用密钥" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <el-form-item label="授权类型：" prop="authorizedGrantTypes">
                            <div class="form-item-div">
                                <el-checkbox-group v-model="formModel.authorizedGrantTypes" size="large">
                                    <el-checkbox label="refresh_token" />
                                    <el-checkbox label="password" />
                                    <el-checkbox label="authorization_code" />
                                    <el-checkbox label="captcha" />
                                    <el-checkbox label="social" />
                                </el-checkbox-group>
                            </div>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="授权范围：" prop="scope">
                            <el-input v-model="formModel.scope" clearable placeholder="请输入授权范围" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="令牌秒数：" prop="accessTokenValidity">
                            <el-input-number v-model="formModel.accessTokenValidity" :min="1" block controls-position="right" placeholder="请输入令牌秒数" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="刷新秒数：" prop="refreshTokenValidity">
                            <el-input-number v-model="formModel.refreshTokenValidity" :min="1" block controls-position="right" placeholder="请输入刷新秒数" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="资源集合：">
                            <el-input v-model="formModel.resourceIds" clearable placeholder="请输入资源集合" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="权限：">
                            <el-input v-model="formModel.authorities" clearable placeholder="请输入权限" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="自动授权：">
                            <el-input v-model="formModel.autoapprove" clearable placeholder="请输入自动授权" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <el-form-item label="回调地址：" prop="webServerRedirectUri">
                            <el-input v-model="formModel.webServerRedirectUri" clearable placeholder="请输入回调地址" />
                        </el-form-item>
                    </el-col>
                </el-row>
            </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>
    </hc-card>
</template>

<script setup>
import { nextTick, onActivated, ref } from 'vue'
import { arrToId, formValidate, getArrValue } from 'js-fast-way'
import { reloadPage } from '~uti/tools'
import { HcDelMsg } from 'hc-vue3-ui'
import mainApi from '~api/system/client'

defineOptions({
    name: 'Client',
})

//激活
onActivated(() => {
    searchForm.value.current = 1
    getTableData()
})

//搜索表单
const searchForm = ref({ clientId: null, current: 1, size: 30, total: 0 })

//搜索
const searchClick = () => {
    searchForm.value.current = 1
    getTableData()
}

//分页
const pageChange = ({ current, size }) => {
    searchForm.value.current = current
    searchForm.value.size = size
    getTableData()
}

//表格数据
const tableRef = ref(null)
const tableColumn = ref([
    { key: 'name', name: '应用名称' },
    { key: 'clientId', name: '应用ID' },
    { key: 'clientSecret', name: '应用密钥' },
    { key: 'scope', name: '授权范围' },
    { key: 'accessTokenValidity', name: '令牌秒数' },
    { key: 'refreshTokenValidity', name: '刷新秒数' },
    { key: 'action', name: '操作', width: 100, align: 'center' },
])

//获取表格数据
const tableLoading = ref(true)
const tableData = ref([])
const getTableData = async () => {
    tableData.value = []
    tableLoading.value = true
    const { error, code, data } = await mainApi.page(searchForm.value)
    tableLoading.value = false
    if (!error && code === 200) {
        tableData.value = getArrValue(data['records'])
        searchForm.value.total = data['total']
    } else {
        tableData.value = []
        searchForm.value.total = 0
    }
}

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

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

//菜单表单
const formRef = ref(null)
const formModel = ref({})
const formRules = {
    name: {
        required: true,
        trigger: 'blur',
        message: '请输入应用名称',
    },
    clientId: {
        required: true,
        trigger: 'blur',
        message: '请输入应用id',
    },
    clientSecret: {
        required: true,
        trigger: 'blur',
        message: '请输入应用密钥',
    },
    authorizedGrantTypes: {
        required: true,
        trigger: 'blur',
        message: '请选择授权类型',
    },
    scope: {
        required: true,
        trigger: 'blur',
        message: '请输入授权范围',
    },
    accessTokenValidity: {
        required: true,
        trigger: 'blur',
        message: '请输入令牌秒数',
    },
    refreshTokenValidity: {
        required: true,
        trigger: 'blur',
        message: '请输入刷新秒数',
    },
    webServerRedirectUri: {
        required: true,
        trigger: 'blur',
        message: '请输入回调地址',
    },
}

//新增
const addClick = () => {
    dialogTitle.value = '新增应用'
    formModel.value = {
        category: 1, isOpen: 1, isLayout: 1, isShowButton: 1,
        sort: 1,
    }
    //显示表单弹窗
    nextTick(() => {
        isDialogShow.value = true
    })
}

//修改菜单
const editRowClick = (row) => {
    formModel.value = {}
    dialogTitle.value = '修改应用'
    formModel.value = { ...row }
    formModel.value.authorizedGrantTypes = row.authorizedGrantTypes.split(',')
    //显示表单弹窗
    nextTick(() => {
        isDialogShow.value = true
    })
}

//删除菜单
const delRowClick = async ({ item }, resolve) => {
    const { code, msg } = await mainApi.del(item.id)
    if (code === 200) {
        resolve()
        window.$message.success('删除成功')
        reloadPage()
    } else {
        resolve()
        window.$message.error(msg ?? '删除失败')
    }
}

//批量删除菜单
const delClick = () => {
    const rows = tableCheckKeys.value
    if (rows.length <= 0) {
        window.$message.warning('请选择要删除的菜单')
        return false
    }
    //确认删除
    HcDelMsg(async (resolve) => {
        //发起请求
        const ids = arrToId(rows)
        const { code, msg } = await mainApi.del(ids)
        //关闭弹窗的回调
        resolve()
        //处理结果
        if (code === 200) {
            window.$message.success('删除成功')
            reloadPage()
        } else {
            window.$message.error(msg ?? '删除失败')
        }
    })
}

//提交表单
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.authorizedGrantTypes = form.authorizedGrantTypes.join(',')
    //发起请求
    const { error, code, msg } = await mainApi.submit(form)
    submitLoading.value = false
    if (!error && code === 200) {
        window?.$message?.success('操作成功')
        reloadPage()
    } else {
        window?.$message?.error(msg ?? '操作失败')
    }
}

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