/* eslint-disable eqeqeq, jsx-a11y/anchor-is-valid, no-script-url */
import React, { Component } from "react"
import "./togroup.scss"
import { HeaderBar, VList } from "../../../common"
import { getParam, http, browser, wxShare } from "src/utils"
import { connect } from "react-redux"
import { Link } from "react-router-dom"
import { WingBlank, WhiteSpace, Flex, Toast, Modal } from "antd-mobile"

@connect((state) => ({ user: state.user }))
class ToGroup extends Component {
  constructor(props) {
    super(props)
    this.state = {
      data: {},
      share: false,
      pdd_price: 0,
      groupon_member: [],
      person_num: 0, // 共多少人成团
      is_success: false, // 是否拼团成功
      number: 0, // 差几人成团
      isBuy: false,
      modal: false,
      pddOrderId: "",
    }
  }

  invitedFriends = () => {
    const { pdd_price, number, data } = this.state
    if (browser.isWeixin) {
      let share = this.state.share
      this.setState({
        share: !share,
      })
      wxShare({
        title: `【仅剩${number}个名额】我${pdd_price}元拼了《${data.course_title}》`,
        desc: data.course_title,
        link: window.location.href + "&is_originator=1",
        imgUrl: data.image_name,
      })
    } else {
      Toast.info("请在微信中使用分享功能！", 2)
    }
  }

  componentDidMount() {
    http.get(`${API["base-api"]}/pdd/info/${getParam("id")}`).then((res) => {
      if (res.data.errno !== 0) {
        Toast.info(res.data.msg, 2)
        return
      }
      this.setState({
        data: res.data.data.course_info,
        pdd_price: res.data.data.pdd_price,
        groupon_member: res.data.data.groupon_member,
        is_success: res.data.data.is_success,
        person_num: res.data.data.person_num,
        course_list: res.data.data.course_list,
        number: res.data.data.number,
        pddOrderId: res.data.data.pdd_order_id,
        countdown: "",
        isBuy: res.data.data.is_buy,
      })

      if (res.data.data.is_success === 0) {
        let date = res.data.data.end_time * 1000,
          day = 0,
          hours = 0,
          minutes = 0,
          seconds = 0
        setInterval(() => {
          date -= 1000
          if (res.data.data.end_time > 86400) {
            day = `${parseInt(date / (3600000 * 24))}`.padStart(2, 0)
            hours = `${parseInt(
              (date - day * 3600000 * 24) / 3600000
            )}`.padStart(2, 0)
            minutes = `${parseInt(
              (date - day * 3600000 * 24 - hours * 3600000) / 60000
            )}`.padStart(2, 0)
            this.setState({
              countdown: `${day}天${hours}时${minutes}分`,
            })
          } else {
            hours = `${parseInt(date / (60 * 60 * 1000))}`.padStart(2, 0)
            minutes = `${parseInt((date - hours * 3600000) / 60000)}`.padStart(
              2,
              0
            )
            seconds = `${parseInt(
              (date - hours * 3600000 - minutes * 60000) / 1000
            )}`.padStart(2, 0)
            this.setState({
              countdown: `${hours}:${minutes}:${seconds}`,
            })
          }
        }, 1000)
      }
    })
  }

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

  handleToGroup = () => {
    const { isBuy = false, data = {} } = this.state
    const { user, history, location } = this.props
    if (user.hasError) {
      if (browser.isWeixin) {
        let redirectURI = window.location.href
        if (
          redirectURI.includes("code=") &&
          redirectURI.includes("state=STATE")
        ) {
          let index = redirectURI.lastIndexOf("code=")
          redirectURI = redirectURI.substr(0, index - 1)
        }
        window.location.assign(
          `https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx23dac6775ac82877&redirect_uri=${encodeURIComponent(
            redirectURI
          )}&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect`
        )
      } else {
        history.push("/passport", { from: location })
      }
      return
    }

    if (!isBuy) {
      history.push(`/order?id=${data.course_id}`, {
        group: 1,
        pdd_order_id: this.state.pddOrderId,
      })
    } else {
      this.setState({
        modal: true,
      })
    }
  }

