<template>
    <div class="p-3 d-flex flex-cln">
        <div class="bg-fff flex1 ov-hd d-flex flex-cln">
            <div class="pd-16 d-flex a-c border-bottom">
                <div class="flex1 ov-hd">
                    <span class="f-s-18 c-333 f-w-6">编辑会议宣传门户</span>
                    <el-button @click="router.go(-1)" text type="primary">
                        <el-icon>
                            <Back />
                        </el-icon>
                        返回上一级
                    </el-button>
                </div>
                <div class="d-flex a-c">
                    <el-button v-if="form.id" @click="setBgMusic">设置背景音乐</el-button>
                    <el-button @click="router.go(-1)">取消</el-button>
                    <el-button @click="previewTpl" type="primary">预览</el-button>
                </div>
            </div>
            <div class="flex1 ov-hd d-flex">
                <div class="bg-#fff w-200 box-sizing-border over-auto">
                    <MeetingTplList v-if="meetid" :meetid="meetid" @selectItem="selectItem" :list="list"
                        @setIndex="setIndexTpl" @addMeetingTpls="addMeetingTpls" @delete="deleteListTpl"
                        @changeLabel="changeLabel"></MeetingTplList>
                </div>
                <div class="flex1 ov-hd d-flex flex-cln a-c bg-#f7f7f7">
                    <div v-if="form.id" @click="changeLabel(form)" class="w-750 pd2-10-0 f-w-5 f-s-18">
                        {{ form?.label }}
                        <el-icon>
                            <EditPen />
                        </el-icon>
                    </div>
                    <MeetingTplH5 v-if="form.id" v-model="form" @activated="activated"
                        @deleteItemEvents="deleteItemEvents" @muisc="setMuisc"></MeetingTplH5>
                </div>
                <div class="bg-#fff w-300">
                    <MeetingTplEvents v-if="curEvent" v-model="curEvent" :dict="dict" @save="saveEevent" :list="list">
                    </MeetingTplEvents>
                </div>
            </div>
        </div>
    </div>
    <H5ModelLook v-if="showPreviewTpl" v-model:show="showPreviewTpl" :src="previewTplStr" title="预览"></H5ModelLook>
</template>
<script setup lang="ts" name="ptpl-edit-index">
import router from '@/router';
import { MeetingTplH5, MeetingTplList, MeetingTplEvents } from '../../models';
import { useRoute } from 'vue-router';
import { httpRequests } from '@/utils/httpRequests';
import { importFileGetUrls } from '@/utils/models';
import { H5ModelLook } from '@/views/components';

