<!-- 展示点页面 -->

<template>
    <div class="spotBox">

        <!-- 表格数据 -->
        <TablePaging :data="g_SpotTableData">
            <template #table>
                <el-table-column prop="name" label="名称" />

                <el-table-column label="类型">
                    <template #default="scope">
                        {{ drawerBank.g_typeMapping[scope.row.type] }}
                    </template>
                </el-table-column>

                <el-table-column label="封面">
                    <template #default="scope">
                        <el-image class="avatar"
                            :src="(scope.row.cover?.indexOf('http') == 0 ? '' : 'https://') + scope.row.cover"
                            fit="cover" />
                    </template>
                </el-table-column>
                <el-table-column prop="dataUrl" label="数据地址" />

                <el-table-column label="操作" width="100">
                    <template #default="scope">
                        <el-button type="warning" @click="act_spotOperation(2, scope.row)">编辑</el-button>
                    </template>
                </el-table-column>
            </template>
        </TablePaging>


        <!-- 展示点抽屉 -->
        <el-drawer v-model="drawerBank.g_innerDrawer" :title="drawerBank.g_drawerName" :append-to-body="true" size="45%"
            style="min-width: 300px;" modal-class="dialog_class">
            <el-form :model="g_form" label-width="auto">
                <el-form-item label="名称">
                    <el-input v-model="g_form.name" />
                </el-form-item>

                <el-form-item label="类型">
                    <el-input v-model="drawerBank.g_typeMapping[g_form.type]" disabled />
                </el-form-item>

                <el-form-item label="数据源">
                    <el-input v-model="g_form.dataUrl" disabled />
                    <el-button type="danger" style="margin-left: 10px;" @click="act_onUnloadDataSource()">卸载</el-button>
                    <el-button type="primary" style="margin-left: 10px;"
                        @click="act_onSelectDataSource()">选择</el-button>
                </el-form-item>

                <div v-if="g_form.type == 1">
                    <el-form-item label="显示缩略图">
                        <el-switch v-model="g_form.config.isCover" active-text="是" active-value="1" inactive-text="否"
                            inactive-value="0" />
                    </el-form-item>
                    <el-form-item label="封面" v-show="g_form.config.isCover == 1">
                        <ImageUpload ref="imgchildComponentRef"
                            :URL="(g_form.coverUrl?.indexOf('http') == 0 ? '' : 'https://') + g_form.coverUrl"
                            :handleUploadSuccess="act_handleUploadSuccess" />
                    </el-form-item>
                    <el-form-item label="显示文字">
                        <el-switch v-model="g_form.config.isText" active-text="是" active-value="1" inactive-text="否"
                            inactive-value="0" />
                    </el-form-item>
                    <el-form-item label="文字" v-show="g_form.config.isText == 1">
                        <el-input v-model="g_form.config.textUrl" />
                    </el-form-item>
                </div>

                <div v-if="g_form.type == 2">
                    <el-form-item label="显示缩略图">
                        <el-switch v-model="g_form.config.isCover" active-text="是" active-value="1" inactive-text="否"
                            inactive-value="0" />
                    </el-form-item>
                    <el-form-item label="封面" v-if="g_form.config.isCover == 1">
                        <ImageUpload ref="imgchildComponentRef"
                            :URL="(g_form.coverUrl?.indexOf('http') == 0 ? '' : 'https://') + g_form.coverUrl"
                            :handleUploadSuccess="act_handleUploadSuccess" />
                    </el-form-item>
                    <el-form-item label="自动播放视频">
                        <el-switch v-model="g_form.config.isAuto" active-text="是" active-value="1" inactive-text="否"
                            inactive-value="0" />
                    </el-form-item>
                    <el-form-item label="视频打开方式">
                        <el-switch v-model="g_form.config.videoType" active-text="打开网页" active-value="1"
                            inactive-text="页面内打开" inactive-value="0" />
                    </el-form-item>
                    <el-form-item label="视频">
                        <VideoUpload ref="videochildComponentRef" :URL="g_form.coverUrl"
                            :handleUploadSuccess="act_handleUploadSuccess" />
                    </el-form-item>
                </div>

                <div v-if="g_form.type == 3">
                    <el-form-item label="超链接" v-if="g_form.type == 3">
                        <el-input v-model="g_form.coverUrl" />
                    </el-form-item>
                    <el-form-item label="打开方式">
                        <el-switch v-model="g_form.config.videoType" active-text="打开新网页" active-value="1"
                            inactive-text="当前页面切换" inactive-value="0" />
                    </el-form-item>
                </div>

                <div v-if="g_form.type == 4">
                    <el-form-item label="图册" v-if="g_form.type == 4">
                        <div v-for="item in (g_form.coverUrl || '').split(',')">
                            <ImageUpload ref="imgchildComponentRef"
                                :URL="(item?.indexOf('http') == 0 ? '' : 'https://') + item"
                                :handleUploadSuccess="act_handleUploadSuccess" />
                        </div>
                    </el-form-item>
                    <el-form-item label="打开方式">
                        <el-switch v-model="g_form.config.atlasType" active-text="图册" active-value="1"
                            inactive-text="轮播" inactive-value="0" />
                    </el-form-item>
                </div>

                <div v-if="g_form.type == 4">
                    <el-form-item label="模型" v-if="g_form.type == 5">
                        <el-input v-model="g_form.coverUrl" />
                    </el-form-item>
                </div>

                <el-form-item>
                    <el-button type="primary" @click="act_onSubmit">{{ g_pageType ? "修改" : "创建" }}</el-button>
                </el-form-item>
            </el-form>


            <!-- 选择数据源 -->
            <el-drawer v-model="drawerBank.g_dataSourceDrawer" :title="drawerBank.g_dataSourceDrawerName"
                :append-to-body="true" size="40%" style="min-width: 350px;" modal-class="dialog_class">
                <el-form>

                    <el-form-item>
                        <TablePaging :data="drawerBank.g_dataSourceDrawerTableData"
                            :current-change="act_handleCurrentChange">
                            <template #table>
                                <el-table-column prop="title" label="名称" />
                                <el-table-column label="类型">
                                    <template #default="scope">
                                        {{ drawerBank.g_typeMapping[String(scope.row.type)] }}
                                    </template>
                                </el-table-column>
                                <el-table-column prop="url" label="地址" />
                                <el-table-column label="缩略图">
                                    <template #default="scope">
                                        <el-image class="avatar"
                                            :src="(scope.row.cover?.indexOf('http') == 0 ? '' : 'https://') + scope.row.cover"
                                            fit="cover" />
                                    </template>
                                </el-table-column>

                                <el-table-column prop="spot" label="点位" />
                            </template>
                        </TablePaging>

                        <!-- <el-table :data="drawerBank.g_dataSourceDrawerTableData" border style="width: 100%"
                            @current-change="act_handleCurrentChange" empty-text="暂无数据">
                            <el-table-column prop="title" label="名称" />
                            <el-table-column label="类型">
                                <template #default="scope">
                                    {{ g_dataSourceType[scope.row.type] }}
                                </template>
                            </el-table-column>
                            <el-table-column prop="url" label="地址" />

                            <el-table-column label="缩略图">
                                <template #default="scope">
                                    <el-image class="avatar" :src="'http://' + scope.row.cover" fit="cover" />
                                </template>
                            </el-table-column>

                            <el-table-column prop="spot" label="点位" />
                        </el-table> -->

                    </el-form-item>

                    <el-form-item>
                        <el-button type="primary" @click="act_ensureDataSource">确定</el-button>
                    </el-form-item>
                </el-form>
            </el-drawer>

        </el-drawer>

    </div>
