<!-- 数据源页面 -->

<template>
    <div>
        <div class="buttonSet">
            <el-button type="primary" @click="act_dataSourceOperation(1)">创建</el-button>
        </div>

        <!-- 表格数据 -->
        <el-table :data="g_SpotTableData" border table-layout="fixed" empty-text="暂无数据">
            <el-table-column prop="title" label="名称" />
            <el-table-column prop="typeName" 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 label="操作">
                <template #default="scope">
                    <el-button type="warning" @click="act_dataSourceOperation(2, scope.row)">编辑</el-button>
                </template>
            </el-table-column>
        </el-table>


        <!-- 选择展厅抽屉 -->
        <el-drawer v-if="g_innerDrawer" v-model="g_innerDrawer" :title="g_drawerName" :append-to-body="true" size="45%"
            style="min-width: 350px;" :before-close="act_closeCallback" modal-class="dialog_class">
            <el-form :model="g_form" label-width="auto">
                <el-form-item label="名称">
                    <el-input v-model="g_form.dataSource.title" />
                </el-form-item>

                <el-form-item label="类型">
                    <el-select v-model="g_form.dataSource.type" placeholder="Select" size="large" style="width: 100%"
                        @change="act_dataSourceTypeChange">
                        <el-option v-for="item in g_dataSourceType" :key="item.id" :label="item.title"
                            :value="item.id" />
                    </el-select>
                </el-form-item>

                <!-- <el-form-item label="配置">
                    <el-input v-model="g_form.config" />
                </el-form-item> -->

                <el-form-item label="数据">
                    <!-- 图片类型 -->
                    <ImageUpload v-if="g_form.dataSource.type == 1" ref="imgchildComponentRef_1"
                        :URL="(g_form.data?.indexOf('http') == 0 ? '' : 'https://') + g_form.data"
                        :handleUploadSuccess="act_handleUploadSuccess" />
                    <!-- 视频类型 -->
                    <VideoUpload v-if="g_form.dataSource.type == 2" ref="videochildComponentRef" :URL="g_form.data"
                        :handleUploadSuccess="act_handleUploadSuccess" />
                    <!-- 超链接、文字类型 -->
                    <el-input v-if="g_form.dataSource.type == 3 || g_form.dataSource.type == 4" v-model="g_form.data" />
                </el-form-item>

                <el-form-item label="封面">
                    <ImageUpload ref="imgchildComponentRef_2"
                        :URL="(g_form.cover?.indexOf('http') == 0 ? '' : 'https://') + g_form.cover"
                        :handleUploadSuccess="act_coverUploadSuccess" />
                </el-form-item>

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

    </div>
</template>

<script setup>
/************************************************
 *                   引入文件                   *
 ************************************************/
import { ref, reactive, onMounted } from 'vue'
import { ElMessageBox, ElMessage, ElLoading } from 'element-plus'
import ImageUpload from '@/components/Common/ImageUpload.vue'
import VideoUpload from '@/components/Common/VideoUpload.vue'
import { getGalleryDataSources, updateDataSource, addDataSource } from '@/http/api/pages/DataSources/index'
import { getDataType } from '@/http/api/pages/DataType/index'



/************************************************
 * 全局变量
 * 
 * 格式: g_ + 事件名     例如: getAppDataList
 ************************************************/

// 父组件传递过来的函数
const g_props = defineProps({
    act_updateVisibility: Function,
    get_userAppDataList: Function,
    g_ShowroomDataList: Object,
})

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

// 表格数据
const g_SpotTableData = ref([])


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

// 选择展厅抽屉状态
const g_innerDrawer = ref(false)
// 抽屉类型
const g_drawerType = ref(1)
// 抽屉名称
const g_drawerName = ref("数据源创建")
// 数据源类型
const g_dataSourceType = [
    {
        "id": 1,
        "title": "图片",
        "introduction": "图片类型",
    },
    {
        "id": 2,
        "title": "视频",
        "introduction": "视频类型",
    },
    {
        "id": 3,
        "title": "超链接",
        "introduction": "超链接类型",
    },
    {
        "id": 4,
        "title": "文字",
        "introduction": "文字类型",
    },
    {
        "id": 5,
        "title": "图册",
        "introduction": "图册类型",
    },
    {
        "id": 6,
        "title": "模型",
        "introduction": "模型类型",
    }
]