const VITE_APP_MEETING_URL = ref(import.meta.env.VITE_APP_MEETING_URL || '');
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const dict = proxy?.useDict('page_event')
const { page_event } = toRefs<any>(dict);
const showPreviewTpl = ref(false);
// 获取地址栏参数
const meetid = ref<string>('');
const form = ref<any>({});
onMounted(() => {
    const route = useRoute();
    meetid.value = (route.query.meetid as string) || '';
});
const curEvent = ref<any>(null);
const activated = (item: any) => {
    curEvent.value = item;
};
const selectItem = (item: any) => {
    form.value.id = null;
    setTimeout(() => {
        form.value = { ...item };
        curEvent.value = null;
    }, 100);

};
const saveEevent = async (item: any) => {
    if (!form.value?.events || !form.value?.events.length) return;
    const index = form.value.events.findIndex((it: any) => it.id === item.id);
    if (index === -1) return;
    const oldItem = form.value.events[index];
    form.value.events[index] = { ...item, x: oldItem.x, y: oldItem.y, w: oldItem.w, h: oldItem.h };
    // 保存成功
    const res: any = await httpRequests.post(`/dgtmedicine/trainpage/edit`, form.value);
    if (!res || res.code !== 200) return;
    proxy?.$modal.msgSuccess('保存成功');
};
const deleteItemEvents = (item: any) => {
    if (curEvent.value?.id === item.id) {
        curEvent.value = null;
    }
};
// 预览
const previewTplStr = ref<string>('');
const previewTpl = async () => {
    if (!list.value?.length) {
        return proxy?.$modal.msgWarning('请先添加页面');
    }
    previewTplStr.value = `${VITE_APP_MEETING_URL.value}?id=${list.value[0].id}`;
    showPreviewTpl.value = true;
};
const list = ref<any>([]);
const itemsData = ref<any>([]);
const getList = async () => {
    const res: any = await httpRequests.get(`/dgtmedicine/trainpage/listByTrainId/${meetid.value}`,);
    if (!res || res.code !== 200) return;
    list.value = res.data;
};
const addMeetingTpls = async () => {
    const res: any[] = await importFileGetUrls(['png', 'jpg', 'jpeg'], true);
    // 过滤掉code不为200的
    if (!res || !res.length) return;
    const datas = res.filter(item => item.code === 200).map(item => item.data);
    const promises = datas.map(item => {
        return httpRequests.post('/dgtmedicine/trainpage/add', {
            trainId: meetid.value,
            label: '页面名称',
            img: item.url,
            homeFlag: 0,
            events: []
        });
    });
    const results = await Promise.all(promises);
    const successResults = results.filter(item => item && item.code === 200).map(item => item.data);
    if (!successResults.length) return;
    getList();
}
const deleteListTpl = async (item: any) => {
    ElMessageBox({
        title: '删除提示',
        cancelButtonText: '我再看看',
        confirmButtonText: '确认删除',
        showCancelButton: true,
        confirmButtonClass: 'el-button--danger',
        message: h('p', null, [h('div', null, ``), h('div', null, [h('span', null, '删除后页面和触发事件将同步删除，无法撤回，请谨慎操作！')])]),
        callback: async (action: string) => {
            if (action === 'confirm') {
                const res = await httpRequests.get(`/dgtmedicine/trainpage/remove/${item.id}`);
                if (res) {
                    ElMessage.success('删除成功');
                    if (item.id === form.value.id) {
                        form.value = {};
                        curEvent.value = null;
                    }
                    getList();
                }
            }
        }
    });
};
const setIndexTpl = async (item) => {
    ElMessageBox({
        title: '提示',
        cancelButtonText: '我再看看',
        confirmButtonText: '确认设置',
        showCancelButton: true,
        message: h('p', null, [h('div', null, ``), h('div', null, [h('span', null, '是否设置该页面为会议宣传门户首页？')])]),
        callback: async (action: string) => {
            if (action === 'confirm') {
                const res = await httpRequests.get(`/dgtmedicine/trainpage/setHomePage/${item.id}`);
                if (res) {
                    ElMessage.success('设置成功');
                    getList();
                }
            }
        }
    });
}
const setMuisc = (item: any) => {
    if (form.value.id === item.id) {
        form.value = { ...form.value, ...item }
    }
};
const changeLabel = async (item: any) => {
    const { value: label } = await ElMessageBox.prompt('请输入页面名称', '修改页面名称', {
        confirmButtonText: '保存',
        cancelButtonText: '取消',
        inputValue: item.label,
        inputPattern: /^(?!\s*$).+/,
        inputErrorMessage: '页面名称不能为空'
    });
    if (label !== undefined) {
        const res = await httpRequests.post('/dgtmedicine/trainpage/edit', { ...item, label });
        if (res && res.code === 200) {
            ElMessage.success('修改成功');
            getList();
            if (item.id === form.value.id) {
                form.value.label = label;
            }
        }
    }
};
// 设置背景音乐
const setBgMusic = async () => {
    const res: any[] = await importFileGetUrls(['mp3'], false);
    if (!res || !res.length) return;
    const music = res.find(item => item.code === 200);
    if (!music || !music.data || !music.data.url) return;
    form.value.bgMusic = music.data.url;
    const musicParams = {
        id: form.value.id,
        bgmRact: form.value.bgmRact || {
            x: 100,
            y: 100,
            w: 50,
            h: 50
        },
        bgm: music.data.url
    };
    const saveRes = await httpRequests.post('/dgtmedicine/trainpage/setBgm', musicParams);
    if (saveRes && saveRes.code === 200) {
        ElMessage.success('设置背景音乐成功');
        getList();
        if (form.value.id) {
            form.value = { ...form.value, ...musicParams }
        }
    }
};
// 发布页面
const publishTpl = async () => {
    if (!form.value?.id) {
        ElMessage.warning('请先选择一个页面进行发布');
        return;
    };
    const res: any = await httpRequests.post(`/dgtmedicine/trainpage/edit`, form.value);
    if (!res || res.code !== 200) return;
    ElMessage.success('发布成功');
};
onMounted(() => {
    getList();
});
</script>