</template>

<script setup>
/************************************************
 *                   引入文件                   *
 ************************************************/
import { ref, reactive, onMounted } from 'vue'
import { ElMessageBox, ElMessage, ElLoading } from 'element-plus'
import TablePaging from '@/components/Common/TablePaging.vue'
import { getUserScenepot, getDataSourceList, updateSpot, getDataSourceBySpot } from '@/http/api/pages/Spot/index'
import { uninstallDataSource, mountDataSource } from '@/http/api/pages/DataSources/index'
import ImageUpload from '@/components/Common/ImageUpload.vue'
import VideoUpload from '@/components/Common/VideoUpload.vue'


/************************************************
 * 全局变量
 *
 * 格式: g_ + 事件名     例如: getAppDataList
 ************************************************/
// 父组件传递过来的函数
const g_props = defineProps({
    act_updateVisibility: Function,
    get_userScenesDataList: Function,
    g_SceneDataList: Object,
})

// 子组件引用
const imgchildComponentRef = ref(null);
const videochildComponentRef = ref(null);

const value3 = ref(true)
// 数据源类型
const g_dataSourceType = {
    1: "Unity版本",
    2: "全景版本"
}
// 表格数据
const g_SpotTableData = ref([])

// 页面类型 如果有id 则是编辑页面 如果没有id 则是新增页面
const g_pageType = ref(g_props.g_SceneDataList.id)

const drawerBank = reactive({
    // 展示点抽屉
    g_innerDrawer: false, // 状态
    g_drawerType: '1', // 类型
    g_drawerName: '数据源创建', // 名称
    // 数据源抽屉
    g_dataSourceDrawer: false, // 状态
    g_dataSourceDrawerName: '数据源选择', // 名称
    g_dataSourceDrawerTableData: [], // 表格数据
    // 配置映射
    g_configurationMapping: {
        isText: `超链接本页面加载`, // 视频类型
        textUrl: "",
    },
    // 类型映射
    g_typeMapping: {
        '1': '图片',
        '2': '视频',
        '3': '超链接',
        '4': '文字',
        '5': '图册',
        '6': '模型'
    },
})

