<!-- 创建场景&修改场景 -->

<template>
    <div>
        <!-- 表单数据 -->
        <el-form v-if="g_isLoaded" :model="g_form" label-width="auto">
            <el-form-item label="归属展厅">
                <el-input v-model="g_form.appName" disabled />
                <el-button type="primary" style="margin-left: 10px;"
                    @click="act_openSecondaryDrawer(1)">选择展厅</el-button>
            </el-form-item>

            <el-form-item label="场景名称">
                <el-input v-model="g_form.title" />
            </el-form-item>

            <el-form-item label="挂载模板">
                <el-input v-model="g_form.templateName" disabled />
                <el-button v-if="!g_pageType" type="primary" style="margin-left: 10px;"
                    @click="act_openSecondaryDrawer(2)">选择模板</el-button>
            </el-form-item>

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

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

        <!-- 选择展厅抽屉 -->
        <el-drawer v-model="g_innerDrawer" :title="g_secondaryDrawerType == 1 ? '选择展厅' : '选择模板'" :append-to-body="true"
            size="45%" style="min-width: 350px;" modal-class="dialog_class">

            <!-- 查询展厅 -->
            <el-form v-if="g_secondaryDrawerType == 1" class="form-custom">
                <el-form-item label="展厅名称">
                    <el-input v-model="g_queryCondition.title" />
                    <el-button type="primary" style="margin-left: 10px;" @click="act_inquire">查询</el-button>
                </el-form-item>

                <!-- 表格数据 -->
                <TablePaging :data="g_galleryTableData" :currentChange="act_handleCurrentChange">
                    <template #table>
                        <el-table-column prop="title" label="展厅名称" width="180" />
                        <el-table-column prop="introduction" label="简介" />
                    </template>
                </TablePaging>

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


            <!-- 查询模板 -->
            <el-form v-if="g_secondaryDrawerType == 2" class="form-custom">
                <el-form-item label="模板名称">
                    <el-input v-model="g_queryCondition.title" />
                    <el-button type="primary" style="margin-left: 10px;" @click="act_inquire">查询</el-button>
                </el-form-item>

                <!-- 表格数据 -->
                <TablePaging :data="g_TemplateTableData" :currentChange="act_handleCurrentChange">
                    <template #table>
                        <el-table-column prop="title" label="模板名称" width="180" />
                        <el-table-column prop="introduction" label="简介" />
                    </template>
                </TablePaging>

                <el-form-item>
                    <el-button type="success" @click="act_ensureGallert">确定</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 { getScenesDetail, updateScenes, addScenes } from '@/http/api/pages/Scene/index'
import { getAppsDetail, getAppsList, getUserAppsList } from '@/http/api/pages/Gallery/index'
import { getTemplatesList, getTemplatesDetail, getTemplatesBuyList } from '@/http/api/pages/Template/index'
import ImageUpload from '@/components/Common/ImageUpload.vue'
import TablePaging from '@/components/Common/TablePaging.vue'
import { useMySceneStore } from "@/store/index";


/************************************************
 * 全局变量
 * 
 * 格式: g_ + 事件名     例如: getAppDataList
 ************************************************/
// 获取我的场景
const g_useMySceneStore = useMySceneStore();

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

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

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

// 查询条件表单
const g_queryCondition = reactive({
    title: "", // 展厅\模板名称
    userId: g_props.g_SceneDataList.userId, // 用户id
})

// 待确认表单
const g_confirmedForm = reactive({
    appName: "", // 展厅名称
    appId: "",// 展厅id
    templateName: "", // 模板名称
    templateId: "", // 模板id
})

// 表单数据
const g_form = reactive({
    id: g_props.g_SceneDataList.id,
    appName: "", // 展厅名称
    appId: "", // 展厅id
    cover: "", // 场景缩略图
    title: "", // 场景名称
    spot: "", // 展示点
    templateName: "", // 模板名称
    templateId: "", // 模板id
    type: "", // 类型
    status: "", // 状态
    userId: g_props.g_SceneDataList.userId
})

