import React, { Component } from "react"
import {
  Flex,
  WingBlank,
  WhiteSpace,
  List,
  Radio,
  Toast,
  Checkbox,
} from "antd-mobile"
import { http, getParam, browser } from "src/utils"
import { HeaderBar } from "src/common/index"
import { Link } from "react-router-dom"
import "./index.scss"
import { VList } from "src/common"
import { WithFullSize } from "src/HOCs"
import classnames from "classnames"

const RadioItem = Radio.RadioItem

let mockData
if (browser.isWeixin) {
  mockData = [{ value: 1, label: "微信支付", icon: "iconweixinzhifu" }]
} else {
  mockData = [
    { value: 1, label: "微信支付", icon: "iconweixinzhifu" },
    { value: 0, label: "支付宝", icon: "iconalipay" },
  ]
}

class PayOrder extends Component {
  constructor(props) {
    super(props)
    this.state = {
      pay_amount: 0,
      payType: 1,
      stageNumber: 0,
      checkPeriod: false,
      singleMoney: 0,
      periodNumber: 0,
      orderId: getParam("oid"),
      huabei: false,
      fenqiList: [
        {
          value: "zhifubao",
          qishu: "3",
          lilv: "2.30%",
          everyMoney: 300,
          feiyong: 2.3,
        },
        {
          value: "weixin",
          qishu: "6",
          lilv: "4.50%",
          everyMoney: 150,
          feiyong: 4.5,
        },
        {
          value: "huabei",
          qishu: "9",
          lilv: "7.50%",
          everyMoney: 100,
          feiyong: 7.5,
        },
      ],
      categoryList: [],
      agree: false,
    }
  }