// 编辑、创建数据
const g_form = reactive({
    "id": "", // id
    "name": "", // 名称
    "type": "", // 类型
    "coverUrl": "", // 封面url
    "dataUrl": "", // 数据url
    "dataSourceName": "", // 数据源名称
    "config": {} // 配置
})

// 数据源暂存
const g_dataSource = reactive({
    "id": "", // id
    "dataUrl": "",  // 数据源地址
    "dataSourceName": "" // 数据源名称
})


/************************************************
 * 生命周期函数
 ************************************************/
// 挂载完成
onMounted(() => {
    act_onInit();
})

/************************************************
* 事件处理
*
* 格式: act_ + 事件名     例如: getAppDataList
************************************************/
// 初始化页面
const act_onInit = () => {
    if (g_pageType.value) {
        get_SceneDetail();
    }
}

// 编辑展示点
const act_spotOperation = (type, row) => {
    drawerBank.g_drawerName = type == 1 ? "展示点创建" : "展示点编辑";
    drawerBank.g_drawerType = type;
    drawerBank.g_innerDrawer = true;
    // if (row.dataUrl) {
    // act_getDataSource({ sceneId: g_pageType.value, spotId: row.id }, (dataSource) => act_SpotInit(row, dataSource))
    // } else {
    act_SpotInit(row, {});
    // }
}

// 初始化抽屉信息
const act_SpotInit = (row, dataSource) => {
    console.log(row);
    const isCreate = drawerBank.g_drawerType == 1
    g_form.id = isCreate ? "" : row.id
    g_form.name = isCreate ? "" : row.name
    g_form.coverUrl = isCreate ? "" : row.coverUrl
    g_form.dataSourceId = isCreate ? "" : row.dataSourceId
    g_form.dataUrl = isCreate ? "" : row.dataUrl
    g_form.dataSourceName = isCreate ? "" : row.dataSourceName
    g_form.type = isCreate ? "" : row.type
    g_form.config = isCreate ? "" : JSON.parse(row.config)
}

// 选择数据源
const act_onSelectDataSource = () => {
    drawerBank.g_dataSourceDrawer = true
    get_DataSource()
}

const act_getDataSource = ({ sceneId, spotId }, callback) => {
    getDataSourceBySpot({ sceneId, spotId }).then(res => {
        if (res.code == 200) {
            if (callback) callback(res.data);
        } else {
            ElMessage({
                message: res.msg,
                type: 'error',
            })
        }
    })
}

// 卸载数据源
const act_onUnloadDataSource = () => {
    if (g_form.dataSourceId) {
        const dataList = {
            dataSourceId: g_form.dataSourceId,
            sceneId: g_pageType.value,
            spotId: g_form.id
        }
        uninstallDataSource(dataList).then(res => {
            if (res.code == 200) {
                g_form.dataSourceId = "";
                g_form.coverUrl = "";
                g_form.dataUrl = "";
                ElMessage({
                    message: "卸载成功",
                    type: 'success',
                })
            } else {
                ElMessage({
                    message: res.msg,
                    type: 'error',
                })
            }
        })
    }
}

// 挂载数据源
const act_onMountDataSource = (dataSource) => {
    console.log("dataSource", dataSource);
    if (g_form.dataUrl) {
        // 先卸载
        uninstallDataSource({
            dataSourceId: g_form.dataSourceId,
            sceneId: g_pageType.value,
            spotId: g_form.id
        }).then(res => {
            if (res.code == 200) {
                g_form.dataSourceId = "";
                g_form.coverUrl = "";
                g_form.dataUrl = "";
                // 后挂载
                mountDataSource({
                    dataSourceId: dataSource.id,
                    sceneId: g_pageType.value,
                    spotId: g_form.id
                }).then(res => {
                    if (res.code == 200) {
                        g_form.dataSourceId = dataSource.id;
                        g_form.coverUrl = dataSource.coverUrl;
                        g_form.dataUrl = dataSource.dataUrl;
                        get_SceneDetail();
                        ElMessage({
                            message: "挂载成功",
                            type: 'success',
                        })
                    } else {
                        ElMessage({
                            message: res.msg,
                            type: 'error',
                        })
                    }
                })
            } else {
                ElMessage({
                    message: res.msg,
                    type: 'error',
                })
            }
        })
    } else {
        mountDataSource({
            dataSourceId: dataSource.id,
            sceneId: g_pageType.value,
            spotId: g_form.id
        }).then(res => {
            if (res.code == 200) {
                g_form.dataSourceId = dataSource.id;
                g_form.coverUrl = dataSource.coverUrl;
                g_form.dataUrl = dataSource.dataUrl;
                get_SceneDetail();
                ElMessage({
                    message: "挂载成功",
                    type: 'success',
                })
            } else {
                ElMessage({
                    message: res.msg,
                    type: 'error',
                })
            }
        })
    }
}