// 二级抽屉类型
const g_secondaryDrawerType = ref(1)
// 选择展厅抽屉状态
const g_innerDrawer = ref(false)

// 展厅表格数据
const g_galleryTableData = ref([])
const g_TemplateTableData = ref([])

// 加载状态
const g_isLoaded = ref(false)


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




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

// 提交
const act_onSubmit = async () => {
    if (!g_form.appId) {
        ElMessage({
            message: '请选择归属展厅',
            grouping: true,
            type: 'warning',
        })
        return
    }

    if (!g_form.title) {
        ElMessage({
            message: '请输入场景名称',
            grouping: true,
            type: 'warning',
        })
        return
    }

    if (!g_form.templateId) {
        ElMessage({
            message: '请选择挂载模板',
            grouping: true,
            type: 'warning',
        })
        return
    }

    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.cover = res.url : g_form.video = res.url
}

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

// 打开二级抽屉
const act_openSecondaryDrawer = (type) => {
    // type  1:展厅  2:模板
    g_secondaryDrawerType.value = type;
    type == 1 ? get_userScenesDataList() : get_userTemplatesDataList();
    g_innerDrawer.value = true;
}

// 选择展厅
const act_handleCurrentChange = (val) => {
    if (g_secondaryDrawerType.value == 1) {
        g_confirmedForm.appName = val?.title
        g_confirmedForm.appId = val?.id
    } else {
        g_confirmedForm.templateName = val?.title
        g_confirmedForm.templateId = val?.id
    }
}

// 确定选择展厅
const act_ensureGallert = () => {
    // 关闭抽屉
    g_innerDrawer.value = false;
    if (g_secondaryDrawerType.value == 1) {
        g_form.appId = g_confirmedForm.appId;
        g_form.appName = g_confirmedForm.appName;
    } else {
        g_form.templateName = g_confirmedForm.templateName;
        g_form.templateId = g_confirmedForm.templateId;
    }
}

// 修改场景信息
const act_updateScene = () => {
    updateScenes(g_form).then((res) => {
        g_useMySceneStore.updateFlag = true;
        g_props.get_userScenesDataList();
        ElMessage({
            message: '修改成功',
            grouping: true,
            type: 'success',
        })
    })
}

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



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

// 获取场景详细信息
const getSceneDetail = () => {
    getScenesDetail(g_pageType.value).then((res1) => {
        g_form.title = res1.data.title;
        g_form.appId = res1.data.appId;
        g_form.spot = res1.data.spot;
        g_form.templateId = res1.data.templateId;
        g_form.cover = res1.data.cover;
        g_form.type = res1.data.type;
        g_form.status = res1.data.status;

        // 获取展厅数据
        getAppsDetail(res1.data.appId).then((res2) => {
            g_form.appName = res2.data.title;
        })

        // 获取模板数据
        getTemplatesDetail(res1.data.templateId).then((res) => {
            g_form.templateName = res.data.title;
        })

        g_isLoaded.value = true;

    })
}

// 获取用户展厅列表
const get_userScenesDataList = () => {
    getUserAppsList(g_props.g_SceneDataList.userId).then((res) => {
        console.log("获取用户展厅列表", g_props.g_SceneDataList.userId, res)
        g_galleryTableData.value = res.data
    })
}

// 获取查询列表
const get_queryDataList = () => {
    if (g_secondaryDrawerType.value == 1) {
        getAppsList(g_queryCondition).then((res) => {
            g_galleryTableData.value = res.data
        })
    } else {
        getTemplatesList(g_queryCondition).then((res) => {
            g_TemplateTableData.value = res.data
        })
    }

}

// 获取用户已购买模板
const get_userTemplatesDataList = () => {
    // 获取模板数据
    getTemplatesBuyList(g_form.userId).then((res) => {
        g_TemplateTableData.value = res.data;
    })
}


</script>

<style scoped>
.form-custom {
    flex: 1;
    display: flex;
    flex-direction: column
}

::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>