<template>
    <el-dropdown trigger="click">
        <div class="el-dropdown-link" title="文件">
            <img :src="local_storage" alt="" class="header_right_icon left">
            <span class="header_right_title_span">文件</span>
        </div>
        <template #dropdown>
            <el-dropdown-menu>
                <el-dropdown-item class="header_menu_li" @click="cloudSave()"
                    style="color: #26a69a;">云端存储</el-dropdown-item>
                <el-dropdown-item class="header_menu_li" @click="importFile()"
                    style="color: #26a69a;">导入</el-dropdown-item>
                <el-dropdown-item class="header_menu_li" @click="exportFile()"
                    style="color: #26a69a;">导出</el-dropdown-item>
            </el-dropdown-menu>
        </template>
    </el-dropdown>
    <el-dialog v-model="cloudDialog" title="云端存储" width="800">
        <el-row :gutter="24" style="text-align: center;">
            <el-col :span="7" style="margin-top: 15px;">
                <el-card :body-style="{ padding: '0px' }">
                    <div style="padding: 14px;">

                    </div>
                </el-card>
            </el-col>
            <el-col :span="7" v-for="(item, index) in cloudData" style="margin-top: 15px;">
                <el-card :body-style="{ padding: '0px' }" @click="openFile($event, item)">
                    <div class="cloud_card_top">
                        <img @click="share($event, item.filenameid)" src="../../assets/img/分享.png" alt="">
                        <div>
                            <img @click="saveFile($event, item.filenameid)" src="../../assets//img/save.png" alt="">
                            <img @click="deleteFile($event, item.filename)" src="../../assets//img/delete.png" alt="">
                        </div>
                    </div>
                    <div class="cloud_card_bottom" style="padding: 14px;">
                        <span>{{ item.filename }}</span><br />
                        <span>上次修改：{{ new Date(item.date).toLocaleDateString() }}</span>
                    </div>
                </el-card>
            </el-col>
        </el-row>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="cloudDialog = false">关闭</el-button>
            </div>
        </template>
    </el-dialog>
</template>
<script setup>
import { ref, watchEffect } from 'vue'
import { ElMessage } from 'element-plus'
import Blockly from 'blockly';
import { Plus, Delete } from '@element-plus/icons-vue'
import local_storage from '../../assets/img/local_storage.png'
import '../../assets/css/header.css'
import store from '../../stores/blockly'
import { exportFileGlobal } from '../../gloabl/globalMethods'
import userInfo from '../../stores/modules/userInfo'
import axios from 'axios'
import server from '@/config/index'

const props = defineProps({
    exportImportFileName: {
        type: String
    }
})
const emit = defineEmits(["setFileName"])
const user = userInfo()
const exportXml = store.useyXmlStore()
const importFileName = store.useImportFileNameStore()
const cloudDialog = ref(false)
const cloudData = ref([])
const cloudSave = () => {
    console.log("云端存储", user.userInfo, server)
    if (JSON.stringify(user.userInfo) != "{}") {
        console.log("云端存储", user.userInfo)
        axios.defaults.withCredentials = true
        axios.changeOrigin = true
        axios.get(`${server.host}blockx/files`).then(res => {
            console.table(res.data)
            cloudData.value = res.data
        })
        cloudDialog.value = true
    } else {
        ElMessage({
            message: '请先登录',
            type: 'warning',
        })
    }
}
const importFile = () => {
    console.log("导入xml文件", importFileName)
    importFileName.$patch({ fileName: "2222" })
    emit("setFileName", "22")
}
// console.log(getCurrentInstance().appContext.config.globalProperties)
// $exportFile(exportXml,props.exportImportFileName + '.xml')
const exportFile = () => {
    let name = props.exportImportFileName + '.xml'
    if (exportXml.xmlStr && exportXml.xmlStr != `<xml xmlns="https://developers.google.com/blockly/xml"></xml>`) {
        exportFileGlobal(exportXml.xmlStr, name)
    } else {
        ElMessage({
            message: '导出内容为空',
            type: 'warning',
        })
    }

    // let blob = new Blob([exportXml], { type: 'text/plain;charset=utf-8' })
    // // 创建一个指向Blob对象的URL
    // const textURL = window.URL.createObjectURL(blob);
    // // 创建一个临时的a标签用于触发下载
    // const link = document.createElement('a');
    // link.href = textURL;
    // link.download = props.exportImportFileName + '.xml'; // 指定下载文件的名称
    // document.body.appendChild(link); // 将a标签添加到文档中
    // // 触发点击事件以开始下载
    // link.click();

    // // 清理：移除a标签，释放创建的URL
    // document.body.removeChild(link);
    // window.URL.revokeObjectURL(textURL);
}
const share = (e, id) => {
    e.stopPropagation();
    // console.log("分享", location.href)
    // "https://beta.v.cocorobo.cn/?lang=zh-hans&Qd=5ed71aeb0ff4fc69b32e866b_1721619372665";
    const text = location.href + "&Qd=" + id;
    navigator.clipboard.writeText(text).then(() => {
        console.log('内容已复制到剪贴板');
    }).catch(err => {
        console.error('复制到剪贴板失败: ', err);

    });
}

const deleteFile = (e, id) => {
    e.stopPropagation();
    // https://api.cocorobo.cn/blockx/1721619372665
    axios.delete(`https://api.cocorobo.cn/blockx/${id}`).then(res => {
        console.log(res)
        if (res.status == 200) {
            ElMessage({
                message: '删除成功',
                type: 'success',
            })
            cloudSave()
        } else {
            ElMessage({
                message: '删除失败',
                type: 'error',
            })
        }
    })
}

const saveFile = (e, name) => {
    e.stopPropagation();
    // https://api.cocorobo.cn/blockx/1716428157190
    console.log("保存文件", exportXml.xmlStr)
    let form = new FormData()
    // form.append('platformType', "CocoPi")
    form.append('filename', name)
    form.append('xml', exportXml.xmlStr)
    // form.append('code', "")
    axios.put(`https://api.cocorobo.cn/blockx/${name}`, form).then(res => {
        console.log(res)
        if (res.status == 200) {
            ElMessage({
                message: '保存成功',
                type: 'success',
            })
        }
        else {
            ElMessage({
                message: '保存失败',
                type: 'error',
            })
        }
    })
}

const openFile = (e, item) => {
    e.stopPropagation();
    // https://api.cocorobo.cn/blockx/5ed71aeb0ff4fc69b32e866b_1710676497206
    console.log("打开文件", item)
    axios.get(`https://api.cocorobo.cn/blockx/${item.filenameid}`).then(res => {
        console.log(res.data.xml.split("$")[1])
       if (res.status == 200) {
            exportXml.xmlStr = res.data.xml.split("$")[1]
            importFileName.$patch({ fileName: item.filename })
            emit("setFileName", item.filename)
        }
        else {
            ElMessage({
                message: '打开失败',
                type: 'error',
            })
        }
    })
}
</script>
<style scoped lang="scss">
.cloud_card_top {
    display: flex;
    justify-content: space-between;
    background-color: #454fb5;
    padding: 8px 10px;

    img {
        width: 25px;
        height: 25px;
    }
}
</style>