<template>
    <el-dropdown trigger="click">
        <div class="el-dropdown-link" :title="$t('message.file')">
            <el-tooltip :content="$t('message.file')">
                <div>
                    <img :src="local_storage" alt="" class="header_right_icon left">
                    <span class="header_right_title_span">{{ $t('message.file') }}</span>
                </div>
            </el-tooltip>
        </div>
        <template #dropdown>
            <el-dropdown-menu>
                <el-dropdown-item class="header_menu_li" @click="cloudSave()" style="color: #26a69a;">{{
                    $t('message.cloud_save') }}</el-dropdown-item>
                <el-dropdown-item class="header_menu_li" @click="importFile()" style="color: #26a69a;">{{
                    $t('message.import') }}</el-dropdown-item>
                <el-dropdown-item class="header_menu_li" @click="exportFile()" style="color: #26a69a;">{{
                    $t('message.Export') }}</el-dropdown-item>
            </el-dropdown-menu>
        </template>
    </el-dropdown>
    <el-dialog v-model="cloudDialog" :title="$t('message.cloud_save')" 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;">
                        <el-icon :size="80" @click="createFile()">
                            <DocumentAdd />
                        </el-icon>
                    </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>
                        <el-icon :size="20">
                            <Edit @click="update($event, item)" />
                        </el-icon><br />
                        <span>{{ $t('message.last_version') }}{{ new Date(item.date).toLocaleDateString() }}</span>
                    </div>
                </el-card>
            </el-col>
        </el-row>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="cloudDialog = false">{{ $t('message.close') }}</el-button>
            </div>
        </template>
    </el-dialog>
    <el-dialog v-model="updateDialog" :title="updateTitle" width="400">
        <el-input v-model="newFilename" style="margin-top: 20px;"></el-input>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="sumbit" type="primary">{{ $t('message.ok') }}</el-button>
                <el-button @click="updateDialog = false">{{ $t('message.close') }}</el-button>
            </div>
        </template>
    </el-dialog>
</template>
<script setup>
import { ref } from 'vue'
import { ElMessage } from 'element-plus'
import { Edit, DocumentAdd } from '@element-plus/icons-vue'
import Blockly from 'blockly';
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'
import { useI18n } from 'vue-i18n'
const { t } = useI18n() // 解构出t方法

const props = defineProps({
    exportImportFileName: {
        type: String
    }
})
const emit = defineEmits(["setFileName"])
const user = userInfo()
const exportXml = store.useyXmlStore()
const importFileName = store.useImportFileNameStore()
const LoadBlocklyStatus = store.useLoadBlocklyStatus()
const cloudDialog = ref(false)
const cloudData = ref([])
const updateDialog = ref(false)
const updateData = ref({})
const newFilename = ref('')
const updateTitle = ref(t('mesage.add'))
const cloudSave = () => {
    if (JSON.stringify(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: t('message.please_login'),
            type: 'warning',
        })
    }
}
// 导入文件
const importFile = () => {
    const input = document.createElement('input');
    input.type = 'file';
    input.accept = '.xml';
    // input.onClick = e => {
    //     e.stopPropagation();
    // }
    input.onchange = e => {
        const file = e.target.files[0];
        const reader = new FileReader();
        reader.onload = e => {
            let xml = e.target.result;
            exportXml.$patch({ xmlStr: xml })
            LoadBlocklyStatus.$patch({ status: true })
            importFileName.$patch({ fileName: file.name })
            emit("setFileName", file.name)
            localStorage.setItem('workspaceXml', xml)
            setTimeout(() => {
                LoadBlocklyStatus.$patch({ status: false })
            }, 100)
        };
        reader.readAsText(file);
    };
    input.click();
}
// 导出文件
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: t('message.export_content_empty'),
            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('内容已复制到剪贴板');
        ElMessage({
            message: t('message.link_copy'),
            type: 'success',
        })
    }).catch(err => {
        console.error('复制到剪贴板失败: ', err);
        ElMessage({
            message: t('message.link_copy_error'),
            type: 'warning',
        })
    });
}
// 删除文件
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: t('message.delete_success'),
                type: 'success',
            })
            cloudSave()
        } else {
            ElMessage({
                message: t('message.delete_error'),
                type: 'error',
            })
        }
    })
}
// 保存文件
const saveFile = (e, name) => {
    e.stopPropagation();
    // https://api.cocorobo.cn/blockx/1716428157190
    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.data == "OK") {
            ElMessage({
                message: t('message.save_success'),
                type: 'success',
            })
        }
        else {
            ElMessage({
                message: t('message.save_error'),
                type: 'error',
            })
        }
    })
}
// 打开文件
const openFile = (e, item) => {
    e.stopPropagation();
    // https://api.cocorobo.cn/blockx/5ed71aeb0ff4fc69b32e866b_1710676497206
    axios.get(`https://api.cocorobo.cn/blockx/${item.filenameid}`).then(res => {
        console.log(res.data.xml)
        if (res.status == 200) {
            let xml = res.data.xml
            if(xml.indexOf('$') == 4){
                xml = xml.slice(5)
            }
            importFileName.$patch({ fileName: item.filename })
            emit("setFileName", item.filename)
            exportXml.$patch({ xmlStr: xml })
            LoadBlocklyStatus.$patch({ status: true })
            localStorage.setItem('workspaceXml', xml)
            setTimeout(() => {
                LoadBlocklyStatus.$patch({ status: false })
                cloudDialog.value = false
            }, 100)
        }
        else {
            ElMessage({
                message: t('message.open_error'),
                type: 'error',
            })
        }
    })
}
// 
const update = (e, item) => {
    updateDialog.value = true
    e.stopPropagation();
    console.log(item)
    updateData.value = item
    newFilename.value = item.filename
    updateTitle.value = t('message.update')
}
const sumbit = () => {
    if (updateTitle.value == t('message.add')) {
        let params = {
            filename: newFilename.value,
            type: '',
            xml: exportXml.xmlStr
        }
        axios.post("https://api.cocorobo.cn/blockx/", params).then(res => {
            console.log(res)
            if (res.statusText == "OK") {
                cloudSave()
                ElMessage({
                    message: t('message.add_success'),
                    type: 'success',
                })
                updateDialog.value = false
            } else {
                ElMessage({
                    message: t('message.add_error'),
                    type: 'error',
                })
            }

        })
    } else {
        let data = {
            currentFilename: updateData.value.filename,
            newFilename: newFilename.value
        }
        axios.put('https://api.cocorobo.cn/blockx/modify', data).then(res => {
            console.log(res)
            if (res.data == "Filename update.") {
                cloudSave()
                ElMessage({
                    message: t('message.update_success'),
                    type: 'success',
                })
                updateDialog.value = false
            } else {
                ElMessage({
                    message: t('message.update_error'),
                    type: 'error',
                })
            }
        })
    }

}
const createFile = () => {
    updateDialog.value = true
    newFilename.value = ""
    updateTitle.value = t('message.add')
}
</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>