<template>
    <div class="store-page">
        <Breadcrumb />

        <a-card title="乐跑账号管理">
            <a-row class="query-row">
                <a-col :flex="'1000px'" class="query-main">
                    <a-form class="queryForm app-query-form" :model="queryData" :label-col-props="{ span: 6 }" :wrapper-col-props="{ span: 18 }"
                        label-align="left">
                        <a-row :gutter="16">
                            <a-col :span="6">
                                <a-form-item field="area" label="跑区">
                                    <a-select v-model="queryData.area" placeholder="请选择乐跑跑区" default-value="">
                                        <a-option value="">所有</a-option>
                                        <a-option v-for="(item, index) in area" :key="index" :value="item">
                                            {{ item }}
                                        </a-option>
                                    </a-select>
                                </a-form-item>
                            </a-col>
                            <a-col :span="6">
                                <a-form-item field="user_uuid" label="创建人UUID">
                                    <a-input v-model="queryData.user_uuid" allow-clear />
                                </a-form-item>
                            </a-col>
                            <a-col :span="6">
                                <a-form-item field="email" label="用户邮箱">
                                    <EmailAutoComplete v-model="queryData.email" allow-clear />
                                </a-form-item>
                            </a-col>
                            <a-col :span="6">
                                <a-form-item field="username" label="账号名称">
                                    <a-input v-model="queryData.username" allow-clear />
                                </a-form-item>
                            </a-col>
                            <a-col :span="6">
                                <a-form-item field="notes" label="备注">
                                    <a-input v-model="queryData.notes" allow-clear />
                                </a-form-item>
                            </a-col>
                            <a-col :span="6">
                                <a-form-item field="student_num" label="学号">
                                    <a-input v-model="queryData.student_num" allow-clear />
                                </a-form-item>
                            </a-col>
                            <a-col :span="6">
                                <a-form-item field="bind_code" label="绑定码">
                                    <a-input v-model="queryData.bind_code" allow-clear />
                                </a-form-item>
                            </a-col>
                            <a-col :span="6">
                                <a-form-item field="bot_account" label="机器人账号">
                                    <a-input v-model="queryData.bot_account" allow-clear />
                                </a-form-item>
                            </a-col>
                            <a-col :span="6">
                                <a-form-item field="state" label="账号状态">
                                    <a-select v-model="queryData.state" :options="state" placeholder="请选择账号状态"
                                        :default-value="-1" />
                                </a-form-item>
                            </a-col>
                            <a-col :span="6">
                                <a-form-item field="auto_time" label="乐跑时段">
                                    <a-select v-model="queryData.auto_time" placeholder="请选择自动乐跑时段" :default-value="0">
                                        <a-option :value="0">所有时段</a-option>
                                        <a-option v-for="(item, index) in auto_time" :key="index" :value="item.value">
                                            {{ item.label }}
                                        </a-option>
                                    </a-select>
                                </a-form-item>
                            </a-col>
                            <a-col :span="6">
                                <a-form-item field="queryTime" label="更新时间">
                                    <a-range-picker v-model="queryData.queryTime" show-time format="YY-MM-DD HH:mm"
                                        value-format="x" @ok="search()" />
                                </a-form-item>
                            </a-col>
                        </a-row>
                    </a-form>
                </a-col>
                <a-divider class="query-divider" style="height: 84px" direction="vertical" />
                <a-col :flex="1" class="app-query-actions">
                    <a-space class="query-actions-space" direction="vertical" :size="18">
                        <a-button type="primary" @click="search">
                            <template #icon>
                                <icon-search />
                            </template>
                            搜索
                        </a-button>
                        <a-button @click="reset">
                            <template #icon>
                                <icon-refresh />
                            </template>
                            重置
                        </a-button>
                    </a-space>
                </a-col>
            </a-row>

            <a-table :data="data" :bordered="false" hoverable class="table table-clickable" :loading="loading" :columns="columns" :scroll="{ x: 2850 }" @row-click="onRowClick" :pagination="{
                showPageSize: true,
                showJumper: true,
                showTotal: true,
                pageSize: pagination.pagesize,
                current: pagination.current,
                total: pagination.total
            }" @page-change="handlePageChange" @page-size-change="handlePageSizeChange">
                <template #create_user="{ record }">
                    <a-avatar :size="30">
                        <img :alt="record.create_user ?? ''"
                            :src="record.avatar || 'https://lepao-cloud.xxoo365.top/view.php/25aa126dc406974ff3579a99a2c6501a.png'" />
                    </a-avatar>
                    {{ record.create_user }}
                </template>
                <template #name="{ record }">
                    <a-avatar :size="30">
                        <img :alt="record.name ?? ''"
                            :src="record.user_avatar || 'https://lepao-cloud.xxoo365.top/view.php/25aa126dc406974ff3579a99a2c6501a.png'" />
                    </a-avatar>
                    {{ record.name }}
                </template>
                <template #sex="{ record }">
                    <icon-man v-if="record.sex === 1" />
                    <icon-woman v-else-if="record.sex === 2" />
                    {{ record.sex === 1 ? '男' : (record.sex === 2 ? '女' : '') }}
                </template>
                <template #auto_run="{ record }">
                    <a-tag color="green" v-if="record.auto_run">{{ record.target_count === 0 ? '开启-∞次' :
                        `开启-${record.target_count}次` }}</a-tag>
                    <a-tag color="red" v-else>关闭</a-tag>
                </template>
                <template #notice_type="{ record }">
                    <span v-if="record.notice_type === 'email'"><icon-email /> {{ record.email ?? '未绑定' }}</span>
                    <span v-else-if="record.notice_type === 'bot'"><icon-robot /> {{ record.bot_account ?? '未绑定'
                    }}</span>
                    <span v-else><icon-notification-close /> 无通知</span>
                </template>
                <template #auto_day="{ record }">
                    <span v-if="record.auto_run && record.auto_day && record.auto_day.length > 0">
                        {{record.auto_day.slice().sort((a, b) => {
                            if (a === 0) return 1; if (b === 0) return -1; return a - b;
                        }).map(day => auto_day.find(item => item.value === day)?.label).join(',').replace(/周/g, '')}}
                    </span>
                    <span v-else>-</span>
                </template>
                <template #num="{ record }">
                    {{ record.term_num != record.total_num ? `${record.total_num} / ${record.term_num}` :
                        '已完成' }}
                </template>
                <template #state="{ record }">
                    <div v-if="record.state === 0" class="state">
                        <div class="circle zero"></div>需登录
                    </div>
                    <div v-else-if="record.state === 1" class="state">
                        <div class="circle one"></div>正常
                    </div>
                    <div v-else class="state">
                        <div class="circle else"></div>状态异常
                    </div>
                </template>
                <template #face_state="{ record }">
                    <div v-if="record.face_state === 0" class="state">
                        <div class="circle zero"></div>未采集
                    </div>
                    <div v-else-if="record.face_state === 1" class="state">
                        <div class="circle one"></div>已通过
                    </div>
                    <div v-else class="state">
                        <div class="circle else"></div>不通过
                    </div>
                </template>
                <template #auto_time="{ record }">
                    {{ autoTimeLabel(record) }}
                </template>
                <template #create_time="{ record }">
                    {{ stramptoTime(record.create_time) }}
                </template>
                <template #update_time="{ record }">
                    {{ record.update_time ? stramptoTime(record.update_time) : '待登录' }}
                </template>
                <template #optional="{ record }">
                    <a-dropdown :popup-max-height="false" trigger="hover" @click.stop>
                        <a-button>操作 <icon-down /></a-button>
                        <template #content>
                            <a-doption v-if="hasPermission('action.lepao.admin.updateAccount')" @click="editAccount(record)"><icon-edit /> 编辑账号</a-doption>
                            <a-doption @click="faceRecoRef.openModal(record)"><icon-video-camera /> 人脸采集</a-doption>
                            <a-doption @click="bindBotRef.openModal(record)"><icon-robot-add /> 绑定智能机器人</a-doption>
                            <a-doption @click="openBindAudit(record)"><icon-history /> 绑定解绑记录</a-doption>
                            <a-doption v-if="hasPermission('action.lepao.singleRun')" @click="SingleRun(record)"><icon-play-circle /> 开始单次乐跑</a-doption>
                            <a-doption v-if="hasPermission('action.lepao.changeAutoRun')" @click="ChangeAutoRun(record)"><icon-translate /> {{ record.auto_run ? '关闭' :
                                '开启' }}自动乐跑</a-doption>
                            <a-doption v-if="hasPermission('action.lepao.admin.updateAccount')" @click="UpdateAccountInfo(record)"><icon-refresh /> 更新账号信息</a-doption>
                            <a-doption v-if="hasPermission('action.lepao.deleteAccount')" @click="DeleteAccount(record)"><icon-minus-circle /> 解绑账号</a-doption>
                        </template>
                    </a-dropdown>
                </template>
            </a-table>
        </a-card>
    </div>

    <!-- 账号编辑对话框 -->
    <a-modal v-model:visible="visible" title="编辑账号" @cancel="handleCancel" @before-ok="handleBeforeOk" draggable
        :ok-loading="ok_loading" esc-to-close closable>
        <a-form :model="form">
            <a-form-item field="student_num" label="学号">
                <a-input v-model="form.student_num" placeholder="账号所有者学号，填写错误将无法登录" />
            </a-form-item>
            <a-form-item field="notice_type" label="通知方式">
                <a-radio-group v-model="form.notice_type">
                    <a-radio value="email"><icon-email /> 邮件</a-radio>
                    <a-radio value="bot"><icon-robot /> 智能机器人</a-radio>
                    <a-radio value="none"><icon-notification-close /> 无通知</a-radio>
                </a-radio-group>
            </a-form-item>
            <a-form-item field="email" label="通知邮箱" v-if="form.notice_type === 'email'">
                <EmailAutoComplete v-model="form.email" placeholder="用于接收乐跑失败、登录失效的通知" allow-clear />
            </a-form-item>
            <a-form-item field="area" label="乐跑跑区">
                <a-select v-model="form.area" placeholder="请选择乐跑跑区" default-value="">
                    <a-option value="">随机分配</a-option>
                    <a-option v-for="(item, index) in area" :key="index" :value="item">
                        <span class="vipcontent">
                            <span>{{ item }} </span>
                        </span>
                    </a-option>
                </a-select>
            </a-form-item>
            <a-form-item field="auto_run" label="自动乐跑开关">
                <a-switch v-model="form.auto_run" :checked-value="1" :unchecked-value="0" />
            </a-form-item>
            <a-form-item field="target_count" label="乐跑目标次数" v-if="form.auto_run">
                <a-input-number v-model="form.target_count" placeholder="请输入乐跑目标次数" mode="button" />
                <template #extra>
                    <div>当学期有效次数达到目标次数时自动乐跑将关闭，0为不限次</div>
                </template>
            </a-form-item>
            <a-form-item field="auto_day" label="自动乐跑星期" v-if="form.auto_run">
                <a-checkbox-group v-model="form.auto_day" placeholder="请选择每天自动乐跑的星期" :options="auto_day" />
            </a-form-item>
            <a-form-item field="auto_time" label="自动乐跑时段" v-if="form.auto_run">
                <a-select v-model="form.auto_time" placeholder="请选择每天自动乐跑的时段" :options="auto_time" />
            </a-form-item>
            <a-form-item field="notes" label="备注">
                <a-textarea v-model="form.notes" no-trim placeholder="添加对账号的备注（非必填）" :max-length="{ length: 50 }" allow-clear
                    show-word-limit />
            </a-form-item>
        </a-form>
    </a-modal>

    <faceModal :faceInfo="faceInfo" ref="faceRecoRef" />
    <bindBot ref="bindBotRef" />
    <accountDetailCard ref="accountDetailRef" admin />

    <a-modal v-model:visible="bindAuditVisible" title="绑定解绑记录" :footer="false" width="980px" draggable>
        <a-table :bordered="false" :data="bindAuditData" :columns="bindAuditColumns" :loading="bindAuditLoading" :pagination="false"
            :scroll="{ x: 1450, y: 420 }">
            <template #lepao_user="{ record }">
                <a-space>
                    <a-avatar :size="26">
                        <img :src="record.lepao_avatar || 'https://lepao-cloud.xxoo365.top/view.php/25aa126dc406974ff3579a99a2c6501a.png'" />
                    </a-avatar>
                    {{ record.lepao_name || '-' }}
                </a-space>
            </template>
            <template #owner_user="{ record }">
                <a-space>
                    <a-avatar :size="26">
                        <img :src="record.owner_avatar || 'https://lepao-cloud.xxoo365.top/view.php/25aa126dc406974ff3579a99a2c6501a.png'" />
                    </a-avatar>
                    {{ record.owner_username || '-' }}
                </a-space>
            </template>
            <template #action="{ record }">
                <a-tag>{{ actionLabel(record.action) }}</a-tag>
            </template>
            <template #source="{ record }">
                {{ sourceLabel(record.source) }}
            </template>
            <template #operator_user="{ record }">
                <a-space>
                    <a-avatar :size="26">
                        <img :src="record.operator_avatar || 'https://lepao-cloud.xxoo365.top/view.php/25aa126dc406974ff3579a99a2c6501a.png'" />
                    </a-avatar>
                    {{ record.operator_username || '-' }}
                </a-space>
            </template>
            <template #detail_json="{ record }">
                {{ formatDetail(record.detail_json) }}
            </template>
            <template #created_at="{ record }">
                {{ stramptoTime(record.created_at) }}
            </template>
            <template #empty>
                <a-empty description="暂无绑定解绑记录" />
            </template>
        </a-table>
    </a-modal>