  onChange = (value) => {
    this.setState({
      payType: value,
      checkPeriod: false,
    })
    if (value === 2) {
      this.setState({
        huabei: true,
      })
    }
  }
  // 确定购买
  pay = () => {
    const { payType, orderId } = this.state
    if (!this.state.agree) {
      return
    }
    if (payType === 0) {
      this.alipayPay(orderId)
    } else if (payType === 1) {
      this.weixinPay(orderId)
    }
  }
  // 微信支付
  weixinPay = (orderId) => {
    // 微信内部-支付
    if (browser.isWeixin) {
      window.location.href =
        "https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx23dac6775ac82877&redirect_uri=" +
        encodeURIComponent(window.location.href + "&aa=bb").toLowerCase() +
        "&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect"
    } else {
      // 微信外部-支付
      http
        .get(`${API["base-api"]}/pay/wxpay/wap_charge/oid/${orderId}`)
        .then((res) => {
          if (res.data.errno === 0) {
            window.location.href =
              res.data.data.url +
              "&redirect_url=" +
              encodeURIComponent(
                window.location.href + "&weixinpay=1"
              ).toLowerCase()
          } else {
            Toast.info(res.data.msg, 2)
          }
        })
    }
  }
  // 微信内部支付
  isweixinPay = () => {
    let _this = this
    let weixin_code = getParam("code")
    if (weixin_code) {
      if (getParam("oid") !== undefined) {
        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) {
                    // eslint-disable-next-line eqeqeq
                    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
                              _this.props.history.replace(
                                `/expand/callback?order_id=${getParam("oid")}`
                              )
                            }
                          })
                      }, 1000)
                    } else {
                      alert("支付失败")
                    }
                  }
                )
              }

              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()
              }
            } else {
              Toast.info(res.data.msg, 2)
            }
          })
      }
    }
  }
  // 支付完成之后获取状态
  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 =
              "/expand/callback?order_id=" + getParam("oid")
          }
        })
    }, 1000)
  }

  onBridgeReady1 = (data) => {
    let _this = this
    data = data || _this.BridgeData

    /* eslint-disable-next-line no-undef */
    WeixinJSBridge.invoke(
      "getBrandWCPayRequest",
      {
        appId: "wx23dac6775ac82877", //公众号名称，由商户传入
        timeStamp: data.timeStamp, //时间戳，自1970年以来的秒数
        nonceStr: data.nonceStr, //随机串
        package: data.package,
        signType: data.signType, //微信签名方式：
        paySign: data.paySign, //微信签名
      },
      function (res) {
        // eslint-disable-next-line eqeqeq
        if (res.err_msg == "get_brand_wcpay_request:ok") {
          Toast.info("支付成功", 2)
          _this.payCallback()
        } else {
          alert("支付失败")
        }
      }
    )
  }
  // 支付宝支付
  alipayPay = (orderId) => {
    http
      .get(`${API["base-api"]}/pay/alipay/wap_charge_new/oid/${orderId}`)
      .then((res) => {
        if (res.data.errno === 0) {
          this.payCallback()
          window.location = res.data.data.url
        } else {
          Toast.info(res.data.msg, 2)
        }
      })
  }

  componentDidMount() {
    if (getParam("weixinpay")) {
      this.payCallback()
    }

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

    http
      .post(`${API["base-api"]}/m/deposit/detail`, {
        order_id: this.state.orderId,
      })
      .then((res) => {
        const { data } = res
        // eslint-disable-next-line eqeqeq
        if (data.errno == 200) {
          this.setState({
            categoryList: [data.data.course_info],
            salePrice: data.data.course_info.sale_price,
          })
        } else {
          Toast.info(data.msg)
        }
      })
  }

  changeAgreement = () => {
    this.setState((prevState) => ({ agree: !prevState.agree }))
  }

  render() {
    const {
      orderId,
      salePrice,
      payType,
      checkPeriod,
      singleMoney,
      periodNumber,
      categoryList,
      agree,
    } = this.state
    return (
      <div className="pay-order">
        <HeaderBar title="确认支付" arrow={true}></HeaderBar>
        <WhiteSpace size="sm"></WhiteSpace>
        <div className="order-number">
          <WingBlank>
            <Flex justify="between" align="center" style={{ height: "44px" }}>
              <span>订单号</span>
              <span className="number">{orderId}</span>
            </Flex>
          </WingBlank>
        </div>
        <WhiteSpace size="md"></WhiteSpace>
        {categoryList.map((item, index) => {
          const Info = (
            <div className="order-info">
              <p className="order-title text-overflow-one">
                <Link to={`/detail?id=${item.course_id}`}>
                  {item.course_title}
                </Link>
              </p>
              <p className="order-content text-overflow-2">
                {item.simpledescription}
              </p>
              <p className="order-des">
                <span className="order-newprice">¥{item.sale_price}</span>
                <span className={"price-des"}>（预付定金）</span>
              </p>
            </div>
          )
          return (
            <VList
              key={index}
              img={item.image_name}
              id={item.course_id}
              info={Info}
            ></VList>
          )
        })}
        <WhiteSpace size="md"></WhiteSpace>
        <div className="order-number">
          <WingBlank>
            <Flex justify="between" align="center" style={{ height: "44px" }}>
              <span>支付金额</span>
              <span className="money">{`￥${salePrice}`}</span>
            </Flex>
          </WingBlank>
        </div>

        <WhiteSpace size="md"></WhiteSpace>
        <List renderHeader={() => "支付方式"} className="pay-type-list">
          {mockData.map((i) => (
            <RadioItem
              thumb={
                <i
                  className={`iconfont ${i.icon} ${
                    payType === i.value ? "checked" : ""
                  }`}
                ></i>
              }
              key={i.value}
              checked={payType === i.value}
              onChange={() => this.onChange(i.value)}
            >
              {i.value === 2 ? (
                <Flex
                  direction="column"
                  align="start"
                  style={{ width: "100%", marginTop: "6px" }}
                >
                  <Flex
                    direction="row"
                    justify="between"
                    style={{ width: "100%", paddingRight: "30px" }}
                  >
                    <span style={{ color: "#555555", fontSize: "14px" }}>
                      {i.label}
                    </span>
                    {checkPeriod ? (
                      <span
                        style={{
                          color: "#333333",
                          fontSize: "12px",
                        }}
                      >{`${singleMoney}元 × ${periodNumber}期`}</span>
                    ) : null}
                  </Flex>
                  <Flex justify="start">
                    <span style={{ color: "#999999", fontSize: "12px" }}>
                      支付上限受限于您的花呗额度
                    </span>
                  </Flex>
                </Flex>
              ) : (
                i.label
              )}
            </RadioItem>
          ))}
        </List>
        <Flex>
          <Flex.Item className={"agreement"}>
            <Checkbox.AgreeItem onChange={this.changeAgreement}>
              我已同意定金不退
            </Checkbox.AgreeItem>
          </Flex.Item>
        </Flex>
        {/*<div className='pay-tip'>请在15分钟内完成支付，否则届时系统将关闭该订单。</div>*/}

        <div
          className={classnames(["pay-button", !agree && "invalid"])}
          onClick={this.pay}
        >
          确认支付
        </div>
      </div>
    )
  }
}

export default WithFullSize(PayOrder)
