function getDateDaysBefore(daysAgo) {
    let dateStr = new Date().toISOString().substring(0, 10);
    return new Date(dateStr).getTime() - daysAgo * 24 * 3600 * 1000;
}

const primaryColor = "#2E324C";

// ======Vue start
let headerVue = "";
let pubkeyDialogVue = "";
let mainVue = "";
let toastVue = "";
let select = "";

function initVue() {
    console.log("[nodePortal.js] initVue : ");
    headerVue = new Vue({
        el: 'header',
        data: {
            shortName: "00000"
        }
    });
    pubkeyDialogVue = new Vue({
        el: '#pubkeyDialog',
        data: {
            sm2KeyStr: "00000",
            myRole: "匿名用户",
            test: "0",
            selectedSM2Key: "0",
            productList: [{id: 0, title: "ContractProvider"}, {id: 1, title: "ContractUser"}, {
                id: 2,
                title: "ContractInstanceManager"
            }],
            sm2KeyList: []
        },
        methods: {
            importPubkey: function () {
                console.log("importkey trigged");
                try {
                    let sm2Key = JSON.parse(this.sm2KeyStr);
                    if (!sm2Key.publicKey || !sm2Key.privateKey) {
                        this.sm2KeyStr = (JSON.stringify(global.sm2Key));
                    } else {
                        if (sm2Key.publicKey.search("\\.") != -1 || sm2Key.publicKey.search("\\.\\.") != -1 || sm2Key.publicKey.search("/") != -1 || sm2Key.publicKey.search("\\\\") != -1) {
                            myToast("导入失败", "不是合法的公钥!");
                            return;
                        }
                        if (sm2Key.privateKey.search("\\.") != -1 || sm2Key.privateKey.search("\\.\\.") != -1 || sm2Key.privateKey.search("/") != -1 || sm2Key.privateKey.search("\\\\") != -1) {
                            myToast("导入失败", "不是合法的私钥!");
                            return;
                        }
                        global.sm2Key = sm2Key;
                        localStorage.setItem("PrivKey", JSON.stringify(sm2Key));
                        headerVue.shortName = global.sm2Key.publicKey.substr(0, 5);
                        let newKey = {};
                        newKey.id = this.sm2KeyList.length;
                        newKey.title = headerVue.shortName;
                        newKey.sm2Key = this.sm2KeyStr;
                        this.sm2KeyList.push(newKey);
                        localStorage.setItem("PrivKeyList", JSON.stringify(this.sm2KeyList));
                        getSession();
                        listProjects("priv");
                    }
                } catch (e) {
                    console.log(e);
                    this.sm2KeyStr = (JSON.stringify(global.sm2Key));
                }
            },
            generatePubkey: function () {
                console.log("generate pubkey trigged");
                let sm2Key = sm2.generateKeyPairHex();
                this.sm2KeyStr = JSON.stringify(sm2Key);
                global.sm2Key = sm2Key;
                localStorage.setItem("PrivKey", JSON.stringify(sm2Key));
                headerVue.shortName = global.sm2Key.publicKey.substr(0, 5);
                let newKey = {};
                newKey.id = this.sm2KeyList.length;
                newKey.title = headerVue.shortName;
                newKey.sm2Key = this.sm2KeyStr;
                this.sm2KeyList.push(newKey);
                this.selectedSM2Key = newKey.id;
                localStorage.setItem("PrivKeyList", JSON.stringify(this.sm2KeyList));
                getSession();
            },
            changeProduct(event) {
                this.test = event.target.value; // 获取option对应的value值
                this.role = this.productList[this.test].title;
                // console.log("选了", this.role);
                global.role = this.role;
            },
            apply: function () {
                console.log("apply");
                global.wssocket
                    .send("{\"action\":\"applyNet\",\"role\":\"NodeManager\"}");

            },
            applyRole: function () {
                let role = this.productList[this.test];
                // console.log("applyRole, " + role);
                applyRole(role.title);

            }, changeSM2Key: function (event) {
                let order = event.target.value; // 获取option对应的value值
                if (!order) {
                    return;
                }
                // console.log("changeSM2Key, -->" + order);
                headerVue.shortName = this.sm2KeyList[order].title;
                this.selectedSM2Key = order;
                this.sm2KeyStr = this.sm2KeyList[order].sm2Key;
                global.sm2Key = JSON.parse(this.sm2KeyStr);
                localStorage.setItem("PrivKey", this.sm2KeyStr);
                getSession();
                location.reload();
            }, deletePubkey: function (event) {
                let order = this.selectedSM2Key;
                // var obj = this.sm2KeyList[order];
                if (this.sm2KeyList.length === 1) {
                    alert("最后一对密钥不可以删除");
                    return;
                }
                let newList = [];
                for (let i = 0; i < order; i++) {
                    newList.push(this.sm2KeyList[i]);
                }

                for (let i = order / 1 + 1; i < this.sm2KeyList.length; i++) {
                    newList.push(this.sm2KeyList[i]);
                }

                this.sm2KeyList = newList;
                for (let i = 0; i < newList.length; i++) {
                    newList[i].id = i;
                }
                if (order >= newList.length) {
                    order--;
                }
                // console.log("after delete, size:" + newList.length + " order:" + order);
                localStorage.setItem("PrivKeyList", JSON.stringify(newList));
                headerVue.shortName = this.sm2KeyList[order].title;
                this.selectedSM2Key = order + "";
                this.sm2KeyStr = this.sm2KeyList[order].sm2Key;
                global.sm2Key = JSON.parse(this.sm2KeyStr);
                localStorage.setItem("PrivKey", this.sm2KeyStr);
                getSession();
            }, exportPubkey: function (event) {
                let uri = "data:text/html,";
                uri += localStorage.getItem("PrivKeyList");
                let link = document.createElement("a");
                link.download = "sm2keyList.json";
                link.href = uri;
                document.body.appendChild(link);
                link.click();
                document.body.removeChild(link);
                // delete link;
            }

        }
    });

    mainVue = new Vue({
        el: "#main",
        data: {
            licenceDueDate: "已过期",
            licenceNodes: 0,
            offlineLicence: undefined,
            licenceRemark: undefined,
            userCount: ".",
            contractCount: ".",
            nodeCount: ".",
            eventCount: ".",
            unitCount: ".",
            pubDialogVue: {},
            projects: [],
            contracts: [],
            contractFunctions: [],
            openedFiles: [{
                isDir: false,
                val: "Please Checkout code from left side!",
                path: "Hello",
                name: "Hello"
            }]

        }
    });
    toastVue = new Vue({
        el: "#alertDiv",
        data: {
            toastTitle: "提示",
            toastMessage: "消息"
        }
    })
}

