/* eslint-disable eqeqeq */
import React, { Component } from "react"
import "./index.scss"
import { HeaderBar } from "../../common"
import OrderList from "src/common/OrderList"
import { http } from "src/utils"
import { Link } from "react-router-dom"
import { Modal, Toast } from "antd-mobile"
import Loading from "src/common/Loading"
import InfiniteScroll from "react-infinite-scroller"
import { debounce } from "lodash"
import { connect } from "react-redux"

const alert = Modal.alert

@connect()
class MyOrders extends Component {
  page = 1

  constructor(props) {
    super(props)
    this.state = {
      data: [],
      pageNum: 1,
      isLoading: true,
      total: 0,
    }
  }

  componentDidMount() {
    this.getList(this.page)
  }

  getMore = debounce(() => {
    if (this.state.data.length % 10 === 0) {
      this.getList(++this.page)
    }
  }, 200)

  // 获取订单
  getList = () => {
    http.get(`${API.home}/m/my/orders/${this.page}/10`).then((res) => {
      if (res.data.code === 200) {
        this.setState({
          data: this.state.data.concat(res.data.data),
          isLoading: false,
        })
      } else {
        Toast.info(res.data.msg, 2)
      }
    })
  }

  // 取消订单
  cancel = (oid) => {
    alert(
      "确认取消订单？",
      "订单取消后，优惠券和抵扣的余额会返回到您的账户。",
      [
        { text: "取消", onPress: () => console.log("cancel") },
        {
          text: "确认",
          onPress: () => {
            let data = {
              order_id: oid,
            }
            http.post(`${API.home}/m/cancel_order`, data).then((res) => {
              if (res.data.code === 200) {
                window.location.reload()
              } else {
                Toast.info(res.data.msg, 2)
              }
            })
          },
        },
      ]
    )
  }

  toCourseDetail = (id) => {
    const { history } = this.props
    history.push(`/detail?id=${id}`)
    return false
  }

  render() {
    return (
      <div className="myorders-box">
        <HeaderBar title="我的订单" arrow={true} cart={false}></HeaderBar>
        <Loading isLoading={this.state.isLoading}>
          {this.state.data && JSON.stringify(this.state.data) !== "[{}]" ? (
            <InfiniteScroll
              pageStart={0}
              hasMore={true}
              loadMore={this.getMore.bind(this)}
              useWindow={true}
            >
              {this.state.data.map((item, index) => {
                return (
                  <div className="order-body" key={index}>
                    <OrderInfo item={item} />
                    {item.course &&
                      item.course.length > 0 &&
                      item.course.map((item, index) => {
                        const Info = (
                          <div className="order-info">
                            <p
                              className="order-title text-overflow-one"
                              onClick={() =>
                                this.toCourseDetail(item.course_id)
                              }
                            >
                              {item.course_title}
                            </p>
                            <p className="order-content text-overflow-2">
                              {item.description}
                            </p>
                            <p className="order-des">
                              <span className="order-newprice">
                                ¥{item.amount}
                              </span>
                              <span className="order-price">
                                ¥{item.price0}
                              </span>
                            </p>
                          </div>
                        )
                        return (
                          <div className="order-wrap" key={index}>
                            <OrderList
                              info={Info}
                              src={item.image_name}
                              isSign={item.is_aist}
                              id={item.course_id}
                              toDetail={this.toCourseDetail}
                            />

                            {item.course_expire &&
                              item.course_expire !== "" && (
                                <span className="course-expire">
                                  {item.course_expire}
                                </span>
                              )}
                          </div>
                        )
                      })}

                    <PayInfo item={item} cancel={this.cancel} />

                    {Number(item.type) === 5 &&
                      Number(item.is_buy) === 0 &&
                      Number(item.is_overdue) === 0 && (
                        <div className={"expand-pay-wk"}>
                          <span className={"expand-pay-time"}>
                            {item.final_end_time}结束付尾款
                          </span>
                          <span>还需支付尾款</span>
                        </div>
                      )}
                    {Number(item.type) === 5 &&
                      Number(item.is_buy) === 0 &&
                      Number(item.is_overdue) === 1 && (
                        <div className={"expand-pay-wk"}>
                          <span>支付尾款时间已过</span>
                        </div>
                      )}
                  </div>
                )
              })}{" "}
            </InfiniteScroll>
          ) : (
            <div className="cart-tip">
              <p className="cart-mess">您还没有订单哦，快去逛逛吧~</p>
              <Link to="/classify">去逛逛</Link>
            </div>
          )}
        </Loading>
      </div>
    )
  }
}

function OrderInfo(props) {
  let btn
  if (props.item.pay_time === "0" && props.item.member_num === 0) {
    btn = <span className="oid-status">等待支付</span>
  } else if (
    props.item.pdd_info &&
    props.item.member_num === props.item.pdd_info.length &&
    props.item.member_num !== 0
  ) {
    btn = <span className="oid-success">拼团成功</span>
  } else {
    btn = <span className="oid-success">支付成功</span>
  }
  return (
    <div className="order-head">
      <span className="oid-num">订单号：{props.item.oid}</span>
      {props.item.type == 4 && props.item.course.length == 3 && (
        <span>付费试学</span>
      )}
      {btn}
    </div>
  )
}

function PayInfo(props) {
  // type 0普通订单 1团购 2小团 3砍价 4单集购买 5定金课定金 6定金课尾款
  let type = ""

  if (props.item.type == 5) {
    type = "（定金）"
  }
  if (props.item.type == 6) {
    type = "（尾款）"
  }
  return (
    <div className="order-btm">
      <div className="price-info">
        <p>
          <span className="payable">应付{type}：</span>
          <span className="price">¥{props.item.pay_amount}</span>
        </p>
        <p>
          <span className="payable">已优惠：</span>
          <span className="price">¥{props.item.discount}</span>
        </p>
      </div>

      {props.item.pay_time === "0" && props.item.member_num === 0 && (
        <div className="btm-right">
          <button
            className="cancel"
            onClick={(event) => props.cancel(props.item.oid)}
          >
            取消订单
          </button>
          <Link to={`/payorder?oid=${props.item.oid}`}>去支付</Link>
        </div>
      )}

      {props.item.member_num !== 0 && (
        <div className="btm-right">
          <div className="group">
            {props.item.pdd_info &&
              props.item.pdd_info.length > 0 &&
              props.item.pdd_info.map((item, index) => {
                return (
                  <img
                    src={
                      item.user_avatar === ""
                        ? "https://julyedu-cdn.oss-cn-beijing.aliyuncs.com/tinypng-spreadtrain8/ellipsis.png"
                        : item.user_avatar
                    }
                    key={index}
                    alt=""
                  />
                )
              })}
          </div>
        </div>
      )}
    </div>
  )
}

export default MyOrders