// 编辑、创建数据
const g_form = reactive({
    dataSource: {
        id: "", // 数据源id
        appId: "", // 展厅id
        spot: "", // 展示点
        title: "", // 数据源名称
        type: "", // 数据源类型
    },
    data: "", // 图片/视频数据url
    cover: "", // 图片缩略图/视频封面url
})




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




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

// 打开抽屉
const act_dataSourceOperation = (type, row) => {
    g_drawerName.value = type == 1 ? "数据源创建" : "数据源编辑"
    g_drawerType.value = type
    g_innerDrawer.value = true
    act_dataSourceInit(row);
}

// 初始化抽屉信息
const act_dataSourceInit = (row) => {
    const isCreate = g_drawerType.value == 1
    g_form.dataSource.id = isCreate ? "" : row.id;
    g_form.dataSource.appId = g_pageType.value;
    g_form.dataSource.spot = isCreate ? "" : row.spot;
    g_form.dataSource.title = isCreate ? "" : row.title;
    g_form.dataSource.type = isCreate ? "" : row.type;
    g_form.cover = isCreate ? "" : row.cover;
    g_form.data = isCreate ? "" : row.url;
    console.log("初始化抽屉信息", g_form)
}

// 数据源类型切换
const act_dataSourceTypeChange = (val) => {
    // console.log(g_form, val)
}

// 数据成功回调
const act_handleUploadSuccess = (res, type) => {
    g_form.data = res.url
}

// 封面上传成功回调
const act_coverUploadSuccess = (res) => {
    g_form.cover = res.url
}

// 提交
const act_onSubmit = async () => {
    if (!g_form.dataSource.title) {
        return ElMessage({
            message: '请输入展厅名称',
            grouping: true,
            type: 'warning',
        });
    }

    if (!g_form.dataSource.type) {
        return ElMessage({
            message: '请选中数据源类型',
            grouping: true,
            type: 'warning',
        });
    }

    let loadingInstance;

    try {
        await ElMessageBox.confirm(
            `${g_drawerType.value == 2 ? "确定修改该数据源吗" : "确定创建该数据源吗"}`,
            '温馨提示',
            {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
            }
        )

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

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

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

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

        g_drawerType.value == 2 ? act_updateDataSource() : act_addDataSource();

    } catch (error) {
        console.log("操作被取消", error);
    } finally {
        if (loadingInstance) {
            loadingInstance.close();
        }
    }

}

// 修改数据源
const act_updateDataSource = () => {
    updateDataSource(g_form).then((res) => {
        if (res.code == 200) {
            ElMessage({
                message: '修改成功',
                grouping: true,
                type: 'success',
            });
            g_SpotTableData.value.find(item => {
                if (item.id == g_form.dataSource.id) {
                    item.title = g_form.dataSource.title;
                    item.type = g_form.dataSource.type;
                    item.url = g_form.data;
                    item.cover = g_form.cover;
                }
            })
            g_innerDrawer.value = false;
        }
    })
}

// 新增数据源
const act_addDataSource = async () => {
    try {
        const res = await addDataSource(g_form);
        if (res.code == 200) {
            ElMessage({
                message: '创建成功',
                grouping: true,
                type: 'success',
            });
            get_SceneDetail();
        } else {
            ElMessage({
                message: res.msg,
                grouping: true,
                type: 'warning',
            });
        }
    } catch (err) {
        ElMessage.error('创建失败!');
    } finally {
        g_innerDrawer.value = false;
    }
}

// 关闭回调
const act_closeCallback = (done) => {
    ElMessageBox.confirm(
        '确定关闭吗？',
        '温馨提示',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    ).then(() => {
        done();
    }).catch(() => {

    })
}

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

// 根据展厅id查询数据源列表
const get_SceneDetail = () => {
    getGalleryDataSources(g_pageType.value).then(res => {
        res.data.forEach(item => {
            item["typeName"] = g_dataSourceType.find(i => i.id == item.type).title;
        })
        g_SpotTableData.value = res.data
    })
}



</script>

<style scoped>
.buttonSet {
    margin-bottom: 8px
}

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

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


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