import React, { Component } from "react"
import { http, getParam, browser, SendMessageToApp } from "src/utils"
import PythonDes from "./pythomDes"
import PythonStudy from "./pythonStudy"
import { connect } from "react-redux"
import { addDays } from "date-fns"
import cookie from "js-cookie"
import { setCurrentUser, startFetchUser } from "src/store/userAction"
import { Toast } from "antd-mobile"
import { WxLogin } from "src/common/index"

@connect(
  (state) => ({
    user: state.user,
  }),
  { setCurrentUser, startFetchUser }
)
class ML extends Component {
  constructor(props) {
    super(props)
    this.state = {
      isPay: "",
      buyTry: "",
      userInfoList: [],
      isAppUpdate: false,
      backwardVersion: false, // 默认是新版本
      isWxlogin: false,
    }
  }

  componentDidMount() {
    document.title =
      "机器学习小课 [精讲8大经典算法，在线编程，无需安装环境，会 python 即可学习] - 七月在线"
    const _this = this
    this.fetchCourseInfo()
    // 获取App登录信息
    window["loginInfo"] = (result) => {
      _this.loginInfo(result)
    }

    if (browser.isWeixin && getParam("oid")) {
      this.isweixinPay()
    }
    if (getParam("weixinpay")) {
      this.payCallback()
    }
  }

  // 微信内部支付回调
  isweixinPay = () => {
    let _this = this
    let weixin_code = getParam("code")
    if (weixin_code) {
      if (getParam("oid") === undefined) {
        return
      } else {
        http
          .get(
            `${API["base-api"]}/pay/wxpay/pub_charge/oid/${getParam(
              "oid"
            )}/code/${weixin_code}`
          )
          .then((res) => {
            if (res.data.errno === 0) {
              let data = res.data.data

              function onBridgeReady() {
                WeixinJSBridge.invoke(
                  "getBrandWCPayRequest",
                  {
                    appId: data.appId, //公众号名称，由商户传入
                    timeStamp: data.timeStamp, //时间戳，自1970年以来的秒数
                    nonceStr: data.nonceStr, //随机串
                    package: data.package,
                    signType: data.signType, //微信签名方式：
                    paySign: data.paySign, //微信签名
                  },

                  function (res) {
                    if (res.err_msg === "get_brand_wcpay_request:ok") {
                      Toast.info("支付成功", 2)
                      _this.intervalPayStatus = setInterval(function () {
                        http
                          .get(
                            `${API["base-api"]}/m/orderState/oid/${getParam(
                              "oid"
                            )}`
                          )
                          .then((res) => {
                            if (res.data.errno === 401) {
                              clearInterval(_this.intervalPayStatus)
                              _this.intervalPayStatus = null
                              window.location.href = "/ml?id=" + getParam("id")
                            }
                          })
                      }, 1000)
                    }
                  }
                )
              }

              if (typeof WeixinJSBridge == "undefined") {
                if (document.addEventListener) {
                  document.addEventListener(
                    "WeixinJSBridgeReady",
                    onBridgeReady,
                    false
                  )
                } else if (document.attachEvent) {
                  document.attachEvent("WeixinJSBridgeReady", onBridgeReady)
                  document.attachEvent("onWeixinJSBridgeReady", onBridgeReady)
                }
              } else {
                onBridgeReady()
              }
            }
          })
      }
    }
  }
  // 支付完成之后获取状态
  payCallback = () => {
    const _this = this
    // 支付回调
    // 定时器轮训获取订单状态
    _this.intervalPayStatus = setInterval(function () {
      http
        .get(`${API["base-api"]}/m/orderState/oid/${getParam("oid")}`)
        .then((res) => {
          if (res.data.errno === 401) {
            clearInterval(_this.intervalPayStatus)
            _this.intervalPayStatus = null
            window.location.href = "/ml?id=" + getParam("id")
          }
        })
    }, 1000)
  }

