import { message, Spin } from "antd"
import React, { useCallback,useState } from "react"
import { api } from '@/services/api'
function ToMp(props: { name: string, type: any, planId: any ,id:any}) {
    let { name, type, planId,id } = props
    const [isReq,setIsReq] = useState<boolean>(false)
    const go = useCallback(() => {
        if(!isReq){
            setIsReq(true)
            fetch(`${api}/erp/config/sysVersion/plugin`,{
                headers:{
                    'Authorization':'Bearer ' + sessionStorage.getItem('Admin-Token') 
                }
            }).then(r=>r.json()).then(rs=>{
                let p_v = rs?.data?.configValue
                if(p_v ===  sessionStorage.getItem('qc_chrome')){
                    fetch(`https://api.zanxiangnet.com/ads/adsChannelAccount/getAccountCookie/${id}`, {
                        method: "GET",
                        headers: { "Content-Type": "application/json" , 'Authorization':'Bearer ' + sessionStorage.getItem('Admin-Token') }, //如果写成contentType会报错
                    }).then((res: any) => res.json()).then(js => {
                        setIsReq(false)
                        if (js?.data?.cookies) {
                            let { cookies, url } = js?.data
                            url = type === 1 ? url : url.replace(/type=1/, `type=${type}`)
                            console.log({ type: 'open', cookies, url, id: planId })
                            window.postMessage({ type: 'open', cookies, url, id: planId })
                        }else{
                            message.error(js?.msg)
                        }
                    })
                }else{
                    setIsReq(false)
                    message.error('插件版本太低，请重新下载安装插件')
                }
            })
         
        }
    }, [isReq])
    return <>
        {
            sessionStorage.getItem('qc_chrome') ? <Spin spinning={isReq}><a onClick={go}>{name}</a> </Spin>: name
        }
    </>
}
export default ToMp