<script lang="ts">
export default {
    name: "agentApply",
};
</script>

<script setup lang="ts">
import { onMounted, reactive, ref, toRefs } from "vue";
import { ElForm, ElMessage, ElMessageBox } from "element-plus";
import { Search, Refresh } from "@element-plus/icons-vue";
import {
    agentApplyPageQuery,
    agentApplyPass,
    agentApplyReject,
} from "@/api/invitation/index";
import {
    AgentApplyQueryParam,
    AgentApplyItem,
} from "@/types/api/invitation/index";

const queryFormRef = ref(ElForm);
const rejectFormRef = ref(ElForm);

const AUDIT_STATUS_MAP: Record<number, { label: string; type: string }> = {
    0: { label: "待审核", type: "warning" },
    1: { label: "审核拒绝", type: "danger" },
    2: { label: "审核通过", type: "success" },
};

const state = reactive({
    loading: false,
    queryParams: {
        pageNo: 1,
        pageSize: 15,
        keyword: "",
        auditStatus: "" as number | "",
    } as AgentApplyQueryParam,
    list: [] as AgentApplyItem[],
    total: 0,
    detailVisible: false,
    currentDetail: null as AgentApplyItem | null,
    rejectVisible: false,
    rejectForm: {
        id: 0,
        rejectReason: "",
    },
    rejectRules: {
        rejectReason: [{ required: true, message: "请填写拒绝原因", trigger: "blur" }],
    },
});

const {
    loading,
    queryParams,
    list,
    total,
    detailVisible,
    currentDetail,
    rejectVisible,
    rejectForm,
    rejectRules,
} = toRefs(state);

function handleQuery() {
    state.loading = true;
    agentApplyPageQuery(state.queryParams)
        .then(({ data }: any) => {
            state.list = data.content;
            state.total = data.totalElements;
        })
        .finally(() => {
            state.loading = false;
        });
}

function resetQuery() {
    queryFormRef.value.resetFields();
    handleQuery();
}

function openDetail(row: AgentApplyItem) {
    state.currentDetail = row;
    state.detailVisible = true;
}

function handlePass(row: AgentApplyItem) {
    ElMessageBox.confirm(`确认通过【${row.email}】的代理商申请？`, "审核确认", {
        confirmButtonText: "确认通过",
        cancelButtonText: "取消",
        type: "warning",
    }).then(() => {
        agentApplyPass(row.id).then((res: any) => {
            if (res.code === 0) {
                ElMessage.success("审核通过");
                handleQuery();
            } else {
                ElMessage.error(res.message || "操作失败");
            }
        });
    });
}

function openReject(row: AgentApplyItem) {
    state.rejectForm.id = row.id;
    state.rejectForm.rejectReason = "";
    state.rejectVisible = true;
}

function submitReject() {
    rejectFormRef.value.validate((valid: boolean) => {
        if (!valid) return;
        agentApplyReject(state.rejectForm.id, state.rejectForm.rejectReason).then(
            (res: any) => {
                if (res.code === 0) {
                    ElMessage.success("已拒绝申请");
                    state.rejectVisible = false;
                    handleQuery();
                } else {
                    ElMessage.error(res.message || "操作失败");
                }
            }
        );
    });
}

onMounted(() => {
    handleQuery();
});
</script>

