import React, { Component } from "react"
import { Flex, List, Toast } from "antd-mobile"
import { OrderItem } from "src/common/index"
import { Link } from "react-router-dom"
import { http, getParam } from "src/utils"
import { HeaderBar } from "src/common/index"

import "./index.scss"

const Item = List.Item

function OrderList(props) {
  const listData = props.list
  return (
    <div>
      {listData.map((item, index) => {
        const {
          course_id,
          image_name,
          sale_price,
          simpledescription,
          course_title,
          coupon_num,
          coupon_desc,
        } = item
        let NewPrice = <span className="order-newprice">¥{sale_price}</span>
        if (props.locationState && props.locationState.group) {
          NewPrice = <span className="order-newprice">¥{props.groupPrice}</span>
        }
        const Info = (
          <div className="order-info">
            <p
              className="order-title"
              style={{
                overflow: "hidden",
                textOverflow: "ellipsis",
                whiteSpace: "nowrap",
              }}
              onClick={() => props.toDetail(course_id)}
            >
              {course_title}
            </p>
            <p
              className="order-content"
              style={{
                WebkitBoxOrient: "vertical",
                WebkitLineClamp: "2",
                wordBreak: "break-all",
                overflow: "hidden",
                textOverflow: "ellipsis",
                display: "-webkit-box",
              }}
            >
              {simpledescription}
            </p>
            <p className="order-des">
              {NewPrice}
              <span className={"price-des"}>（预付定金）</span>
            </p>
          </div>
        )

        return (
          <OrderItem
            {...item}
            src={image_name}
            id={course_id}
            key={index}
            info={Info}
            isaist={props.isaist}
            toDetail={props.toDetail}
          >
            {props.locationState &&
            (props.locationState.type || props.locationState.simple) ? (
              <div className="order-prefer">
                <List key={index}>
                  <Item arrow="horizontal" onClick={() => {}}>
                    <Link
                      to={{
                        pathname: `/coupons`,
                        search: `?id=${course_id}`,
                        state: {
                          from: "/order",
                        },
                      }}
                    >
                      <Flex justify="between">
                        <span
                          style={{
                            color: "#333",
                            fontSize: "15px",
                          }}
                        >
                          优惠券
                        </span>
                        <span
                          style={{
                            fontSize: "14px",
                            color: "#999999",
                          }}
                        >
                          {!coupon_desc
                            ? coupon_num === 0
                              ? "无"
                              : `${coupon_num}张可用`
                            : coupon_desc}
                        </span>
                      </Flex>
                    </Link>
                  </Item>
                </List>
              </div>
            ) : null}
          </OrderItem>
        )
      })}
    </div>
  )
}

class Order extends Component {
  constructor(props) {
    super(props)
    this.state = {
      groupPrice: "",
      total: 0.0, // 需要支付总金额
      discount: 0.0, //
      useBalance: false,
      orderList: [],
      info: false,
      offset: 0,
      depositPrice: 0,
      course_id: getParam("oid"),
      user_account: "",
      finalStartTime: "",
    }
  }

  // 提交订单
  submitOrder = () => {
    http
      .post(`${API["base-api"]}/m/deposit/create`, {
        plat_form: 5,
        source: getParam("source"), //来源 1-详情页 2-活动页,
        course_id: this.state.course_id,
        is_deduction: this.state.useBalance ? 1 : 0,
      })
      .then((res) => {
        const { data } = res
        if (data.errno === 200) {
          if (data.data["pay_jump"]) {
            this.props.history.replace(
              `/expand/callback?order_id=${data.data["order_id"]}`
            )
          } else {
            this.props.history.replace({
              pathname: "/deposit-pay-order",
              search: `?oid=${data.data["order_id"]}`,
            })
          }
        } else {
          Toast.info(data.msg)
        }
      })
  }

  showInfo = () => {
    this.setState((prevState) => ({
      info: !prevState.info,
    }))
  }

  componentDidMount() {
    http
      .post(`${API["base-api"]}/m/deposit/preorder`, {
        course_id: this.state.course_id,
      })
      .then((res) => {
        const { data } = res
        if (data.errno === 200) {
          this.setState({
            orderList: [data.data.course],
            depositPrice: data.data.course["sale_price"],
            user_account: data.data["user_account"],
            finalStartTime: data.data["final_start_time"],
          })
        } else {
          Toast.info(data.msg)
        }
      })
  }

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

