import { Tabs } from 'antd'
import {
  factoryContentUrls,
  bookingV2Urls,
  homeUrl,
  tmIssueUrl,
  tbIssueUrl,
  tbIssueUrls,
} from '../config'
import { ACTION } from '../types'
const tmNameSiffix = ['旗舰店', '专卖店', '专营店']
let monitoringRemoveTabId = new Map()
let result_sendResponse: boolean = false
let tb_user: any = {}
let taIssueId: any = null
chrome.runtime.onMessage.addListener(function (message, sender, sendResponse) {
  // console.log('message1',message,sender);
  if (message.action === ACTION.task) {
    getUserLoginData()
    let awaitResultFun = () => {
        console.log('awaitResultFun',result_sendResponse);
      if (result_sendResponse) {
        if (JSON.stringify(tb_user) === '{}') {
          chrome.storage.sync.set({ info: '当前千牛登录账号信息获取失败' })
          sendResponse({
            status: -200,
            task_id: message.value.task_id,
            msg: '当前千牛登录账号信息获取失败,请登录千牛账号后重试!',
          })
          return true
        } else {
          chrome.storage.sync.remove('info')
          if (message.value.seller.nick !== tb_user.userNick) {
            chrome.storage.sync.set({
              info: '当前登录的千牛账号与图动力授权的账号信息不一致,请统一登录后重试!',})
            sendResponse({
              status: -200,
              task_id: message.value.task_id,
              msg: '当前登录的千牛账号与图动力授权的账号信息不一致,请统一登录后重试!',
            })
            return true
          }
        }
        chrome.tabs.query(
          {
            url: tbIssueUrls,
          },
          function (tabs) {
            console.log('如果图动力登录的账号和千牛云登录的账号不一致，则popup页面爆红tabs',tabs);
            
            // 如果图动力登录的账号和千牛云登录的账号不一致，则popup页面爆红
            tabs &&tabs.forEach((tab) => {
                // chrome.tabs.update(tab.id!,{ active: true },function (tab1) {})
                chrome.tabs.sendMessage(tab.id!,{ action: ACTION.task, value: message.value },(res) => {
                    console.log('res', res, new Date().getTime())
                    if (res) {
                      sendResponse(res)
                    //   chrome.tabs.update(sender.tab!.id!,{ active: true },function (tab1) {})
                    }
                  }
                )
              })
            if (tabs.length == 0) {
              sendResponse({
                status: -200,
                task_id: message.value.task_id,
                msg: '请打开千牛商家工作台',
              })
              alert('请打开千牛商家工作台')
            }
          }
        )
      } else {
        setTimeout(() => {
          awaitResultFun()
        }, 500)
      }
    }
    awaitResultFun()
  } else if (message.action === 'getUserLoginData') {
    getUserLoginData()
    let awaitResultFun = () => {
      if (result_sendResponse) {
        sendResponse()
      } else {
        setTimeout(() => {
          awaitResultFun()
        }, 500)
      }
    }
    awaitResultFun()
  }
  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
      }
    //   chrome.tabs.query(
    //     {
    //       url: [tbIssueUrl],
    //     },
    //     async function (tabs) {
    //       console.log('query tabs', tabs,tab)
    //       let complete_tabs: any = []
    //       if (tabs.length) {
    //         complete_tabs = tabs.filter((item) => item.status === 'complete')
    //       }
    //       console.log('complete_tabs', complete_tabs)
    //       if (!complete_tabs.length) {
    //         taIssueId = await createTab(tbIssueUrl)
    //       }
    //     }
    //   )
      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)
      taIssueId = tabId
      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)
        console.log('monitoringRemoveTabId', monitoringRemoveTabId)
        let cookie = await getCookieAll(tab.url)
        // console.log('cookie22',tab.url,cookie);
        let token: any = await getCookies(tab.url, 'XSRF-TOKEN')
        let userData: object = {
          cookie: cookie,
          token: token.value,
          userNick: userNick,
        }
        tb_user = userData
        chrome.storage.sync.set({ tb_user: JSON.stringify(userData) })
        console.log(
          'user data :',userData,new Date().getMinutes(),new Date().getSeconds())
        let id: any = tab.id
        result_sendResponse = true
      }
    }
    if (monitoringRemoveTabId.has(tab.id)&&tab.url&&tab.url!==tbIssueUrl) {
      let id: any = tab.id
      chrome.tabs.remove(id)
    }
  }
})

async function getUserLoginData() {
  result_sendResponse = false
  monitoringRemoveTabId.clear()
  // console.log('taIssueId',taIssueId);
  taIssueId && chrome.tabs.remove(taIssueId)
  let tabId = await createTab(homeUrl)
  monitoringRemoveTabId.set(tabId, '')
}
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
}
function getLocalStronges(url: string, name: string) {
  return new Promise((resolve, reject) => {
    chrome.storage.local.get(
      {
        url: url,
        name: name,
      },
      (cookies) => {
        resolve(cookies)
      }
    )
  })
}