  render() {
    const {
      data: { course_id, course_title, simpledescription, price0, price1 },
      is_success,
      course_list,
    } = this.state
    const Info = (
      <div className="info">
        <p className="title" onClick={() => this.toCourseDetail(course_id)}>
          {course_title}
        </p>
        <p className="contact text-overflow-2">{simpledescription}</p>
        <div className="des">
          <p className="course-price">
            <span className="new">¥{price1}</span>
            <span className="old">¥{price0}</span>
          </p>
        </div>
      </div>
    )
    return (
      <div className="to-group-box">
        <HeaderBar title="拼团" cart={false} toHref={"/"}></HeaderBar>
        <Modal
          transparent
          visible={this.state.modal}
          title="提示"
          footer={[
            {
              text: "确定",
              onPress: () => {
                this.setState({
                  modal: false,
                })
                this.props.history.push("/")
              },
            },
          ]}
        >
          <p>您已经购买过该课程～</p>
        </Modal>
        {!is_success && (
          <VList
            img={this.state.data.image_name}
            id={this.state.data.course_id}
            info={Info}
            toDetail={this.toCourseDetail}
          />
        )}

        <GorupContent
          data={this.state}
          invitedFriends={this.invitedFriends}
          handleToGroup={this.handleToGroup}
          userInfo={this.props.user}
        />

        <WhiteSpace></WhiteSpace>
        <div className="group-course">
          <div className="top-title">
            <span>本周特惠</span>
            {/* <Link to={`/preferential`} className="more">
              更多<i className="iconfont iconiconfront-70"></i>
            </Link> */}
          </div>
          {course_list &&
            course_list.length > 0 &&
            course_list[0].course &&
            course_list[0].course.length > 0 &&
            course_list[0].course.slice(0, 4).map((item) => {
              let weekInfo = (
                <div className="info">
                  <p
                    className="title"
                    onClick={() => this.toCourseDetail(item.course_id)}
                  >
                    {/* <Link to={`/detail?id=${item.course_id}`}> */}
                    {item.course_title}
                    {/* </Link> */}
                  </p>
                  <p className="contact text-overflow-2">
                    {item.simpledescription}
                  </p>
                  <div className="des">
                    <p className="course-price">
                      <span className="new">¥{item.pdd_price}</span>
                      <span className="old">¥{item.price0}</span>
                    </p>
                  </div>
                </div>
              )
              return (
                <VList
                  img={item.image_name}
                  key={item.course_id}
                  id={item.course_id}
                  info={weekInfo}
                  toDetail={this.toCourseDetail}
                />
              )
            })}
        </div>
      </div>
    )
  }
}

function GorupContent(props) {
  let tip, btn, dec, groupTip
  const {
    pdd_price,
    data,
    groupon_member,
    is_success,
    person_num,
    share,
    number,
    countdown,
  } = props.data
  const { userInfo } = props
  let ary = [],
    num = number

  while (num != 0) {
    ary.push(num)
    num--
  }
  groupTip = (
    <div className="group-user-list">
      <Flex justify="center" className="imgList">
        {groupon_member.map((item) => {
          return (
            <div className="imgContainer" key={Math.random()}>
              <img className="imgname" src={item.avatar} alt="" />
              {item.user_type === 1 ? (
                <div className="leaderFlag">
                  <span>团长</span>
                </div>
              ) : null}
            </div>
          )
        })}
        {ary.map((item) => {
          return (
            <div className="imgContainer" key={Math.random()}>
              <div className="imgname">
                <i className="iconfont iconwode-xianxing no-body"></i>
              </div>
            </div>
          )
        })}
      </Flex>
    </div>
  )

  if (groupon_member && groupon_member.length > 0) {
    let flag = false
    !userInfo.hasError &&
      groupon_member.forEach((item) => {
        if (item.uid == userInfo.data.uid) {
          flag = true
        }
      })
    if (flag) {
      tip = (
        <p className="tip">{`拼团省￥${Math.round(
          data.price1 - pdd_price,
          2
        )}元`}</p>
      )
      btn = (
        <span className="group-btn" onClick={props.invitedFriends}>
          邀请好友参团 {countdown} 后结束
        </span>
      )
      dec = <p className="dec">分享到3个群后，成团率高达98%</p>
    } else {
      if (getParam("is_originator") == 1) {
        tip = (
          <p className="tip">{`拼团省￥${Math.round(
            data.price1 - pdd_price,
            2
          )}元`}</p>
        )
        btn = (
          <a
            href="javascript:;"
            className="group-btn"
            onClick={props.handleToGroup}
          >
            一键参团
          </a>
        )
      } else {
        tip = (
          <p className="tip">{`拼团省￥${Math.round(
            data.price1 - pdd_price,
            2
          )}元`}</p>
        )
        btn = (
          <span className="group-btn" onClick={props.invitedFriends}>
            邀请好友参团 {countdown} 后结束
          </span>
        )
        dec = <p className="dec">分享到3个群后，成团率高达98%</p>
      }
    }
  }

  if (is_success === 1) {
    tip = <p className="success">拼团成功</p>
    btn = (
      <Link to={`/detail?id=${data.course_id}`} className="tostudy">
        去学习
      </Link>
    )
  }
  return (
    <div className="gorup-content">
      {share ? (
        <div className="groupSuccessMbc" onClick={props.invitedFriends}>
          <div className="tipContent">
            {`还差${number}人，分享到3个群，成团率高达98%`}
          </div>
          <div className="tipArrow">
            <i className="iconfont iconyindao"></i>
          </div>
        </div>
      ) : null}

      {tip}
      <WingBlank>{groupTip}</WingBlank>
      <WingBlank>{btn}</WingBlank>
      {dec}
      {!is_success && (
        <div className="group-dec">
          <span>
            <i className="iconfont iconiconfront-1"></i>
            ·好友参团 ·人满成交 ·人不满退款
          </span>
          <span className="allNum">{`累计${person_num}人成团`}</span>
        </div>
      )}
    </div>
  )
}

export default ToGroup
