<template>
    <div class="p-3">
        <div class="bg-fff flex1 ov-hd d-flex flex-cln" v-show="showSearch">
            <div class="pd-16 border-bottom">
                <div class="f-s-20 c-333 f-w-7 mb-10">会议管理</div>
                <div class="d-flex">
                    <div class="flex1 ov-hd d-flex j-ed">
                        <el-form :model="queryParams" ref="queryFormRef" :inline="true" label-width="auto">
                            <el-form-item label="会议名称" prop="trainingName">
                                <el-input v-model="queryParams.trainingName" placeholder="搜会议名称" clearable style="width: 160px" @keyup.enter="handleQuery" />
                            </el-form-item>
                            <el-form-item label="培训方式" prop="joinType">
                                <el-select v-model="queryParams.joinType" placeholder="请选择培训方式" clearable style="width: 160px" @change="handleQuery">
                                    <el-option v-for="item in dm_training_join_type" :key="item.value" :label="item.label" :value="item.value" />
                                </el-select>
                            </el-form-item>
                            <el-form-item label="是否颁发证书" prop="certFlag">
                                <el-select v-model="queryParams.certFlag" placeholder="请选择是否颁发证书" clearable style="width: 160px" @change="handleQuery">
                                    <el-option v-for="item in yes_no" :key="item.value" :label="item.label" :value="item.value" />
                                </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>
                    </div>
                </div>
            </div>
            <div class="d-flex flex1 ov-hd flex-cln pd-16">
                <div class="d-flex j-sb mb-16">
                    <div>
                        <searchTabs v-model="queryParams.status" @change="handleQuery" :list="tabs" key-label="name" key-count="num" key-value="type"></searchTabs>
                    </div>
                    <el-button type="primary" @click="router.push({ path: 'lmmeetingadd' })">新增会议</el-button>
                </div>
                <div class="flex1 ov-hd">
                    <vxe-table :loading="loading" border :data="dataList" min-height="0" max-height="100%">
                        <vxe-column title="序号" align="center" type="seq" width="50" />
                        <vxe-column field="trainingName" title="会议名称" :formatter="colNoData" min-width="150" class-name="f-w-600" />
                        <vxe-column field="trainingTime" min-width="130" title="会议时间" class-name="f-w-600">
                            <template #default="{ row }">{{ row.trainingStart }}~{{ row.trainingEnd }}</template>
                        </vxe-column>
                        <vxe-column field="signupsTime" min-width="130" title="报名时间" class-name="f-w-600">
                            <template #default="{ row }">{{ row.signupStart }}~{{ row.signupEnd }}</template>
                        </vxe-column>
                        <vxe-column field="joinType" title="会议方式" width="80">
                            <template #default="{ row }">
                                {{ selectDictLabel(dm_training_join_type, row.joinType) }}
                            </template>
                        </vxe-column>
                        <!-- <vxe-column field="trainingLocation" title="培训地点" align="center" min-width="150" /> -->
                        <vxe-column field="certFlag" title="是否颁发证书" width="60">
                            <template #default="{ row }">
                                {{ selectDictLabel(yes_no, row.certFlag) }}
                            </template>
                        </vxe-column>
                        <vxe-column field="joinCount" title="报名人数" width="60" class-name="f-w-600" />
                        <vxe-column field="signCount" title="签到人数" width="60" class-name="f-w-600" />
                        <vxe-column field="waitCount" title="待审核人数" width="60" class-name="f-w-600" />
                        <vxe-column field="certCount" title="领取证书人数" width="80" />
                        <vxe-column field="certFlag" title="会议状态" width="80">
                            <template #default="{ row }">
                                <DictTag :options="dm_training_status" :value="row?.trainingStatus"></DictTag>
                            </template>
                        </vxe-column>
                        <vxe-column field="certFlag" title="签到二维码" width="90" align="center">
                            <template #default="{ row }">
                                <el-button @click="trainingSignIn(row)" :style="{ color: !['1', '0'].includes(row?.trainingStatus) ? '#999' : '#0079fe' }" text :disabled="!['1', '0'].includes(row?.trainingStatus)">查看</el-button>
                            </template>
                        </vxe-column>
                        <vxe-column title="临时报名通道" align="center" field="createByName" width="120" :formatter="colNoData">
                            <template #default="{ row }">
                                <el-popconfirm confirm-button-text="确认" cancel-button-text="取消" title="通过临时报名通道报名将不受时间限制，是否确认打开？" :disabled="row.trainingStatus == '2'" @confirm="confirmEvent(row)" @cancel="cancelEvent">
                                    <template #reference>
                                        <el-switch :model-value="row.trainingStatus == '2' ? '0' : row.tempStatus" @update:model-value="row.trainingStatus != '2' ? row.tempStatus = $event : null" :loading="loading1" active-value="1" inactive-value="0" :before-change="beforeChange1" :disabled="row.trainingStatus == '2'" />
                                    </template>
                                </el-popconfirm>
                                <el-button v-if="row.tempStatus == '1' && row.trainingStatus !== '2'" type="primary" text @click="temporary(row)" :disabled="row.trainingStatus == '2'">查看</el-button>
                            </template>
                        </vxe-column>
                        <vxe-column title=" 创建人" align="center" field="createByName" width="70" :formatter="colNoData" />
                        <vxe-column title="创建时间" align="center" field="createTime" width="160" :formatter="colNoData" />
                        <vxe-column title="操作" width="240" fixed="right">
                            <template #default="{ row }">
                                <el-button v-if="['3'].includes(row?.trainingStatus)" type="primary" text @click="trainingOn(row)">上架</el-button>
                                <span></span>
                                <el-button v-if="!['3'].includes(row?.trainingStatus)" type="danger" text @click="trainingOff(row)">下架</el-button>
                                <span></span>
                                <el-button v-if="['3'].includes(row?.trainingStatus)" type="primary" @click="editRow(row)" text>编辑</el-button>
                                <span></span>
                                <el-button @click="router.push({ path: 'lmmeetingdetail', query: { id: row?.id } })" style="color: #0079fe;" text>人员管理及详情</el-button>
                                <span></span>
                                <el-button text type="danger" @click="deleteRow(row)">删除</el-button>
                            </template>
                        </vxe-column>
                    </vxe-table>
                </div>
                <pagination :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
            </div>
        </div>
    </div>
    <SignInCode v-if="showSignIn" v-model:show="showSignIn" :info="rowInfo" :dict="{ dm_training_join_type }"></SignInCode>
    <TemporaryRegistration v-if="showTemporary" v-model:show="showTemporary" :info="temporaryRegistration" :dict="{ dm_training_join_type }"></TemporaryRegistration>
