
'use strict';
import React from 'react';
import { observer } from 'mobx-react';
import { md5 } from '@spark/utils';
import { CHANNEL_PARAMS } from '@src/utils/constants';
import API from '@src/api';
import './middlePageNew.less';
import { _throttle, getUrlParam, isWechatMini, windowJumpUrl } from '@src/utils/utils';
import WxOpenModule from '@src/components/wxOpenModule/wxOpenModule';
import { miniGoUrl, onInitShare } from '@src/utils/share';
import { ensureDomain, domain } from '@spark/dbdomain';
@observer
class MiddlePage extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      isWeixinMini: false,
      dataInfo:{},
      callBackUrl:'',
    };
  }

  async componentDidMount() {
    await onInitShare();
    await ensureDomain();
    CFG.domain = domain || window.location.origin;
    CFG.index = CFG.domain + CFG.index;
    this.juageWeixin();

    const requestParam = getUrlParam("requestParam");

    const param = getUrlParam("param"); // 长航加油站 加密串参数

    const channel = getUrlParam("channel");

    const timestamp = new Date().getTime();

    const sign = md5(requestParam + timestamp + "24fnTNEK8KqURnlZhIJ58mdylVe1rs0BZha");

    const isFromShare = getUrlParam("isFromShare");

    const empno = getUrlParam("empno");

    const empname = getUrlParam("empname");

    const wdTK = getUrlParam("wdTK");

    const empnoShow = getUrlParam("empnoShow");
    let actUrl = getUrlParam("actUrl") && getUrlParam("actUrl") != 'null' ? decodeURIComponent(getUrlParam("actUrl")) : CFG.index;
    //接口重定向地址
    let directUrl = `${actUrl}&channel=${channel}&empno=${empno}&empname=${empname}&wdTK=${wdTK}&isFromShare=${isFromShare}&empnoShow=${empnoShow}`

    // 用不到了
    // const middleUrl = CFG.projectId == 'pa77ad6bf' ? CFG.middleTestPage : CFG.middleProdPage;
    // const callBackUrl = `${middleUrl}&redirectUrl=${actUrl}&channel=${channel}&empno=${empno}&empname=${empname}&wdTK=${wdTK}&isFromShare=${isFromShare}&empnoShow=${empnoShow}`
    // this.setState({callBackUrl})
    
    // console.info("这是直接跳转的链接", directUrl);
    if (channel == CHANNEL_PARAMS.THD_MINI) {
      //太好店渠道 
      const thirdParam = JSON.parse(decodeURIComponent(getUrlParam("thdParam")));
      let newEmpno = thirdParam.empno;
      let newEmpname = thirdParam.empname;
      let openId = thirdParam.openid
      let newEmpnoShow = thirdParam.empnoShow
      let custPhone = thirdParam.custPhone
      let token = getUrlParam("token")
      let newWdTK = decodeURIComponent(getUrlParam("wdTK"))
      // console.error("kankancanshu", thirdParam, custPhone)
      //  console.info('---sign',getUrlParam("thdParam") + timestamp + "24fnTNEK8KqURnlZhIJ58mdylVe1rs0BZha")
      const {success, data} = await API.thdLoginNew({
        requestParam:encodeURIComponent(getUrlParam("thdParam")),
        redirect: encodeURIComponent(directUrl),
        channel:channel,
        sign:md5(getUrlParam("thdParam") + timestamp + "24fnTNEK8KqURnlZhIJ58mdylVe1rs0BZha"),
        timestamp:timestamp,
        empno:newEmpno,
        empname:newEmpname,
        openid:openId,
        wdTK:newWdTK,
        empnoShow:newEmpnoShow,
        custPhone:custPhone,
        token:token,
        authToken:'P_PT_PHONE_THD25GuardingLife',
        environment:CFG.environment,
      })
      if(success){
        this.setState({dataInfo:data},()=>{
          this.handleToGo2()
        })
        
        
      }
    }else{
      const { success, data } = await API.tbLoginNew({
        token: getUrlParam("token"),
        src: "d8",
        redirectUrl: encodeURIComponent(encodeURIComponent(directUrl)),
      });
      if (success) {
        console.info('----data', data);
        this.setState({dataInfo:data},()=>{
          // this.handleToGo2()
        })
      } else {

      }
    }
    
    
  }
  
  //授权三合一（登录、授权、兴趣收集合并） 6.22迭代
  handleAuthOrize = (token) => {
    if(getUrlParam('channel') == CHANNEL_PARAMS.THD_MINI){
      const link  = `${CFG.originUrl}/cpicactivity/#/mini-auth-loading?isCollect=1&token=${token}&gwAuthToken=P_PT_PHONE_THD25GuardingLife&channel=${CFG.channel}`
      // alert(link)
      windowJumpUrl(link)
    }else{
      const link2 = `/packageAgent/pages/loading/loading?gwAuthToken=P_PT_PHONE_25GuardingLife&channel=${CFG.channel}`
      console.info("官微小程序2", link2);
      // alert(link)
      wx?.miniProgram?.navigateTo({ url: link2 });
    }
  };

  handleToGo2 = () =>{
    const {dataInfo} = this.state;
    if(getUrlParam('channel') == CHANNEL_PARAMS.THD_MINI){
      const { boolLogin,  authBaseFlag, interestCollectionFlag, authUrl, autoLoginUrl, token} = dataInfo;
      if(!boolLogin || !authBaseFlag || !interestCollectionFlag){
        this.handleAuthOrize(token)
      }else{
        // location.href = autoLoginUrl; //免登录链接
        location.replace(autoLoginUrl)
      }
      
    }else{
      const { loginFlag, authBaseFlag, interestCollectionFlag, autoLoginUrl, } = dataInfo;
      if (!loginFlag || !authBaseFlag || !interestCollectionFlag) {
        this.handleAuthOrize()
      }else{
        // location.href = autoLoginUrl;
        location.replace(autoLoginUrl)
      }
      
    }
  }
  //授权头像昵称
  handleGetUserInfo = (backUrl, token) => {
    if(getUrlParam('channel') == CHANNEL_PARAMS.THD_MINI){
      // const link2 = `/kydraw/pages/gwndhd/index?url=${encodeURIComponent(backUrl)}`
      const link2  = '/kydraw/pages/gwndhd/index?url='+encodeURIComponent(backUrl)
      // alert('授权头像昵称')
      // alert(
      //   `${CFG.originUrl}/sxwxauthentication/wx-thirdAuth/silentForMini?rUrl=${encodeURIComponent(link2)}&src=sxwx2db&token=${token}`
      // )
      windowJumpUrl(
        `${CFG.originUrl}/sxwxauthentication/wx-thirdAuth/silentForMini?rUrl=${encodeURIComponent(link2)}&src=sxwx2db&token=${token}`
      )
    }else{
      console.info("授权头像昵称");
      const link2 = `/pages/webviewByToken/index?url=${backUrl}`
      miniGoUrl(`/packageMember/pages/avatarNameAuthorization/avatarNameAuthorization/index?isskip=0&backurl=${encodeURIComponent(link2)}`);
    }
  };
  // 跳转兴趣收集页面
  handleInterestCollection = (backUrl, token) => {
    if(getUrlParam('channel') == CHANNEL_PARAMS.THD_MINI){
      const link2 = `/kydraw/pages/gwndhd/index?url=${encodeURIComponent(backUrl)}`
     windowJumpUrl(
        `${CFG.originUrl}/cpicactivity/#/mini-auth-loading?pageCode=interestComponent&backurl=${encodeURIComponent(link2)}&token=${token}`
     )
    }else{
      console.info("跳转兴趣收集页面官微");
      const link2 = `/pages/webviewByToken/index?url=${encodeURIComponent(backUrl)}`
      // alert(`/pages/webviewByToken/index?url=${encodeURIComponent(`${CFG.originUrl}/cpicactivity/#/mini-auth-loading?pageCode=interestComponent&backurl=${encodeURIComponent(link2)}`)}`);
      miniGoUrl(`/pages/webviewByToken/index?url=${encodeURIComponent(`${CFG.originUrl}/cpicactivity/#/mini-auth-loading?pageCode=interestComponent&backurl=${encodeURIComponent(link2)}`)}`);
    }
  };

  // 判断是否为微信小程序环境
  juageWeixin = async () => {
    const env = await isWechatMini();
    console.error(env, "这个有问题？？");
    let isWeixinMini = false;
    if (env == "mini") isWeixinMini = true;
    this.setState({
      isWeixinMini,
    });
  };
  // 获取登录小程序路径
  getWeixinMiniPath = () => {
    let path = "";
    const { isWeixinMini } = this.state;
    console.info(
      "这是path",
      `/packageMember/pages/bindPhone/thirdBindPhone/thirdBindPhone?gwAuthToken=P_PT_PHONE_25GuardingLife`
    );
    if (isWeixinMini) {
      //官微小程序
      CFG.miniAppid = "wx68b00bbff4c69cc9"; //生产appid wx68b00bbff4c69cc9   测试appid:  wx0fe22fef352fafc1
      CFG.miniUserName = "gh_70448c19370c";
      path = `/packageMember/pages/bindPhone/thirdBindPhone/thirdBindPhone?gwAuthToken=P_PT_PHONE_25GuardingLife&channel=${CFG.channel}`;
    } else {
      //H5默认跳转官微小程序
      CFG.miniAppid = "wx68b00bbff4c69cc9";
      CFG.miniUserName = "gh_70448c19370c";
      path = `/packageMember/pages/bindPhone/thirdBindPhone/thirdBindPhone?gwAuthToken=P_PT_PHONE_25GuardingLife&channel=${CFG.channel}`;
    }

    window.myAlert  && window.myAlert(path);

    return path;
  };
  // 跳转逻辑处理 用不到了
  handleToGo = _throttle(() => {
    const {callBackUrl, dataInfo} = this.state;
    if(getUrlParam('channel') == CHANNEL_PARAMS.THD_MINI){
      const { boolLogin,  authBaseFlag, interestCollectionFlag, authUrl, autoLoginUrl, token} = dataInfo;
      if(boolLogin){ // 已登录
        if(!authBaseFlag){
          this.handleGetUserInfo(callBackUrl, token)
          return;
        }
        // if(!interestCollectionFlag){
        //   this.handleInterestCollection(callBackUrl, token)
        //   return
        // }
        location.href = autoLoginUrl; //免登录链接
        
      }else{
        location.href = authUrl; //授权地址
      }
    }else{
      const { loginFlag, authBaseFlag, interestCollectionFlag, autoLoginUrl, } = dataInfo;
      if (loginFlag) {
        if(!authBaseFlag){
          this.handleGetUserInfo(callBackUrl)
          return;
        }
        // if(!interestCollectionFlag){
        //   this.handleInterestCollection(callBackUrl)
        //   return
        // }
        location.href = autoLoginUrl;
      }else{
        const { isWeixinMini } = this.state;
        console.info("跳转-->", isWeixinMini, this.getWeixinMiniPath());
        if (!isWeixinMini) return; //H5走组件的能力，小程序内直接跳转
        wx?.miniProgram?.navigateTo({ url: this.getWeixinMiniPath() });
        // wx.miniProgram.navigateTo({ url: url });
      }
    }
    
  });
  render() {
    const { isWeixinMini } = this.state;
    const channel = getUrlParam("channel");
    return (
      <div className="middlePageNew">
        <div className={`${channel == CHANNEL_PARAMS.THD_MINI ? 'bg' : 'bg1'}`}>
          {/* <div className="btn"></div> */}
          <div className="btn" onClick={this.handleToGo2}>
            {/* {!isWeixinMini && (
              <WxOpenModule
                id={"downLoadbtn"}
                appid={CFG.miniAppid}
                username={CFG.miniUserName}
                envVersion={CFG.miniEnv}
                path={this.getWeixinMiniPath()}></WxOpenModule>
            )} */}
          </div>
        </div>
      </div>
    );
  }
}


export default MiddlePage;
