<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 lm_training_join_type" :key="item.value" :label="item.label" :value="item.value" />
                                </el-select>
                            </el-form-item>
                            <el-form-item label="报名状态" prop="joinStatus">
                                <el-select v-model="queryParams.joinStatus" placeholder="请选择会报名状态" clearable style="width: 160px" @change="handleQuery">
                                    <el-option v-for="item in lm_training_join_status" :key="item.value" :label="item.label" :value="item.value" />
                                </el-select>
                            </el-form-item>
                            <el-form-item label="会议状态" prop="trainingStatus">
                                <el-select v-model="queryParams.trainingStatus" placeholder="请选择会议状态" clearable style="width: 160px" @change="handleQuery">
                                    <el-option v-for="item in lm_training_status" :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: 'meeting-add' })">新增会议</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="370" title="会议时间" class-name="f-w-600">
                            <template #default="{ row }">
                                <div class="d-flex a-c">
                                    {{ row.trainingStart.slice(0, -3) }}~{{ row.trainingEnd.slice(0, -3) }}
                                    <DictTag :options="lm_training_status" :value="row?.trainingStatus"></DictTag>
                                </div>
                            </template>
                        </vxe-column>
                        <vxe-column field="signupsTime" min-width="350" title="报名时间" class-name="f-w-600 p-rtv">
                            <template #default="{ row }">
                                <div class="d-flex a-c">
                                    {{ row.signupStart.slice(0, -3) }}~{{ row.signupEnd.slice(0, -3) }}
                                    <DictTag :options="lm_training_join_status" :value="row?.joinStatus"></DictTag>
                                </div>
                                <div v-if="row.joinStatus == '1'" class="pos-tag">
                                    <el-button @click="openEnrollRegistration(row)" type="primary" size="small" text>报名二维码{{ '>' }}</el-button>
                                </div>
                            </template>
                        </vxe-column>
                        <vxe-column field="joinType" title="会议方式" width="80">
                            <template #default="{ row }">
                                {{ selectDictLabel(lm_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="pageEnable" title="会议门户" width="80">
                            <template #default="{ row }">
                                <el-switch v-model="row.pageEnable" active-value="1" inactive-value="0" @change="changePageEnable(row.id,row?.pageEnable)"></el-switch>
                                <div v-if="+row.pageId" @click="ckeckpageEnable(row?.trainingName,row?.pageId,row?.id)" class="c-s-p">查看</div>
                                <div v-else @click="router.push({ path: 'ptpl-edit', query: { meetid: row?.id } })" class="c-s-p">去设置</div>
                            </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 }">
                                <div v-if="row.tempStatus == '0'">
                                    <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>
                                </div>
                                <div v-if="row.tempStatus == '1'">
                                    <el-switch v-if="+row.tempStatus" :model-value="row.trainingStatus == '2' ? '0' : row.tempStatus" @update:model-value="row.trainingStatus != '2' ? row.tempStatus = $event : null" :loading="loading1" :before-change="() => beforeChange2(row)" active-value="1" inactive-value="0" :disabled="row.trainingStatus == '2'" />
                                </div>
                                <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="!+row?.status" type="primary" text @click="trainingOn(row)">上架</el-button>
                                <span></span>
                                <el-button v-if="+row?.status" type="danger" text @click="trainingOff(row)">下架</el-button>
                                <span></span>
                                <el-button v-if="!+row?.status" type="primary" @click="editRow(row)" text>编辑</el-button>
                                <span></span>
                                <el-badge :value="row.waitCount" class="item" :offset="[-10, 5]" v-if="+row.waitCount">
                                    <el-button @click="router.push({ path: 'meeting-detail', query: { id: row?.id } })" style="color: #0079fe;" text>人员管理及详情</el-button>
                                </el-badge>
                                <el-button v-else @click="router.push({ path: 'meeting-detail', 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="{ lm_training_join_type }"></SignInCode>
    <TemporaryRegistration v-if="showTemporary" v-model:show="showTemporary" :info="temporaryRegistration" :dict="{ lm_training_join_type }"></TemporaryRegistration>
    <EnrollRegistration v-if="showEnroll" v-model:show="showEnroll" :info="rowInfo" :dict="{ lm_training_join_type }"></EnrollRegistration>
    <el-dialog v-model="dialogVisible" title="会议门户" width="500">
        <div class="mb-20">会议名称：{{ training?.trainingName }}</div>
        <div>访问地址：{{ `${VITE_APP_MEETING_URL}/?id=${training?.pageId}` }}</div>
        <template #footer>
            <div style="display: flex;justify-content: space-around;">
                <el-button type="primary" @click="router.push({ path: 'ptpl-edit', query: { meetid: training?.id } })">编辑</el-button>
                <el-button @click="copyToClipboard(`会议名称：${training?.trainingName } 访问地址：${`${VITE_APP_MEETING_URL}/?id=${training?.pageId}`}`)">复制</el-button>
            </div>
        </template>
    </el-dialog>
</template>

<script setup name="meeting" lang="ts">
import { offOrNoTemp, publishTraining, queryTrainingCount, trainingDelete, trainingList, unpublishTraining,switchPage } from '@/api/training';
import { colNoData } from '@/utils/noData';
import { searchTabs } from '@/views/models';
import { SignInCode, TemporaryRegistration,EnrollRegistration } from '../models';
import { copyTextToClipboard } from '@/directive/common/copyText';
const VITE_APP_MEETING_URL = ref(import.meta.env.VITE_APP_MEETING_URL);
const router = useRouter();
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { lm_training_join_type, yes_no, dm_training_cert, lm_training_status,lm_training_join_status } = toRefs<any>(proxy?.useDict('lm_training_join_type', 'yes_no', 'dm_training_cert', 'lm_training_status',"lm_training_join_status"));
const loading = ref(true);
const showSearch = ref(true);
const showSignIn = ref(false);
const showEnroll = 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 dialogVisible = ref(false)
const training = ref<any>({})
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 beforeChange2 = (row): Promise<boolean> => {
    offOrNoTemps(row)
    return new Promise((resolve) => {
        resolve(true); // 手动返回 resolved Promise
    });
};
const offOrNoTemps = async (row) => {
    const res = await offOrNoTemp({
        trainingId: row.id,
        tempStatus: row.tempStatus == '1' ? '0' : '1'
    })
}

const openEnrollRegistration = (row) => {
    rowInfo.value = { ...row };
    showEnroll.value = true;
};
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',
        customClass: 'custom-message-box', // 添加自定义类名
    }).then(async () => {
        const res = await publishTraining(row?.id);
        if (res) {
            ElMessage.success('上架成功');
            getList();
            getMeetingCount()
        }
    });
};
// 下架会议
const trainingOff = async (row: any) => {
    ElMessageBox.confirm(`确认要下架该会议吗？`, '下架提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(async () => {
        const res = await unpublishTraining(row?.id);
        if (res) {
            ElMessage.success('下架成功');
            getList();
            getMeetingCount()
        }
    });
};
/** 编辑会议 */
const editRow = (row) => {
    router.push({ path: 'meeting-add', 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 };
    console.log(temporaryRegistration.value, 'temporaryRegistration.value');

    showTemporary.value = true;
};
// 开关会议门户
const changePageEnable = async(id,pageEnable)=>{
   const res = await switchPage({id,pageEnable})
}
const ckeckpageEnable = (trainingName,pageId,id)=>{
    training.value.trainingName = trainingName
    training.value.pageId = pageId
    training.value.id = id
    dialogVisible.value = true
}

// 复制文本到剪贴板
const copyToClipboard = async (text)=>{
  try {
    const sc = copyTextToClipboard(text)
    if (sc) {
        ElMessage.success('复制成功');
    } else {
        ElMessage.error('复制失败，请手动复制');
    }
  } catch (err) {
    console.error('无法复制文本: ', err);
    return false;
  }
}

// 使用示例
onMounted(() => {
    getMeetingCount();
    getList();
});
</script>
<style lang="scss" scoped>
.pos-tag{
    position: absolute;
    bottom: 5px;
    right: 5px;
}
</style>