<template>
    <div class="app-container">
        <!-- 搜索表单 -->
        <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item prop="keyword">
                <el-input
                    v-model="queryParams.keyword"
                    placeholder="姓名 / 手机号搜索"
                    style="width: 220px"
                    clearable
                    @keyup.enter="handleQuery"
                />
            </el-form-item>
            <el-form-item prop="auditStatus">
                <el-select
                    v-model="queryParams.auditStatus"
                    placeholder="审核状态"
                    clearable
                    style="width: 140px"
                >
                    <el-option label="待审核" :value="0" />
                    <el-option label="审核拒绝" :value="1" />
                    <el-option label="审核通过" :value="2" />
                </el-select>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" :icon="Search" @click="handleQuery">搜索</el-button>
                <el-button :icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
        </el-form>

        <!-- 数据表格 -->
        <el-table
            v-loading="loading"
            :data="list"
            highlight-current-row
            border
        >
            <el-table-column label="ID" prop="id" align="center" width="80" />
            <el-table-column label="会员ID" prop="memberId" align="center" width="100" />
            <el-table-column label="联系邮箱" prop="email" align="center" min-width="200" show-overflow-tooltip />
            <el-table-column label="审核状态" prop="auditStatus" align="center" width="110">
                <template #default="{ row }">
                    <el-tag :type="AUDIT_STATUS_MAP[row.auditStatus]?.type">
                        {{ AUDIT_STATUS_MAP[row.auditStatus]?.label }}
                    </el-tag>
                </template>
            </el-table-column>
            <el-table-column label="拒绝原因" prop="rejectReason" align="center" min-width="140" show-overflow-tooltip>
                <template #default="{ row }">
                    <span>{{ row.rejectReason || '-' }}</span>
                </template>
            </el-table-column>
            <el-table-column label="申请时间" prop="createTime" align="center" min-width="170" />
            <el-table-column label="操作" align="center" width="200" fixed="right">
                <template #default="{ row }">
                    <el-button link type="primary" @click="openDetail(row)">详情</el-button>
                    <template v-if="row.auditStatus === 0">
                        <el-button link type="success" @click="handlePass(row)">通过</el-button>
                        <el-button link type="danger" @click="openReject(row)">拒绝</el-button>
                    </template>
                </template>
            </el-table-column>
        </el-table>

        <!-- 分页 -->
        <pagination
            v-if="total > 0"
            :total="total"
            v-model:page="queryParams.pageNo"
            v-model:limit="queryParams.pageSize"
            @pagination="handleQuery"
        />

        <!-- 详情弹窗 -->
        <el-dialog v-model="detailVisible" title="申请详情" width="500px">
            <el-descriptions :column="1" border v-if="currentDetail">
                <el-descriptions-item label="申请ID">{{ currentDetail.id }}</el-descriptions-item>
                <el-descriptions-item label="会员ID">{{ currentDetail.memberId }}</el-descriptions-item>
                <el-descriptions-item label="联系邮箱">{{ currentDetail.email || '-' }}</el-descriptions-item>
                <el-descriptions-item label="审核状态">
                    <el-tag :type="AUDIT_STATUS_MAP[currentDetail.auditStatus]?.type">
                        {{ AUDIT_STATUS_MAP[currentDetail.auditStatus]?.label }}
                    </el-tag>
                </el-descriptions-item>
                <el-descriptions-item label="拒绝原因" v-if="currentDetail.rejectReason">
                    {{ currentDetail.rejectReason }}
                </el-descriptions-item>
                <el-descriptions-item label="申请时间">{{ currentDetail.createTime }}</el-descriptions-item>
                <el-descriptions-item label="更新时间">{{ currentDetail.updateTime }}</el-descriptions-item>
            </el-descriptions>
        </el-dialog>

        <!-- 拒绝原因弹窗 -->
        <el-dialog v-model="rejectVisible" title="填写拒绝原因" width="420px">
            <el-form
                ref="rejectFormRef"
                :model="rejectForm"
                :rules="rejectRules"
                label-width="90px"
            >
                <el-form-item label="拒绝原因" prop="rejectReason">
                    <el-input
                        v-model="rejectForm.rejectReason"
                        type="textarea"
                        :rows="4"
                        placeholder="请填写拒绝原因"
                        maxlength="500"
                        show-word-limit
                    />
                </el-form-item>
            </el-form>
            <template #footer>
                <el-button @click="rejectVisible = false">取消</el-button>
                <el-button type="danger" @click="submitReject">确认拒绝</el-button>
            </template>
        </el-dialog>
    </div>
</template>