</template>

<script setup>
import { ref, reactive, onMounted, onUnmounted, h } from 'vue'
import { addAccount, adminAccountList, deleteAccount, changeAutoRun, singleRun, adminUpdateAccountInfo, getAdminBindAuditByAccount, getAdminBindAuditList } from '@/api/lepao'
import { Modal, Notification, Message } from '@arco-design/web-vue'
import faceModal from '@/components/FaceModal/faceModal.vue'
import bindBot from '@/components/BindBot/bindBot.vue'
import accountDetailCard from '@/components/LepaoAccountCard/accountDetailCard.vue'
import { getSemesterTimestamps } from '@/utils/util'
import { hasPermission } from '@/utils/permission'

const faceRecoRef = ref(null)
const bindBotRef = ref(null)
const accountDetailRef = ref(null)

const ROW_DETAIL_CONFIRM_MS = 3000
const pendingDetailAccountId = ref(null)
let pendingDetailTimer = null

const clearPendingDetail = () => {
    pendingDetailAccountId.value = null
    if (pendingDetailTimer) {
        clearTimeout(pendingDetailTimer)
        pendingDetailTimer = null
    }
}

const bindAuditVisible = ref(false)
const bindAuditLoading = ref(false)
const bindAuditData = ref([])

const queryData = reactive({
    area: '',
    student_num: '',
    user_uuid: '',
    email: '',
    username: '',
    notes: '',
    bind_code: '',
    bot_account: '',
    state: -1,
    auto_time: 0,
    queryTime: []
})

