var UI = chrome.extension.getURL("ui.html");
var icon = chrome.extension.getURL("icon.png");
let extendDom = document.createElement("div");
let app = null;
extendDom.id = "__extend_dom"
extendDom.innerHTML = "<div class='cicon'><div><img src='"+icon+"' v-on:click='showUi'/></div></div>";
extendDom.style="z-index:999;";
const TYPE_WORK  = 1;
const TYPE_READING = 2;
const TYPE_USER = 3;
let ACCESS_TOKEN = "";

chrome.extension.sendRequest({}, function(response) {
    ACCESS_TOKEN = response.access_token;
});

var body = document.getElementById("__nuxt");
fetch(UI).then(function(res){
    return res.text();
}).then(html => {
    let container = document.createElement("div");
    container.id = "container";
    container.innerHTML = html;
    extendDom.appendChild(container)
    body.appendChild(extendDom);
}).then(() => {
    app = new Vue({
        el: '#__extend_dom',
        data: {
            loadingimg: chrome.extension.getURL("loading.png"),
            closeX: chrome.extension.getURL("close.png"),
            fade: false,
            canOpen: false,
            showUiProp: false,
            token: "",
            permission: "-1",
            remark: "",
            user: {
                id: "",
                mobile: "",
                wx: "",
                qq: "",
                email: "",
                nickname:""
            },
            isAuth: false,
            objectId: null,
            type: null,
            isUserInfo: false,
            isWorks: false,
            isYoumi: 0,
            isReading: false,
            access_token: "",
            inZone: false,
            userId: "",
            userRemark: ""    ,
            userPermission: "-1",
            userToken: "",
            err: "",
            loading: false,
            API: {
                addZone:    "https://api.mepai.me/manage/youmi/add-zone",
                getZone:    "https://api.mepai.me/manage/youmi/get-zone",
                removeZone:  "https://api.mepai.me/manage/youmi/remove-zone",
                setRemark:  "https://api.mepai.me/manage/youmi/set-remark",
                getRemark:  "https://api.mepai.me/manage/youmi/get-remark",
                getUserInfo: "https://api.mepai.me/manage/youmi/user",
                getIsYoumi: "https://api.mepai.me/manage/youmi/is-youmi",
                auth: "https://api.mepai.me/manage/youmi/is-auth"
            }
        },
        methods: {
            showUi: function() {
                this.showUiProp = !this.showUiProp;
                if (this.showUiProp) {
                    this.openUi();
                }
            },
            openUi: function() {
                let $this = this;
                let canOpen = this.assertIn();
                this.canOpen = canOpen;
                if (canOpen) {

                    if ($this.type !== null && $this.type !== undefined) {
                        $this.getData($this.API.getRemark, {
                            object_id: $this.objectId,
                            type: $this.type
                        }, res => {
                            if (res.code.toString() === "100001") {
                            if (res.data.toString() !== "") {
                                $this.remark = res.data.remark;
                                $this.permission = res.data.permission;
                                $this.token = res.data.lock_token
                            }
                        }
                    });
                    }
                    //获取基本信息并显示在编辑框
                    if ($this.isUserInfo) {
                        this.getData($this.API.getUserInfo, {
                            uid: $this.userId
                        }, data => {
                            let res = data.data;
                            $this.user.id = res.id;
                            $this.user.qq = res.qq;
                            $this.user.wx = res.wx;
                            $this.user.mobile = res.mobile;
                            $this.user.email = res.email;
                            $this.user.nickname = res.nickname
                        });
                        this.getData($this.API.getRemark, {
                            object_id: $this.userId,
                            type: TYPE_USER
                        }, res => {
                            if (res.code.toString() === "100001") {
                                if (res.data.toString() !== "{}") {
                                    $this.userRemark = res.data.remark;
                                    $this.userPermission = res.data.permission.toString();
                                    $this.userToken = res.data.lock_token
                                }
                            }
                        })
                    }
                    if ($this.isWorks ) {
                         $this.getData($this.API.getIsYoumi, {
                             object_id: $this.objectId,
                             type : $this.type
                        }, data => {
                            $this.isYoumi = data.data;
                        });
                    }
                    if ($this.isReading) {
                        $this.getData($this.API.getIsYoumi, {
                            object_id: $this.objectId,
                            type : $this.type
                        }, data => {
                            $this.isYoumi = data.data;
                        });
                    }
                    if ($this.isReading || $this.isWorks) {
                        $this.getData(this.API.getZone, {
                            object_id: $this.objectId,
                            type: $this.type
                        }, res => {
                            let data = res.data
                            if (data.length === 0) {
                                $this.inZone = false;
                            } else {
                                $this.inZone = true;
                            }
                        })
                    }
                } else {
                    $this.err = "不在个人中心或作品详情或文章详情页";
                }
            },
            assertIn: function() {
                let url = window.location.href;
                let avatar = $(".container").find(".user-portrait").children("img");
                let canOpen = false;
                let $this = this;
                if (url.indexOf("article") > -1 && url.indexOf("list") === -1) {
                    $this.isReading = true;
                    $this.isUserInfo = true;
                    $this.getReadingIdByBase64(url);
                }
                if (url.indexOf("works") > -1 && url.indexOf("list") === -1) {
                    $this.isWorks = true;
                    $this.isUserInfo = true;
                    $this.getWorksIdByBase64(url);
                }
                if (url.indexOf("photographyer") > -1) {
                    $this.isUserInfo = true;
                    $this.getUserIdFromAvatar($(avatar).attr("src"));
                }
                if (!this.isUserInfo && avatar !== undefined && $("title").text().indexOf("米拍摄影社区") > -1) {
                    $this.isUserInfo = true;
                    canOpen = true;
                } else {
                    canOpen = true;
                }
                $this.getAuth();
                if ($this.isUserInfo) {
                    $this.getUserIdFromAvatar($(avatar).attr("src"));
                }
                return canOpen;
            },
            getAuth: function() {
                let $this = this;
                this.getData(this.API.auth, {}, (res) => {
                    if (res.code.toString() === "100001") {
                        $this.isAuth = true;
                    }
                    if (res.code.toString() === "100002") {
                        $this.isAuth = false;
                    }
                });
            },
            getData: function(api, data, callback) {
                let $this = this;
                api = api + "?";
                for (var i in data) {
                    api = api + "&" + i + "=" + data[i]
                }
                var header = {
                    method: "GET",
                    headers: {
                        accesstoken: ACCESS_TOKEN
                    },
                };
                fetch(api, header).then(res => {
                    return res.json()
                }).then(final => {
                    if (final.code.toString() === "100002") {
                        $this.err = "请先登录，若登录账号没有操作权限，请向公司管理员申请";
                    } else if (final.code.toString() === "100001") {
                        $this.err = "";
                    }
                    return callback(final);
                }).catch(e => {
                    console.log(e);
                });
            },
            sendData: function(api, data, callback) {
                let $this = app;
                $this.loading = true;
                var header = {
                    method: "POST",
                    headers: {
                        accesstoken: ACCESS_TOKEN,
                        "Content-Type": "application/json; charset=UTF-8"
                    },
                    body: JSON.stringify(data)
                };
                fetch(api, header).then(res => {
                    $this.loading = false;
                    return res.json()
                }).then(final => {
                    return callback(final);
                })
            },
            onload() {
                this.openUi();
            },
            getWorksIdByBase64(url) {
                let pre1 = /\works\/\S*\?/g;
                let pre2 = /\works\/\S*\?*/g;
                if (url.indexOf("?") > -1) {
                    worksString = url.match(pre1);
                } else {
                    worksString = url.match(pre2);
                }
                let worksId = null;
                if (worksString !== undefined && worksString!==null&& worksString.length > 0) {
                    worksId = worksString[0].replace("works/", "");
                    worksId = worksId.replace("?", "");
                    worksId = this.base64Decode(worksId);
                }
                this.objectId = worksId;
                this.type = TYPE_WORK;
            },
            getReadingIdByBase64(url) {
                let pre1 = /\article\/\S*\?/;
                let pre2 = /\article\/\S*/;
                let str = [];
                if (url.indexOf("?") > -1) {
                     str = url.match(pre1);
                } else {
                     str = url.match(pre2);
                }
                let id = null;
                if ( str !== null && str.length > 0) {
                    id = str[0].replace("article/", "");
                    id = id.replace("?", "");
                    id = this.base64Decode(id);
                }
                this.objectId = id;
                this.type = TYPE_READING;
            },
            getUserIdFromAvatar(avatar) {
                var reg = /\/\d{1,}\//g;
                var idStrings = avatar.match(reg);
                if (idStrings !== undefined &&  idStrings !== null && idStrings !== "") {
                    userId = idStrings[0].replace(/\//g, "");
                }
                this.userId = userId;
            },
            submitRemark() {
                let data = {
                    "remark": this.remark,
                    "object_id": this.objectId,
                    "type" : this.type,
                    "token": this.token,
                    "permission": this.permission.toString()
                }
                let $this = this;
                this.sendData(this.API.setRemark, data, res => {
                    if (res.code === "100001") {
                        $this.remark = res.data.remark;
                        $this.permission = res.data.permission.toString();
                        $this.token = res.data.lock_token;
                        $this.showToast("操作成功");
                    } else {
                        if (res.code.toString() === "100002") {
                            $this.err = "请先登录，若登录账号没有操作权限，请向公司管理员申请";
                        } else {
                            $this.showToast(res.message);
                        }
                    }
                });
            },
            submitUserRemark() {
                let data = {
                    "remark": this.userRemark,
                    "object_id": this.userId,
                    "type" : TYPE_USER,
                    "token": this.userToken,
                    "permission": this.userPermission.toString()
                }
                let $this = this;
                this.sendData(this.API.setRemark, data, res => {
                    if (res.code === "100001") {
                        $this.userRemark = res.data.remark;
                        $this.userPermission = res.data.permission.toString();
                        $this.userToken = res.data.lock_token;
                        $this.showToast("操作成功");
                    } else {
                        if (res.code.toString() === "100002") {
                            $this.err = "请先登录，若登录账号没有操作权限，请向公司管理员申请";
                        } else {
                            $this.showToast(res.message);
                        }
                    }
                });
            },
            removeZone() {
                let $this = this;
                this.sendData(this.API.removeZone, {
                    object_id: this.objectId,
                    type: this.type
                }, res => {
                   if (res.code.toString() === "100001") {
                       $this.inZone = false;
                     $this.showToast("操作成功");
                   } else {
                        if (res.code.toString() === "100002") {
                            $this.err = "请先登录，若登录账号没有操作权限，请向公司管理员申请";
                        } else {
                            $this.showToast(res.message);
                        }
                    }

                });
            },
            addZone() {
                let $this = this;

                this.sendData(this.API.addZone, {
                    object_id: this.objectId,
                    type: this.type
                }, res => {
                    if (res.code.toString() === "100001") {
                        $this.inZone = true;
                        $this.showToast("操作成功");
                    } else {
                        if (res.code.toString() === "100002") {
                            $this.err = "请先登录，若登录账号没有操作权限，请向公司管理员申请";
                        } else {
                            $this.showToast(res.message);
                        }
                    }
                });
            },
            showToast(msg) {
                let $this = this;
                $this.err = msg;
                setTimeout(function () {
                    $this.err = "";
                }, 3000);
            },
            base64Decode(data) {
                if (!isNaN(data)) {
                    return data;
                }
                var rv = window.atob(data);
                rv = escape(rv);
                rv = decodeURIComponent(rv);
                return rv;
            }
        }
    });
    app.onload();
});


let urlCircle = [];
setInterval(function () {
    let currentUrl = window.location.href;
    if (urlCircle.length > 0 && urlCircle.shift() !== currentUrl) {
        window.location.reload();
    }
    urlCircle.push(currentUrl)
}, 1000);