  useBalance = () => {
    let { user_account, depositPrice } = this.state
    if (parseFloat(user_account) === 0) {
      return
    }
    let offset = parseFloat(user_account) - parseFloat(depositPrice)
    offset = offset > 0 ? depositPrice : user_account
    this.setState((prevState) => ({
      useBalance: !prevState.useBalance,
      offset,
    }))
  }

  updateUserAccount = () => {}

  render() {
    const {
      orderList,
      discount,
      groupPrice,
      depositPrice,
      user_account,
      useBalance,
      info,
      offset,
      finalStartTime,
    } = this.state

    return (
      <div className="order-wrapper">
        <Flex>
          <Flex.Item>
            <HeaderBar title="课程报名" arrow={true} />
            <div className="order-list">
              <OrderList
                list={orderList}
                courseId={getParam("id")}
                locationState={this.props.location.state}
                groupPrice={groupPrice}
                toDetail={this.toCourseDetail}
              />
            </div>

            <div className="order-balance">
              <List>
                <Item className="order-prefer-text">
                  <Flex justify="between">
                    <Flex align="center">
                      <span>余额抵扣</span>
                      <span className="order-balanceprice">
                        {" "}
                        (余额:{" "}
                        <i className="order-money">{`${user_account}元`}</i>)
                      </span>
                      <i
                        className="iconfont iconiconfront-22 question-mark"
                        onClick={this.showInfo}
                      ></i>
                    </Flex>
                    <Flex>
                      {useBalance ? (
                        <>
                          <span
                            style={{
                              color: "#FF2121",
                              fontSize: "15px",
                              marginRight: "6px",
                            }}
                          >{`-¥${offset}`}</span>
                          <i
                            className={`iconfont icondanseshixintubiao-5 balance-used`}
                            onClick={this.useBalance}
                          ></i>
                        </>
                      ) : (
                        <i
                          className="circle-icon"
                          onClick={this.useBalance}
                        ></i>
                      )}
                    </Flex>
                  </Flex>
                </Item>
              </List>
            </div>

            <ul className={"deposit-limit-time"}>
              <li>· {finalStartTime}开始支付尾款</li>
              <li>· 代金券只能在支付尾款时使用</li>
            </ul>
            <div className="order-bar">
              <div className="order-course">
                <span className="order-course-text">{`${orderList.length}门课程`}</span>
              </div>
              <div className="order-bar-text">
                <div className="order-amount">
                  <span className="order-amount-title">合计:</span>
                  <span className="order-amount-price">{`￥${depositPrice}`}</span>
                </div>
                <div className="order-preprice">
                  <span className="order-preprice-title">已优惠:</span>
                  <span className="order-preprice-price">{`¥${discount}`}</span>
                </div>
              </div>
              <button type="button" className="order-button has-info">
                <span className="order-button-text" onClick={this.submitOrder}>
                  确定订单
                </span>
              </button>
            </div>
          </Flex.Item>
        </Flex>
        {info ? (
          <div
            style={{
              position: "fixed",
              top: 0,
              left: 0,
              width: "100%",
              height: "100%",
              backgroundColor: "rgba(0, 0, 0, 0.8)",
              zIndex: "99",
            }}
          >
            <div
              style={{
                padding: "20px",
                backgroundColor: "#FFF",
                width: "300px",
                height: "170px",
                margin: "0 auto",
                position: "absolute",
                left: "50%",
                top: "50%",
                transform: "translate(-50%, -50%)",
              }}
            >
              <Flex
                direction="column"
                justify="between"
                align="center"
                style={{ height: "100%" }}
              >
                <p style={{ fontSize: "16px", color: "#333333" }}>
                  余额抵扣说明
                </p>
                <p
                  style={{
                    lineHeight: "20px",
                    fontSize: "13px",
                    color: "#666666",
                  }}
                >
                  分销课程或者参与七月在线的相关活动，可获得资金奖励。账户资金可直接提现，也可抵扣课程费用。
                </p>
                <div
                  onClick={this.showInfo}
                  style={{
                    width: "260px",
                    height: "30px",
                    lineHeight: "30px",
                    textAlign: "center",
                    borderRadius: "3px",
                    border: "1px solid #0099FF",
                    color: "#0099FF",
                    fontSize: "15px",
                  }}
                >
                  知道了
                </div>
              </Flex>
            </div>
          </div>
        ) : null}
      </div>
    )
  }
}

export default Order