// ======Vue done

function initGlobal() {
    window.global = {};
    global.sm2Key = localStorage.getItem("PrivKey");
    global.result = "";
    if (!global.sm2Key || global.sm2Key.length < 100) {
        generate();
    } else {
        global.sm2Key = JSON.parse(global.sm2Key);
    }
    headerVue.shortName = global.sm2Key.publicKey.substr(0, 5);
    pubkeyDialogVue.sm2KeyStr = JSON.stringify(global.sm2Key);
    mainVue.pubDialogVue = pubkeyDialogVue;
    let keyListStr = localStorage.getItem("PrivKeyList");
    let keyObj = {};
    if (!keyListStr) {
        keyObj.id = 0;
        keyObj.title = headerVue.shortName;
        keyObj.sm2Key = pubkeyDialogVue.sm2KeyStr;
        pubkeyDialogVue.sm2KeyList = [];
        pubkeyDialogVue.sm2KeyList.push(keyObj);
        pubkeyDialogVue.selectedSM2Key = 0;
        // mainVue.sm2KeyList = pubkeyDialogVue.sm2KeyList;
        // mainVue.selectedSM2Key = 0;
    } else {
        pubkeyDialogVue.sm2KeyList = JSON.parse(keyListStr);
        pubkeyDialogVue.selectedSM2Key = -1;
        for (let i = 0; i < pubkeyDialogVue.sm2KeyList.length; i++) {
            let obj = pubkeyDialogVue.sm2KeyList[i];
            if (obj.sm2Key === pubkeyDialogVue.sm2KeyStr) {
                pubkeyDialogVue.selectedSM2Key = i;
                // mainVue.sm2KeyList = pubkeyDialogVue.sm2KeyList;
                // mainVue.selectedSM2Key = pubkeyDialogVue.selectedSM2Key;
                return;
            }
        }
        keyObj.id = pubkeyDialogVue.sm2KeyList.length;
        keyObj.title = headerVue.shortName;
        keyObj.sm2Key = pubkeyDialogVue.sm2KeyStr;
        pubkeyDialogVue.sm2KeyList.push(keyObj);
        pubkeyDialogVue.selectedSM2Key = keyObj.id;
        // mainVue.sm2KeyList = pubkeyDialogVue.sm2KeyList;
        // mainVue.selectedSM2Key = pubkeyDialogVue.selectedSM2Key;

    }
}