  isWxloginFun = (val) => {
    this.setState({ isWxlogin: val })
  }
  // 获取app登录数据
  loginInfo = (result) => {
    this.setState(
      {
        userInfoList: result,
      },
      () => {
        if (this.state.userInfoList.length) {
          this.props.startFetchUser()
          this.appLogin()
        }
      }
    )
  }

  // 保存cookie
  appLogin = () => {
    let expires = addDays(new Date(), 90)
    this.state.userInfoList.forEach((item) => {
      cookie.set("token", item.token, {
        expires,
        path: "/",
        domain: ".julyedu.com",
      })
      cookie.set("plat", item.plat, {
        expires,
        path: "/",
        domain: ".julyedu.com",
      })
      cookie.set("uid", item.uid, {
        expires,
        path: "/",
        domain: ".julyedu.com",
      })
      cookie.set("uname", item.uname, {
        expires,
        path: "/",
        domain: ".julyedu.com",
      })
      cookie.set("avatar_file", item.avatar_file, {
        expires,
        path: "/",
        domain: ".julyedu.com",
      })
    })

    if (cookie.get("token") && cookie.get("uid")) {
      this.setState({
        isAppUpdate: true,
      })
      this.fetchCourseInfo()
    }

    this.props.setCurrentUser(this.transformUser(this.state.userInfoList))
  }

  transformUser = (res) => {
    let payload

    res.forEach((item, index) => {
      payload = {
        hasError: false,
        data: {
          username: item.uname,
          avatar: item.avatar_file,
          token: item.token,
          uid: item.uid,
        },
        isFetching: false,
      }
    })

    return payload
  }

  fetchCourseInfo = () => {
    const id = getParam("id")
    const url = getParam("dist_code")
      ? `${API.home}/m/course/detail/${id}/${getParam("dist_code")}`
      : `${API.home}/m/course/detail/${id}`
    http.get(url).then((res) => {
      const { data, code } = res.data
      if (code === 200) {
        let version = getParam("version")
        if (version) {
          version = version.replace(/\./g, "").slice(0, 3)
          if (browser.isAndroidApp && version < 453) {
            // 安卓的低版本
            this.setState({
              backwardVersion: true,
              isPay: 0,
            })
          } else if (browser.isIOSApp && version < 380) {
            // ISO的低版本
            this.setState({
              backwardVersion: true,
              isPay: 0,
            })
          } else {
            // 安卓/IOS 的高版本
            if (data.course_info.is_pay === 1) {
              // 在APP内未登录-去登陆-登录后还显示此页；如果是已购买的用户 就需要跳转到 APP已购买的原生页面
              SendMessageToApp("toSyllabusChapter", id) // 跳转到APP的已购买详情页 id 是课程ID
              return
            }
            this.setState({
              backwardVersion: false,
              isPay: data.course_info.is_pay,
            })
          }
        } else {
          this.setState({
            backwardVersion: false,
            isPay: data.course_info.is_pay,
            buyTry: data.course_info.buy_try,
          })
        }
      }
    })
  }

  render() {
    const { isPay, buyTry, isAppUpdate, backwardVersion, isWxlogin } =
      this.state
    // 旧版本 无论购买未购买 都跳转到 未购买的详情页； 如果是已购买就提示更新APP
    return (
      <div>
        {isPay === 0 && buyTry === 0 && (
          <PythonDes
            backwardVersion={backwardVersion}
            isWxloginFun={this.isWxloginFun.bind(this)}
            history={this.props.history}
            isAppUpdate={isAppUpdate}
            isPay={isPay}
            buyTry={buyTry}
          />
        )}
        {(isPay === 1 || buyTry === 1) && !getParam("version") && (
          <PythonStudy isAppUpdate={isAppUpdate} buyTry={buyTry} />
        )}

        {isWxlogin && <WxLogin history={this.props.history} />}
      </div>
    )
  }
}

export default ML