const pagination = reactive({
    total: 0,
    current: 1, // 默认从第1页开始
    pagesize: 20
})

const visible = ref(false)
const ok_loading = ref(false)
const form = reactive({
    id: null,
    student_num: '',
    email: '',
    area: '',
    notice_type: 'email',
    auto_run: 1,
    auto_time: -1,
    target_count: 30,
    auto_day: [0, 1, 2, 3, 4, 5, 6],
    notes: ''
})

const loading = ref(false)
const data = ref([])

const auto_day = [
    { label: '周一', value: 1 },
    { label: '周二', value: 2 },
    { label: '周三', value: 3 },
    { label: '周四', value: 4 },
    { label: '周五', value: 5 },
    { label: '周六', value: 6 },
    { label: '周日', value: 0 }
]

const state = [
    { label: '全部', value: -1 }, { label: '需登录', value: 0 }, { label: '正常', value: 1 }, { label: '状态异常', value: 2 }
]
const area = ["兰花湖校区跑区", "主校区北跑区", "主校区南跑区", "重庆工商大学茶园校区"]

const columns = [
    {
        title: 'ID',
        dataIndex: 'id',
        fixed: 'left',
        width: 68
    }, {
        title: '创建用户',
        slotName: 'create_user',
        width: 160
    }, {
        title: '账号名称',
        slotName: 'name',
        width: 180
    }, {
        title: '学号',
        dataIndex: 'student_num',
        width: 118
    }, {
        title: '性别',
        slotName: 'sex',
        width: 80
    }, {
        title: '学院',
        dataIndex: 'academy_name',
        width: 200
    }, {
        title: '年级',
        dataIndex: 'grade_id',
        width: 80
    }, {
        title: '通知方式',
        slotName: 'notice_type',
        width: 200
    }, {
        title: '帐号状态',
        slotName: 'state',
        width: 100
    }, {
        title: '乐跑跑区',
        dataIndex: 'area',
        width: 150
    }, {
        title: '自动乐跑',
        slotName: 'auto_run',
        width: 90
    }, {
        title: '自动乐跑星期',
        slotName: 'auto_day',
        width: 155
    }, {
        title: '自动乐跑时段',
        slotName: 'auto_time',
        width: 130
    }, {
        title: '学期目标',
        slotName: 'num',
        width: 90
    }, {
        title: '手机型号',
        dataIndex: 'deviceModel',
        width: 100
    }, {
        title: 'UA',
        dataIndex: 'userAgent',
        width: 120,
        ellipsis: true,
        tooltip: true
    }, {
        title: '人脸状态',
        slotName: 'face_state',
        width: 100
    }, {
        title: '添加时间',
        slotName: 'create_time',
        width: 150
    }, {
        title: '上次更新时间',
        slotName: 'update_time',
        width: 150
    }, {
        title: '备注',
        dataIndex: 'notes',
        width: 200
    }, {
        title: '操作',
        slotName: 'optional',
        fixed: 'right',
        width: 90
    }]

