
'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 } from '@src/utils/utils';
import WxOpenModule from '@src/components/wxOpenModule/wxOpenModule';
import { 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,
    };
  }

  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;
    // console.log(actUrl);
    const jumpUrl = decodeURIComponent(decodeURIComponent(decodeURIComponent(getUrlParam("redirectUrl")))) || CFG.index;
    
    let directUrl = encodeURIComponent(
      encodeURIComponent(
        actUrl +
          `&channel=${channel}&empno=${empno}&empname=${empname}&wdTK=${wdTK}&isFromShare=${isFromShare}&empnoShow=${empnoShow}`
      )
    );

    // alert(actUrl);
    // alert(directUrl);
    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"))
      // JSON.parse(decodeURIComponent(getUrlParam("wdTK")));
      // alert("thirdParam " + thirdParam + "123 " + custPhone)
      console.error("kankancanshu", thirdParam, custPhone)
      // location.href = `${CFG.middleTHRequest}requestParam=${requestParam}&redirect=${directUrl}&channel=${channel}&sign=${sign}&timestamp=${timestamp}&empno=${newEmpno}&empname=${newEmpname}&openid=${openId}&wdTK=${newWdTK}&empnoShow=${newEmpnoShow}&custPhone=${custPhone}`;
     console.info('---sign',getUrlParam("thdParam") + timestamp + "24fnTNEK8KqURnlZhIJ58mdylVe1rs0BZha")
      const {success, data} = await API.thdLoginNew({
        requestParam:encodeURIComponent(getUrlParam("thdParam")),
        redirect:decodeURIComponent(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_THD25DragonBoat',
        environment:CFG.environment,
        // environment:CFG.projectId == 'pd5fd3088' ? 'test' : ''
      })
      if(success){
        if(data?.boolLogin){ // 已登录
          location.href = data?.autoLoginUrl; //免登录链接
        }else{
          location.href = data?.authUrl; //授权地址
        }
      }
    }else{
      const { success, data } = await API.tbLoginNew({
        token: getUrlParam("token"),
        src: "d8",
        redirectUrl: directUrl,
      });
      if (success) {
        if (data?.loginFlag) {
          location.href = data?.autoLoginUrl;
        }
      } else {
      }
    }
    // 这个活动投太好店
    // let targetUrl = `${CFG.middleRequest}requestParam=${requestParam}&redirect=${directUrl}&channel=${channel}&sign=${sign}&timestamp=${timestamp}&empno=${empno}&empname=${empname}&wdTK=${wdTK}`;
    // if (param && param != "changHangParam") targetUrl += `&chparam=${param}`;
    // location.href = targetUrl;
    
  }

  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_25DragonBoat`
    );
    if (isWeixinMini) {
      //官微小程序
      CFG.miniAppid = "wx68b00bbff4c69cc9"; //生产appid wx68b00bbff4c69cc9   测试appid:  wx0fe22fef352fafc1
      CFG.miniUserName = "gh_70448c19370c";
      path = `/packageMember/pages/bindPhone/thirdBindPhone/thirdBindPhone?gwAuthToken=P_PT_PHONE_25DragonBoat&channel=${CFG.channel}`;
    } else {
      //H5默认跳转官微小程序
      CFG.miniAppid = "wx68b00bbff4c69cc9";
      CFG.miniUserName = "gh_70448c19370c";
      path = `/packageMember/pages/bindPhone/thirdBindPhone/thirdBindPhone?gwAuthToken=P_PT_PHONE_25DragonBoat&channel=${CFG.channel}`;
    }

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

    return path;
  };

  handleToDraw = _throttle(() => {
    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.handleToDraw}>
            {!isWeixinMini && (
              <WxOpenModule
                id={"downLoadbtn"}
                appid={CFG.miniAppid}
                username={CFG.miniUserName}
                envVersion={CFG.miniEnv}
                path={this.getWeixinMiniPath()}></WxOpenModule>
            )}
          </div>
        </div>
      </div>
    );
  }
}


export default MiddlePage;