// 提交
const act_onSubmit = async () => {
    console.log('submit!', g_form)

    let loadingInstance;

    try {
        await ElMessageBox.confirm(
            `${g_pageType.value ? "确定修改该场景吗" : "确定创建该场景吗"}`,
            '温馨提示',
            {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
            }
        )

        loadingInstance = ElLoading.service({
            lock: true,
            text: '上传中，请稍候...',
            background: 'rgba(0, 0, 0, 0.7)',
        });

        if (imgchildComponentRef.value && imgchildComponentRef.value.isFileChanged) {
            await imgchildComponentRef.value.act_uploadFiles();
        }

        g_pageType.value ? act_updateScene() : act_addScene();
        g_props.act_updateVisibility();
    } catch (error) {
        console.log("操作被取消", error);
    } finally {
        if (loadingInstance) {
            loadingInstance.close();
        }
    }
}

// 上传成功回调
const act_handleUploadSuccess = (res, type) => {
    type == "img" ? g_form.coverUrl = res.url : g_form.coverUrl = res.url
}

// 查询
const act_inquire = () => {
    // if (!g_queryCondition.title) {
    //     return ElMessage({
    //         message: '请输入查询条件',
    //         grouping: true,
    //         type: 'warning',
    //     })
    // }
}

// 切换配置
const act_handleSelectionChange = (val) => {
    console.log(val)
}

// 选择数据源
const act_handleCurrentChange = (val) => {
    console.log(val)
    if (val) {
        g_dataSource.id = val.id
        g_dataSource.dataUrl = val.url
        g_dataSource.dataSourceName = val.title
        g_dataSource.coverUrl = val.cover
    }
}

// 确定选择数据源
const act_ensureDataSource = () => {
    ElMessageBox.confirm(
        '确定选择该数据源吗?',
        '温馨提示',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    ).then(() => {
        act_onMountDataSource(JSON.parse(JSON.stringify(g_dataSource)));
        drawerBank.g_dataSourceDrawer = false;
        g_dataSource.id = "";
        g_dataSource.dataUrl = "";
        g_dataSource.dataSourceName = "";
        g_dataSource.coverUrl = "";
    }).catch(() => {

    })
}

// 修改展示点
const act_updateScene = () => {
    updateSpot({
        sceneId: g_props.g_SceneDataList.id,
        spot: g_form
    }).then((res) => {
        g_props.get_userScenesDataList();
        ElMessage({
            message: '修改成功',
            grouping: true,
            type: 'success',
        })
    })
}

// 新增场景
const act_addScene = () => {
    // addScenes(g_form).then((res) => {
    //     g_props.get_userScenesDataList();
    //     ElMessage({
    //         message: '创建成功',
    //         grouping: true,
    //         type: 'success',
    //     })
    // }).catch(err => {
    //     console.log(err)
    // })
}

// 格式化配置字段
const act_formatConfigData = (data) => {
    const mappingObject = {
        isCover: "显示缩略图",
        isAuto: "自动播放视频",
        videoType: "视频打开方式",
    }
    data.forEach((item) => {
        const config = JSON.parse(item.config)
        if (config) {
            item.config = [{
                label: Object.keys(config)[0],
                value: Object.values(config)[0],
            }]
        }
    });
}


/************************************************
 * 获取数据
 *
 * 格式: get_ + 事件名     例如: get_AppDataList
 ************************************************/

// 根据用户场景查询展示点列表
const get_SceneDetail = () => {
    getUserScenepot(g_pageType.value).then(res => {
        console.log("展示点", res)
        if (res.code == 200) {
            // act_formatConfigData(res.data)
            g_SpotTableData.value = res.data
        }
    })
}

// 根据展厅id查询数据源列表
const get_DataSource = () => {
    getDataSourceList(g_props.g_SceneDataList.appId).then(res => {
        console.log("数据源", res)
        drawerBank.g_dataSourceDrawerTableData = res.data

        console.log("数据源", res)
    })
}


</script>

<style scoped>
.spotBox {
    height: 100%
}

.buttonSet {
    margin-bottom: 8px
}

::v-deep .el-input {
    flex: 1;
}

::v-deep .el-form-item__content {
    display: flex;
    justify-content: center;
    flex-wrap: wrap;
    ;
}
</style>

<style>
.dialog_class {
    background-color: rgb(0, 0, 0, 0) !important;
}
</style>