const bindAuditColumns = [
    { title: '学号', dataIndex: 'student_num', width: 140 },
    { title: '乐跑账号', slotName: 'lepao_user', width: 180 },
    { title: '所属用户', slotName: 'owner_user', width: 180 },
    { title: '动作', slotName: 'action', width: 120 },
    { title: '来源', slotName: 'source', width: 140 },
    { title: '操作者', slotName: 'operator_user', width: 180 },
    { title: '详情', slotName: 'detail_json', width: 220, ellipsis: true, tooltip: true },
    { title: '时间', slotName: 'created_at', width: 180 }
]

const search = () => {
    pagination.current = 1
    getAccounts()
}

const reset = () => {
    queryData.area = ''
    queryData.student_num = ''
    queryData.user_uuid = ''
    queryData.email = ''
    queryData.username = ''
    queryData.notes = ''
    queryData.bind_code = ''
    queryData.bot_account = ''
    queryData.state = -1
    queryData.auto_time = 0
    queryData.queryTime = getSemesterTimestamps()
    getAccounts()
}

const getAccounts = async () => {
    try {
        loading.value = true
        const reqData = {
            ...queryData,
            pagesize: pagination.pagesize,
            current: pagination.current
        }
        const res = await adminAccountList(reqData)
        if (!res || res.code !== 0)
            return Notification.error({
                title: '获取账号数据失败！',
                content: res?.msg ?? '请稍后再试'
            })

        data.value = res.data
        pagination.total = res.pagination.total
    } catch (error) {
        Notification.error({
            title: '获取账号数据失败！',
            content: error.message || '请稍后再试'
        })
    } finally {
        loading.value = false
    }
}