</template>

<script setup name="meeting" lang="ts">
import { colNoData } from '@/utils/noData';
import { searchTabs } from '@/views/models';
import { trainingList, queryTrainingCount, trainingDelete, publishTraining, unpublishTraining, offOrNoTemp } from '@/api/training';
import { SignInCode, TemporaryRegistration } from '../models';
const router = useRouter();
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { dm_training_join_type, yes_no, lm_training_cert, dm_training_status } = toRefs<any>(proxy?.useDict('dm_training_join_type', 'yes_no', 'lm_training_cert', 'dm_training_status'));
const loading = ref(true);
const showSearch = ref(true);
const showSignIn = ref(false);
const total = ref(0);
const queryFormRef = ref<ElFormInstance>();
const dataList = ref<any[]>([]);
const initFormData = {};
const rowInfo = ref<any>({});
const data = reactive<any>({
    form: { ...initFormData },
    queryParams: {
        pageNum: 1,
        pageSize: 10
    },
    rules: {}
});
const temporaryRegistration = ref()
const showTemporary = ref(false)
const { queryParams, form } = toRefs(data);
/** 查询会员信息列表 */
const getList = async () => {
    loading.value = true;
    const res = await trainingList(queryParams.value);
    dataList.value = res.rows;
    total.value = res.total;
    loading.value = false;
};
const loading1 = ref(false)
let resolvePromise: ((value: boolean) => void) | null = null;

const beforeChange1 = (): Promise<boolean> => {
    loading1.value = true;
    return new Promise((resolve) => {
        // 存储 resolve 以便在 confirm/cancel 时调用
        resolvePromise = resolve;
    });
};
const offOrNoTemps = async (row) => {
    const res = await offOrNoTemp({
        trainingId: row.id,
        tempStatus: row.tempStatus == '1' ? '0' : '1'
    })
}


const confirmEvent = (row) => {
    if (resolvePromise) {
        loading1.value = false;
        resolvePromise(true); // 允许切换
        resolvePromise = null; // 清空引用
        offOrNoTemps(row)
    }
};

const cancelEvent = () => {
    if (resolvePromise) {
        loading1.value = false;
        resolvePromise(false); // 阻止切换
        resolvePromise = null; // 清空引用
    }
};
/** 搜索按钮操作 */
const handleQuery = () => {
    queryParams.value.pageNum = 1;
    getList();
};
/** 重置按钮操作 */
const resetQuery = () => {
    queryFormRef.value?.resetFields();
    handleQuery();
};
// 上架会议
const trainingOn = async (row: any) => {
    ElMessageBox.confirm(`确认要上架该会议吗？`, '上架提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(async () => {
        const res = await publishTraining(row?.id);
        if (res) {
            ElMessage.success('上架成功');
            getList();
        }
    });
};
// 下架会议
const trainingOff = async (row: any) => {
    ElMessageBox.confirm(`确认要下架该会议吗？`, '下架提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(async () => {
        const res = await unpublishTraining(row?.id);
        if (res) {
            ElMessage.success('下架成功');
            getList();
        }
    });
};
/** 编辑会议 */
const editRow = (row) => {
    router.push({ path: 'lmmeetingadd', query: { id: row.id } });
};

/** 删除会议 */
const deleteRow = async (row: any) => {
    ElMessageBox.confirm(`确认要删除该个会议全部记录吗？`, '删除提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(async () => {
        const res = await trainingDelete(row?.id);
        if (res) {
            ElMessage.success('删除成功');
            getList();
        }
    });
};
// 获取会议统计数量
const tabs = ref([]);
const getMeetingCount = async () => {
    const res = await queryTrainingCount();
    if (res?.code === 200) {
        tabs.value = res.data;
    }
};
// 打开签到二维码
const trainingSignIn = (row: any) => {
    rowInfo.value = { ...row };
    showSignIn.value = true;
};
// 打开临时报名二维码
const temporary = (row: any) => {
    temporaryRegistration.value = { ...row };
    showTemporary.value = true;
};
onMounted(() => {
    getMeetingCount();
    getList();
});
</script>
