import React, { useState, useEffect } from "react";
import { Dropdown, Modal, Space, message, Card, Row, Col, Button, Input } from "antd";
import "../../asstes/css/header.css";
import config from "../../config/config";
import { useSelector, useDispatch } from 'react-redux';
import { updateBlocklyXml, updateFileName } from "../../states/global";
import * as Blockly from 'blockly';

import localStorageIcon from '../../asstes/icon/local_storage.png'
import axios from "axios";
import shareIcon from '../../asstes/icon/share.png';
import deleteIcon from '../../asstes/icon/delete.png';
import saveIcon from '../../asstes/icon/save.png';
import addIcon from '../../asstes/icon/add.png';

export interface cloudType {
    date: String;
    filename: String;
    filenameid: String;
    timestamp: number
}

const File: React.FC = () => {
    const dispatch = useDispatch();
    const userInfo = useSelector((state: any) => state.user);
    const blocklyXml = useSelector((state: any) => state.blocklyXml);
    const blockName = useSelector((state: any) => state.blockName);
    const clouSrc = config.clouUrl;
    const [messageApi, contextHolder] = message.useMessage();
    const [cloudList, setCloudList] = useState<cloudType[]>([]);
    const [modalVisible, setModalVisible] = useState(false);
    const [addShow, setAddShow] = useState(false);
    const [fileName, setFileName] = useState("");

    useEffect(() => {
    }, [])
    const items = [
        {
            label: (<p className="cloud-save ant-dropdown-content-style" onClick={() => cloudSave(1)}>云端存储</p>),
            key: "1",
        },
        {
            label: (<p className="cloud-save ant-dropdown-content-style" onClick={() => importFile()}>导入</p>),
            key: "2",
        },
        {
            label: (<p className="cloud-save ant-dropdown-content-style" onClick={() => exportFile()}>导出</p>),
            key: "3",
        },
    ];
    // 打开云端存储，并获取文件列表
    const cloudSave = (type: number) => {
        console.log("云端存储", userInfo);
        if (JSON.stringify(userInfo) !== "{}" && userInfo.username) {
            axios.defaults.withCredentials = true;
            axios.get(clouSrc + "/blockx/files").then((res) => {
                if (res.data.length > 0) {
                    setCloudList(res.data);
                    if (type === 1) {
                        setModalVisible(true);
                    }
                }
            });
        } else {
            messageApi.error("请先登录！", 1);
        }
    }
    // 导入程序
    const importFile = () => {
        const input = document.createElement("input");
        input.type = "file";
        input.accept = ".xml";
        input.onchange = async (event: any) => {
            const file = event.target.files[0];
            if (file) {
                const reader = new FileReader();
                reader.onload = (e: any) => {
                    const content = e.target.result;
                    if (content) {
                        window.blockly.clear();
                        Blockly.Xml.domToWorkspace(Blockly.utils.xml.textToDom(content), window.blockly)
                        dispatch(updateBlocklyXml(content));
                        dispatch(updateFileName(file.name.slice(0, -4)));
                        messageApi.success("文件导入成功！", 1);
                    } else {
                        messageApi.error("文件内容为空！", 1);
                    }
                };
                reader.onerror = () => {
                    messageApi.error("文件读取失败！", 1);
                };
                reader.readAsText(file);
            }
        };
        input.click();
    }
    // 导出xml 程序
    const exportFile = () => {
        const blob = new Blob([blocklyXml], { type: "text/xml" });
        const url = URL.createObjectURL(blob);
        const a = document.createElement("a");
        a.href = url;
        a.download = blockName || "未命名" + ".xml";
        a.click();
        URL.revokeObjectURL(url);
    }
    // 云端保存
    const cloudSaveFile = () => {
        let params = {
            filename: fileName,
            type: "",
            xml: blocklyXml
        }
        axios.post(clouSrc + "/blockx/", params).then((res) => {
            console.log(res.data);
            if(res.data.filename){
                cloudSave(2);
                setAddShow(false);
                setFileName("");
                messageApi.success("保存成功！", 1);
            }
        });
    }
    // 分享功能
    const shareLink = (e: any, data: any) => {
        e.stopPropagation();
        let text = location.href + "&Qd=" + data.filenameid;
        navigator.clipboard.writeText(text).then(() => {
            messageApi.success('复制成功');
        }).catch((err) => {
            messageApi.error('复制失败');
        });
    }
    // 打开文件
    const openFile = (item: any) => {
        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);
                }
                setModalVisible(false);
                window.blockly.clear();
                Blockly.Xml.domToWorkspace(Blockly.utils.xml.textToDom(xml), window.blockly);
                dispatch(updateBlocklyXml(xml));
                dispatch(updateFileName(item.filename.slice(0, -4)));
                messageApi.success("文件打开成功！", 1);
            }
        }).catch(err=>{
            console.log(err);
        })
    }
    // 删除保存文件
    const deleteFile = (e: any, data: any) => {
        e.stopPropagation();
        axios.delete(clouSrc + "/blockx/" + data.filename).then((res) => {
            if (res.status == 200) {
                cloudSave(2)
                messageApi.success('删除成功');
            }
        });
    }
    // 覆盖之前保存文件
    const saveFile = (e: any, data: any) => {
        e.stopPropagation();
        let form = new FormData();
        let blocklyDom = "main$" + Blockly.Xml.domToPrettyText(Blockly.Xml.workspaceToDom(window.blockly));
        console.log(blocklyDom);
        form.append("filename", data.filename);
        form.append("xml", blocklyDom);
        axios.defaults.withCredentials = true;
        axios.defaults.headers.put['Content-Type'] = 'multipart/form-data';
        axios.put(clouSrc + "/blockx/" + data.filename, form).then(res => {
            console.log(res.data);
            if (res.data == "OK") {
                messageApi.success('保存成功');
            }
        }).catch(err => {
            console.log(err);
        })

    }
    return (<>
        <Dropdown menu={{ items }} trigger={["click"]}>
            <Space>
                {contextHolder}
                <div className="header-right-text">
                    <img src={localStorageIcon} alt="localStorage" className="header-right-icon" />
                    <span>文件</span>
                </div>
            </Space>
        </Dropdown >
        <Modal
            title="云端存储"
            visible={modalVisible}
            onCancel={() => setModalVisible(false)}
            className="file-modal"
            width={700}
            footer={null}
        >
            <Row gutter={16} style={{
                border: '1px solid #ccc', padding: "0 5px 10px",
                borderRadius: '5px', overflowY: 'auto', height:'100%'
            }}>
                <Col style={{ marginTop: 10 }} span={8}>
                    <Card className="add-file-card">
                        {!addShow ? <div className="add-file" onClick={() => setAddShow(true)}>
                            <img style={{ width: "50%" }} src={addIcon} alt="add" />
                            <p style={{ marginLeft: 10 }} >新建文件</p>
                        </div> : <div>
                            <p>另存为</p>
                            <Input onChange={(e) => setFileName(e.target.value)} style={{ marginTop: 8 }} type="text" placeholder="请输入文件名" />
                            <div style={{ marginTop: 8, display: "flex", justifyContent: "space-between" }}>
                                <Button onClick={() => setAddShow(false)}>取消</Button>
                                <Button type="primary" onClick={() => cloudSaveFile()}>保存</Button>
                            </div>
                        </div>}
                    </Card>
                </Col>
                {cloudList.length > 0 && cloudList.map(r => {
                    return <Col key={r.filenameid.toString()} style={{ marginTop: 10 }} span={8}>
                        <Card onClick={() => openFile(r)} hoverable extra={<>
                            <img onClick={(e) => shareLink(e, r)} src={shareIcon} alt="share" className="header-right-icon" />
                            <img onClick={(e) => deleteFile(e, r)} src={deleteIcon} alt="delete" className="header-right-icon" />
                            <img onClick={(e) => saveFile(e, r)} src={saveIcon} alt="save" className="header-right-icon" />
                        </>
                        }>
                            <p>{r.filename}</p>
                            <p>上次修改时间：{new Date(r.date.toString()).toLocaleDateString()}</p>
                        </Card>
                    </Col>
                })}
            </Row>
        </Modal>
    </>
    );
}
export default File;