const onRowClick = (record, ev) => {
    if (ev?.target?.closest?.('.arco-dropdown, .arco-btn')) return

    const accountId = record?.id
    if (accountId == null) return

    if (pendingDetailAccountId.value === accountId) {
        clearPendingDetail()
        accountDetailRef.value?.openModal(record)
        return
    }

    clearPendingDetail()
    pendingDetailAccountId.value = accountId
    Message.info('再点一次即可查看账号详情')
    pendingDetailTimer = setTimeout(clearPendingDetail, ROW_DETAIL_CONFIRM_MS)
}

const editAccount = (item) => {
    if (item) {
        form.id = item.id
        form.student_num = item.student_num
        form.email = item.email
        form.area = item.area
        form.auto_run = item.auto_run
        form.auto_time = item.auto_time
        form.auto_day = item.auto_day
        form.notice_type = item.notice_type || 'email'
        form.target_count = item.target_count
        form.notes = item.notes
    } else {
        form.id = null
        form.student_num = ''
        form.auto_run = 1
        form.auto_time = 7
        form.target_count = 30
        form.auto_day = [0, 1, 2, 3, 4, 5, 6]
        form.email = ''
        form.notes = ''
    }
    visible.value = true
}

const handleBeforeOk = async (done) => {
    try {
        ok_loading.value = true
        const { student_num, email, notice_type } = form
        if (!student_num || (!email && notice_type === 'email')) {
            Message.error('请填写完整的账号信息')
            return false
        }

        const studentNumRegex = /^\d{10}$/
        if (!studentNumRegex.test(student_num)) {
            Message.error('请检查学号格式是否正确')
            return false
        }

        const emailRegex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/
        if (form.notice_type === 'email' && !emailRegex.test(email)) {
            Message.error('请检查邮箱格式是否正确')
            return false
        }

        let data = {
            ...form
        }

        const res = await addAccount(data)
        if (!res || res.code !== 0) {
            Notification.error({
                title: '保存乐跑账号失败！',
                content: res?.msg ?? '请稍后再试'
            })
            return false
        }

        Message.success('保存成功！')
        if (form.notice_type === 'bot' && res.data && !res.data.umo) {
            bindBotRef.value.openModal(res.data)
        }
        done()
        getAccounts()
    } catch (error) {
        Notification.error({
            title: '保存乐跑账号失败！',
            content: error.message || '请稍后再试'
        })
        return false
    } finally {
        ok_loading.value = false
    }
}

