import React, { useState, useCallback, useEffect } from "react";
import { Button } from "antd";
import "./index.scss";
import {bookingV2Urls,factoryContentUrls } from "../../../config";
interface User {
    userNick: string,
    cookie:string,
    token:string
  }
let initTime = 0
const WayBillModel = function () {
    // 当前是否连接成功
    const [link,setLink] = useState<boolean>(false)
    // 当前的登录状态
    const [is_login,setIsLogin] = useState<boolean>(false)
    // 用户信息
    const [user,setUser] = useState<User>({
      userNick: '',
      cookie:'',
      token:''
    })
    // 提示信息
    const [info,setInfo] =  useState<string>('')
    // 刷新时候的状态
    const [loading,setLoading] = useState<boolean>(false)
    // 获取发货易快递模板列表
    const getLogin = useCallback(async () => {
        chrome.tabs.query({
            url: [...bookingV2Urls,...factoryContentUrls]
        }, async function (tabs) {
            console.log('tabs',tabs);
            if(!tabs||!tabs.length){
              setLink(false)
             console.log('未连接')
            }else{
              setLink(true)
                // let urls = tabs.map(item=>item.url)
                // if(urls.includes('https://myseller.taobao.com/*')&&urls.includes('*://*.rtxmdz.com/*')){
                //   setLink(true)
                // }
            }
        })
    }, [])
    const delayDate = (time: number)=>{
        return new Promise((resolve, reject) => {
          setTimeout(() => {
            //console.log(‘开始执行‘)
            resolve('status')
          }, time)
        })
      }

    useEffect(() => {
        getLogin()
        // 获取用户信息
        chrome.storage.sync.get("tb_user",function(res){
            console.log(res);
            let userData = res.tb_user
            if (userData == null) {
                setIsLogin(false)
                setLink(false)
                setUser({userNick: '',
                cookie:'',
                token:''})
             } else {
                 let userDataJson:any = JSON.parse(userData)
                setIsLogin(true)
                setUser(userDataJson)
                setLink(true)
             }
        })
        chrome.storage.sync.get("info",function(res){
            console.log("info",res);
            let info = res.info
            info&&setInfo(info)
        })
    }, [])

    // 刷新连接状态
    const refresh = useCallback(() => {
        if(initTime>0)return
        chrome.storage.sync.set({"info":''})
        chrome.storage.sync.get("info",function(res){
            console.log("info",res);
            let info = res.info
            setInfo(info)
        })
        setLoading(true)
        initTime++
        getLogin()
        chrome.runtime.sendMessage({ action: 'getUserLoginData' },async()=>{
           let userData:any = await getStorageItem("tb_user")
           console.log('userData',userData,new Date().getMinutes(),new Date().getSeconds());
           if (userData == null) {
              setIsLogin(false)
              setLink(false)
              setUser({userNick: '',
              cookie:'',
              token:''})
           } else {
               let userDataJson:any = JSON.parse(userData)
              setIsLogin(true)
              setUser(userDataJson)
              setLink(true)
           }
           initTime = 0
           setLoading(false)
        })
        // alert("刷新完毕");
    }, [])
    
    return (
        <>
            <div className="waybill-model">
                <div className="waybill-model-title" key="one">千牛登录账号：{is_login?user.userNick:'未登录'}</div>
                <div className="waybill-model-title" key="two">通信状态：{link?'连接成功':'连接中断'}</div>
                <div className="waybill-model-title tips">{info}</div>
            </div>
            <Button className="btn" type="primary" loading={loading} disabled={loading} onClick={ refresh }>刷新连接状态</Button>
        </>
    )
}
function getStorageItem(key:string) {
    return new Promise((resolve, reject) => {
        chrome.storage.sync.get([key], (item) => {
            resolve(item[key]);
        })
    })

}
export default WayBillModel