
import { factoryContentUrls,bookingV2Urls,homeUrl,tmIssueUrl,tbIssueUrl } from "../config";
import { StartPrint, Print, ACTION } from "../types";
const tmNameSiffix = ['旗舰店', '专卖店', '专营店']
//     platform: PlatformCode,// 平台编码，淘系及其他平台订单模板的为0，拼多多订单的为1，京东订单的为2
const PlatfromsMap = new Map([
    [0, /.+:\/\/a.*\.fahuoyi.com\/scanPrinting\/index/],
    [1, /.+:\/\/pdd.*\.fahuoyi.com\/scanPrinting\/index/],
    [2, /.+:\/\/jd.*\.fahuoyi.com\/scanPrinting\/index/]
])
let monitoringRemoveTabId = new Map();
let result_sendResponse:boolean = false
chrome.runtime.onMessage.addListener(async function (message, sender, sendResponse) {
if (message.action === ACTION.task) {
        // 从bg页面转发给厂家页面的content.js
        chrome.tabs.query({
            url: bookingV2Urls
        }, function (tabs) {
            tabs && tabs.forEach(tab => {
                // chrome.tabs.sendMessage(tab.id!, message)
                chrome.tabs.update(tab.id!, { active: true}, function(tab1) {});
                chrome.tabs.sendMessage(tab.id!, { action: ACTION.task, value: message.value },res=>{
                    console.log(3333,res,tab,new Date());
                    if(res){
                        sendResponse(res);
                        chrome.tabs.update(sender.tab!.id!, { active: true}, function(tab1) {});
                    }
                })
            })
            if(tabs.length==0){
                alert('请打开千牛商家工作台')
                sendResponse({status:1,msg:"请打开千牛商家工作台"});
            }
            chrome.storage.sync.get("tb_user",function(res){
              let userData = res.tb_user
              if (userData == null) {
                alert('请登录千牛商家工作台')
                sendResponse({status:1,msg:"请登录千牛商家工作台"});
               }
            })
            
        })
        // let port = chrome.runtime.connect({ name: "bgSendMessage" })
        // port.postMessage(message)
    }else if(message.action==='getUserLoginData'){
        await getUserLoginData()
        sendResponse()
    }

    return true;
})
chrome.tabs.onUpdated.addListener(async (tabId, changeInfo, tab) => {
    //加载完毕后在执行一些动作
    if (tab.status== "complete") {
        //如果进入了千牛首页 则开始获取对应的数据信息
        if(tab.url&&tab.url.indexOf("loginmyseller.taobao.com") != -1){
            if(monitoringRemoveTabId.has(tab.id)){
                let id:any = tab.id
                chrome.tabs.remove(id);
            }
            chrome.storage.sync.remove("tb_user")
            result_sendResponse=true;
            return
        }
        if (tab.url&&tab.url.indexOf("myseller.taobao.com/home.htm/QnworkbenchHome") != -1) {
            let userNickCookie:any = await getCookies(tab.url, "sn");
            if (userNickCookie === null || userNickCookie === undefined || userNickCookie === "") userNickCookie = await getCookies(tab.url, "_nk_");
            console.log('userNickCookie',userNickCookie);
            if (userNickCookie === null || userNickCookie === undefined) {
                chrome.storage.sync.remove("tb_user")
                result_sendResponse=true;

                return
            };
            let tuDe1 = decodeURI(userNickCookie.value);
            let tuDe2 = unescape(tuDe1.replace(/\\(u[0-9a-fA-F]{4})/gm, '%$1'));
            if (tuDe2.indexOf(":") != -1) tuDe2 = tuDe2.split(":")[0];
            let createUrl = isTm(tuDe2) ? tmIssueUrl : tbIssueUrl;
            let tabId = await createTab(createUrl);
            monitoringRemoveTabId.set(tabId, tuDe2);
        }

        if (tab.url&&(tab.url.indexOf("item.upload.taobao.com/sell/merge") != -1 || tab.url.indexOf("sell.publish.tmall.com/tmall/smart") != -1)) {
            if (monitoringRemoveTabId.has(tab.id)) {
                let userNick:string = monitoringRemoveTabId.get(tab.id);
                let cookie = await getCookieAll(tab.url);
                let token:any = await getCookies(tab.url, "XSRF-TOKEN");
                let userData:object = {
                    cookie:cookie,
                    token: token.value,
                    userNick: userNick,
                }
                console.log("user data :", userData,new Date().getMinutes(),new Date().getSeconds());
                // let serverNum = SoketDispatchManage.hosts[config.evn].length;
                // if (SoketDispatchManage.userNick == null || SoketDispatchManage.userNick != userData.userNick || SoketDispatchManage.getActiveConnectNum() != serverNum) {
                //     //与服务器建立webSocket连接  后续与服务器通信将依赖此链接
                //     SoketDispatchManage.connection(userData.userNick);
                //     if (SoketDispatchManage.getActiveConnectNum() <= 0) {
                //         console.log("socket未连接至任何服务器!")
                //     }
                // }
                let id:any = tab.id
                chrome.storage.sync.set({"tb_user":JSON.stringify(userData)})
                result_sendResponse=true;

            }else{
            // console.log(222,new Date().getMinutes(),new Date().getSeconds());
                chrome.storage.sync.remove("tb_user")
                result_sendResponse=true;

            }
        }
        if(monitoringRemoveTabId.has(tab.id)){
           let id:any = tab.id
           chrome.tabs.remove(id);
        }
    }
    
})

async function getUserLoginData(){
    result_sendResponse = false
    let tabId = await createTab(homeUrl);
    monitoringRemoveTabId.set(tabId, "");
    await newTab()
    return new Promise<void>((resolve, reject) => {
        resolve()
    })
}
function newTab(){
    return new Promise<void>((resolve, reject) => {
        if(result_sendResponse){
            resolve()
        }else{
            setTimeout(() => {
                newTab() 
            },500);
        }
    })
}

async function createTab(url:string) {
    return new Promise((resolve, reject) => {
        chrome.tabs.create({ url: url, active: false }, async (tab) => {
            resolve(tab.id);
        })
    })
}

function getCookies(url:string, name:string){
    return new Promise((resolve, reject) => {
        if (name == "") {
            chrome.cookies.getAll({url}, (cookie) => {
                resolve(cookie);
            })
        } else {
            chrome.cookies.get({
                url: url,
                name: name
            }, (cookies) => {
                resolve(cookies);
            })
        }

    })
}

function getCookieAll(url:string) {
    return new Promise((resolve, reject) => {
        chrome.cookies.getAll({
            'url': url
        }, (callback) => {
            if (callback.length <= 0) resolve("");
            let cookies = "";
            for (let i = 0; i < callback.length; i++) {
                cookies += callback[i].name + '=';
                cookies += callback[i].value;
                if (i != callback.length - 1) cookies += "; ";
            }
            resolve(cookies);
        })
    })

}

function isTm(userNick:string) {
    for (const suffix of tmNameSiffix) {
        if (userNick.indexOf(suffix) !== -1) return true;
    }
    return false;
}