const handleCancel = () => {
    visible.value = false;
}

// 分页 - 页码变化
const handlePageChange = (page) => {
    pagination.current = page
    getAccounts()
}

// 分页 - 每页条数变化
const handlePageSizeChange = (size) => {
    pagination.pagesize = size
    pagination.current = 1 // 页大小变化后回到第一页
    getAccounts()
}

const DeleteAccount = async (item) => {
    Modal.confirm({
        title: '解绑账号',
        content: () => h('div', [
            h('p', '您是否要解绑该账号？该操作不可逆')
        ]),
        onOk: async () => {
            const res = await deleteAccount({ id: item.id })
            if (!res || res.code !== 0)
                return Notification.error({
                    title: '解绑失败',
                    content: res?.msg ?? '请稍后再试'
                })
            Message.success('解绑成功！')
            getAccounts()
        }
    })
}

const ChangeAutoRun = async (record) => {
    const oldValue = record.auto_run;
    record.auto_run = oldValue === 1 ? 0 : 1;
    try {
        const res = await changeAutoRun({ id: record.id });
        if (!res || res.code !== 0) {
            record.auto_run = oldValue;
            Notification.error({
                title: '切换自动乐跑状态失败！',
                content: res?.msg ?? '请稍后再试'
            })
        } else {
            Message.success(`自动乐跑状态已${record.auto_run === 1 ? '开启' : '关闭'}`)
            getAccounts()
        }
    } catch (error) {
        console.log(error)
        record.auto_run = oldValue
        Message.error('切换自动乐跑状态失败！')
    }
}

const SingleRun = async (item) => {
    if (item.state !== 1)
        return Notification.warning({
            title: '当前乐跑账号需登录，请登录后再试',
            content: '如有疑问请联系客服'
        })
    Modal.confirm({
        title: '开始乐跑',
        content: () => h('div', [
            h('p', `您是否要为${item.name}(${item.student_num})乐跑？若乐跑成功将扣减乐跑次数`)
        ]),
        onOk: async () => {
            const res = await singleRun({ student_num: item.student_num })
            if (!res || res.code !== 0)
                return Notification.error({
                    title: '提交乐跑任务失败',
                    content: res?.msg ?? '请稍后再试'
                })
            Message.success('提交乐跑任务成功！')
        }
    })
}

const UpdateAccountInfo = async (record) => {
    try {
        const res = await adminUpdateAccountInfo({
            student_num: record.student_num
        })
        if (!res || res.code !== 0) {
            return Notification.error({
                title: '更新账号信息失败！',
                content: res?.msg ?? '请稍后再试'
            })
        }
        Message.success('已异步触发账号信息更新')
        getAccounts()
    } catch (error) {
        Notification.error({
            title: '更新账号信息失败！',
            content: error.message || '请稍后再试'
        })
    }
}

const actionLabel = (action) => {
    const map = {
        platform_bind: '平台绑定',
        platform_unbind: '平台解绑',
        bot_bind: '机器人绑定',
        bot_unbind: '机器人解绑'
    }
    return map[action] || action
}

const sourceLabel = (source) => {
    const map = {
        user_api: '用户接口',
        admin_api: '管理员接口',
        service_api: '客服接口',
        mcp_qq: '机器人MCP',
        mcp_work_order: '工单MCP'
    }
    return map[source] || source
}

const formatDetail = (detail) => {
    if (!detail) return '-'
    if (typeof detail === 'string') return detail
    const keyMap = {
        via: '触发方式',
        sender: '发送者',
        old_owner_uuid: '原所属用户UUID',
        new_owner_uuid: '新所属用户UUID'
    }
    const valueMap = {
        AddAccount: '用户新增账号',
        DeleteAccount: '账号解绑接口',
        'AddAccount:auto_unbind_rebind': '新增账号自动解绑并重绑'
    }
    return Object.keys(detail)
        .map((key) => {
            const label = keyMap[key] || key
            const rawValue = detail[key]
            const value = (typeof rawValue === 'string' && valueMap[rawValue]) ? valueMap[rawValue] : rawValue
            return `${label}:${value}`
        })
        .join('；')
}

const openBindAudit = async (record) => {
    bindAuditVisible.value = true
    bindAuditLoading.value = true
    bindAuditData.value = []
    try {
        const studentNum = String(record.student_num || '')
        if (!studentNum) {
            Message.warning('该账号缺少学号，无法查询审计记录')
            return
        }

        const res = await getAdminBindAuditByAccount({
            student_num: studentNum,
            pagesize: 100,
            current: 1
        })
        if (!res || res.code !== 0) {
            Notification.error({
                title: '获取绑定解绑记录失败',
                content: res?.msg ?? '请稍后再试'
            })
            return
        }
        const primaryData = Array.isArray(res.data) ? res.data : []
        if (primaryData.length > 0) {
            bindAuditData.value = primaryData
            return
        }

        const fallbackRes = await getAdminBindAuditList({
            student_num: studentNum,
            pagesize: 100,
            current: 1
        })
        const fallbackData = (fallbackRes && fallbackRes.code === 0 && Array.isArray(fallbackRes.data)) ? fallbackRes.data : []
        bindAuditData.value = fallbackData
    } catch (error) {
        Notification.error({
            title: '获取绑定解绑记录失败',
            content: error.message || '请稍后再试'
        })
    } finally {
        bindAuditLoading.value = false
    }
}

onMounted(() => {
    queryData.queryTime = getSemesterTimestamps()
    getAccounts()
})

onUnmounted(() => {
    clearPendingDetail()
})

const stramptoTime = (time) => {
    return new Date(time).toLocaleString('zh-CN', { year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit' })
}

const auto_time = [
    { label: '随机', value: -1 },
    ...Array.from({ length: 17 }, (_, i) => {
        const hour = i + 7
        return { label: `${hour} ~ ${hour + 1}时`, value: hour }
    })
]

const autoTimeLabel = (record) => {
    if (record.auto_time === -1 && record.today_auto_time) {
        return `随机-今日${record.today_auto_time}时`
    }
    const match = auto_time.find(item => item.value === record.auto_time)
    return match ? match.label : '-'
}
</script>

<style scoped>
.query-row {
    margin-bottom: 10px;
}

.query-main {
    min-width: 0;
}

.query-actions-space {
    width: 100%;
}

.table-clickable {
    :deep(.arco-table-tr) {
        cursor: pointer;
    }
}

.table {
    font-family: -apple-system, BlinkMacSystemFont;
    margin-top: 15px;

    .state {
        display: flex;
        align-items: center;

        .circle {
            border-radius: 50%;
            height: 8px;
            min-height: 8px;
            width: 8px;
            min-width: 8px;
            margin-right: 5px;
        }

        .zero {
            background-color: rgb(var(--orange-6));
        }

        .one {
            background-color: rgb(var(--green-6));
        }

        .else {
            background-color: rgb(var(--red-6));
        }
    }
}

@media (max-width: 768px) {
    .query-row {
        display: block;
    }

    .query-divider {
        display: none;
    }

    .query-actions-space {
        margin-top: 4px;
        flex-direction: row !important;
        gap: 10px !important;
    }

    .query-actions-space :deep(.arco-btn) {
        flex: 1;
    }
}
</style>