import React, { Component } from "react"
import "./share.scss"
import { http, getParam, browser, wxShare } from "src/utils"
import { Toast } from "antd-mobile"
import { connect } from "react-redux"
import { Link } from "react-router-dom"
import showAlert from "src/common/deposit/end-expansion-alert"

class ExpandShare extends Component {
  state = {
    isShow: false, //活动规则
    step: 0, // 区分弹窗
    data: "", //膨胀券相关
    courseList: [], // 预售课程列表
    isshowMore: true, // 是否显示查看更多
    pageCount: 1, // 页码
    helpData: "", // 帮助好友助力数据
    courseListMore: "", // 所有课程
  }

  componentDidMount() {
    this.getListorData()
    this.getCourseList()
    if (browser.isWeixin) {
      wxShare({
        title: "AI充电节，预热来袭！80元红包送给你，手要快！",
        desc: "积福气享1折秒课，超10万元奖品来就送--七月在线",
        link: window.location.href,
        imgUrl: "https://cdn.julyedu.com/active19_1111/m/dj-share-img.png",
      })
    }
  }

  // 获取膨胀券相关
  getListorData = () => {
    http
      .get(`${API["base-api"]}/sys/help_list/${getParam("deposit_code")}`)
      .then((res) => {
        const { data, errno, msg } = res.data
        if (errno === 200) {
          this.setState({
            data: data,
          })
        } else {
          Toast.info(msg, 2)
        }
      })
  }

  // 获取课程列表
  getCourseList = () => {
    const _this = this
    http.get(`${API["base-api"]}/anniversary2019/pre_course`).then((res) => {
      const { data, errno, msg } = res.data
      if (errno === 200) {
        if (JSON.stringify(data) === "{}") {
          _this.setState({
            isshowMore: false,
            courseList: [],
          })
        } else if (data.length <= 6) {
          _this.setState({
            isshowMore: false,
            courseList: data,
          })
        } else {
          _this.setState({
            isshowMore: true,
            courseList: data.slice(0, 6),
            courseListMore: data,
          })
        }
      } else {
        Toast.info(msg, 2)
      }
    })
  }

  // 获取更多课程
  getMoreCourseList = () => {
    this.setState({
      courseList: this.state.courseListMore,
      isshowMore: false,
    })
  }
  // 立即付定金
  expandPaydj = (courseId) => {
    const { user } = this.props
    const uid = user && user.data && user.data.uid
    if (!uid) {
      this.props.history.push("/passport/login")
    } else {
      this.props.history.push(`/deposit-order?oid=${courseId}&source=${1}`, {
        id: courseId,
        isexpand: 1,
        sourcenum: 1,
      })
    }
  }
  // 立即付尾款
  expandPaywk = (courseId, time, day) => {
    const { user } = this.props
    const uid = user && user.data && user.data.uid
    if (!uid) {
      this.props.history.push("/passport/login")
    } else {
      let timeStamp = Date.parse(new Date()) / 1000
      if (timeStamp >= time) {
        this.props.history.push("/final-deposit-order?source=1", {
          id: courseId,
          sourcenum: 1,
        })
      } else {
        Toast.info("付尾款时间将在" + day + "开启", 2)
      }
    }
  }
  // 去学习
  tostudy = (courseId) => {
    this.props.history.push(`/getDetail?id=${courseId}`)
  }

  // 显示活动规则
  showRule = () => {
    this.setState({
      isShow: true,
      step: 1,
    })
  }

  // 邀请好友
  share = () => {
    const { user } = this.props
    const uid = user && user.data && user.data.uid
    if (!uid) {
      this.props.history.push("/passport/login")
    } else {
      this.setState({
        isShow: true,
        step: 0,
      })
    }
  }

  // 帮好友助力
  helpFriend = (id) => {
    const { user } = this.props
    const uid = user && user.data && user.data.uid
    if (!uid) {
      this.props.history.push("/passport/login")
    } else {
      http.post(`${API["base-api"]}/sys/help/${id}`).then((res) => {
        const { data, errno, msg } = res.data
        if (errno === 200) {
          this.setState({
            isShow: true,
            step: 2,
            helpData: data,
          })
          this.getListorData()
        } else if (errno === 17018 || errno === 17020) {
          this.setState({
            isShow: true,
            step: 4,
          })
        } else {
          Toast.info(msg, 2)
        }
      })
    }
  }

  // 结束助力
  isendExpand = (data) => {
    const { user } = this.props
    const uid = user && user.data && user.data.uid
    if (!uid) {
      this.props.history.push("/passport/login")
    } else {
      const { amount, limit_amount, id } = data
      showAlert({
        amount,
        limit_amount,
        onCancel: () => {
          this.setState({
            isShow: false,
          })
        },
        onConfirm: () => {
          http
            .post(`${API["base-api"]}/sys/end_expansion`, {
              id,
            })
            .then((res) => {
              const { errno, msg } = res.data
              if (errno === 200) {
                this.setState({
                  isShow: false,
                })
                this.getListorData()
              } else {
                Toast.info(msg)
              }
            })
        },
      })
    }
  }

  // 关闭弹窗
  close = () => {
    this.setState({
      isShow: false,
    })
  }

  render() {
    const { isShow, step, data, courseList, isshowMore, helpData } = this.state
    return (
      <div className="expand-box">
        <div className="banner">
          <img
            src="https://cdn.julyedu.com/active19_1111/m/dj-banner.png"
            alt=""
          />
          <span onClick={() => this.showRule()} />
        </div>
        <div className="all-contnet">
          <div className="content">
            {/*进度||膨胀券*/}
            {<ExpansionStatus data={data} />}
            {/*button*/}
            {
              <ButtonStatus
                data={data}
                share={this.share}
                helpFriend={this.helpFriend}
                isendExpand={this.isendExpand}
              />
            }
          </div>
          {/*好友助力列表*/}
          {(data.oneself === 1 || data.help_list) &&
            data.help_list.length !== 0 && <FriendList data={data} />}
          {/*预售课程列表*/}
          {
            <CourseList
              data={courseList}
              isshowMore={isshowMore}
              getMoreCourseList={this.getMoreCourseList}
              expandPaydj={this.expandPaydj}
              expandPaywk={this.expandPaywk}
              tostudy={this.tostudy}
            />
          }
        </div>

        {isShow && (
          <div className="mbc-box">
            {step === 0 && (
              <ShareBox close={this.close} share={this.share} data={data} />
            )}
            {step === 1 && <ActiveRule />}

            {step === 2 && (
              <AssistanceSuccess
                share={this.share}
                data={data}
                helpData={helpData}
              />
            )}
            {step === 4 && <AssistanceErron close={this.close} />}
            {(step === 1 || step === 2) && (
              <img
                className="close"
                onClick={() => this.close()}
                src="https://cdn.julyedu.com/Public/img/guanbi_icon.png"
                alt=""
              />
            )}
          </div>
        )}
      </div>
    )
  }
}

// 活动规则
function ActiveRule() {
  return (
    <div className="content active-rule">
      <div className="title">活动规则</div>
      <p>
        1、本活动期间，可以助力1位好友不同课程发起的膨胀，但是只能为同一好友；
      </p>
      <p>2、好友发起膨胀后，可以随时终止膨胀；</p>
      <p>
        3、膨胀券膨胀完成后，以优惠券形式发放到参与活动的账号（包括所有助力好友），该膨胀券为全场通用券，可在购买任一课程后进行抵扣（包括已付定金课程）；
      </p>
      <p>4、如有疑问，可联系七月在线客服微信：julyedukefu；</p>
      <p>*本活动最终解释权归七月在线所有</p>
    </div>
  )
}

// 邀请好友 分享弹窗
function ShareBox(props) {
  const { close, data } = props
  return (
    <div className="content">
      <div onClick={() => close()} className="fiexd"></div>
      <div className="share-box">
        {browser.isWeixin && (
          <img src="//cdn.julyedu.com/share/throw_icon.png" alt="" />
        )}
        <p>邀请好友助力</p>
        <p>
          膨胀券翻倍膨胀，{data.start_amount}元变{data.limit_amount}元！
        </p>
        <span>送助力好友{data.limit_amount}元</span>
      </div>
    </div>
  )
}

//助力成功弹窗
function AssistanceSuccess(props) {
  const { helpData, share, data } = props
  return (
    <div className="content assistance-success">
      <div className="title">助力成功</div>
      <p className="add-price">
        <img
          src="https://cdn.julyedu.com/active19_717/m/add-money.png"
          alt=""
        />
        +{helpData.help_amount}
      </p>
      <p className="all-price">
        <span>{helpData.sale_amount}</span>元
      </p>
      <p className="assistance-tip">
        感谢你的助力，你们离{data.limit_amount}元又更近了哦！
        <br />
        可以邀请其他小伙伴一起助力～
      </p>
      <button onClick={() => share()}>
        邀请更多好友拿{data.limit_amount}元
      </button>
    </div>
  )
}

// 助力失败弹窗
function AssistanceErron(props) {
  const { close } = props
  return (
    <div className="content assistance-erron">
      <div className="title">温馨提示</div>
      <p>很遗憾～</p>
      <p>你已经帮别的好友助过力了，</p>
      <p>不能再帮这位好友助力！</p>
      <button onClick={() => close()}>知道了</button>
    </div>
  )
}

// 判断是否结束膨胀
function ExpansionStatus(props) {
  const { data } = props
  //is_end: 0 判断活动是否结束  0否1是
  // is_end_expansion: 0,是否是自己结束膨胀  0否1是
  if (data.is_end === 0 && data.is_end_expansion === 0) {
    return <ProgressData data={data} />
  } else {
    return <EndExpansion data={data} />
  }
}

// 没有结束膨胀的情况
function ProgressData(props) {
  const data = props.data
  return (
    <div>
      <div className="user-mess">
        <img src={data.avatar_file} alt="user" />
        帮我助力，送你{data.limit_amount}元
      </div>
      <div className="progress-box">
        <div className="progress-base">
          <span
            className="progress-active"
            style={{
              width:
                ((data.amount - data.start_amount) / data.limit_amount) * 100 +
                "%",
            }}
          >
            <span className="ending">
              <span className="tip">
                {data.amount}元 <i />
              </span>
            </span>
          </span>
        </div>
        <div className="progress-price">
          <span>{data.start_amount}元</span>
          <span>{data.limit_amount}元</span>
        </div>
      </div>
      {data.help_list.length === 0 && (
        <div className="help-mess no">
          还没有好友为{data.oneself === 1 ? "你" : "Ta"}助力哦～
        </div>
      )}
      {data.help_list.length > 0 && (
        <div className="help-mess has">
          已有<span className="FF19A0">{data.help_list.length}</span>位好友助力
        </div>
      )}
    </div>
  )
}

// 结束膨胀的情况
function EndExpansion(props) {
  const data = props.data
  return (
    <div className="coupon-box">
      <div className="coupon">
        <p className="coupon-name">红包膨胀优惠券</p>
        <p className="coupon-price">
          <span>{data.amount}</span>元
        </p>
        <p className="coupon-time">有效期至：{data.expire_time}</p>
      </div>
      <div className="tip">
        <ul>
          {new Array(19).fill("1").map((item, index) => {
            return <li key={index} />
          })}
        </ul>
        全场通用
      </div>
      <p className="over-mess">该礼券已成功发放至账户</p>
      <p className="over-mess">可在七月在线pc/app-我的-优惠券查看</p>
    </div>
  )
}

// 按钮
function ButtonStatus(props) {
  const { data, share, helpFriend, isendExpand } = props
  // data.oneself 判断是否是自己  0帮好友助力 1自己
  // data.is_help  是否已经帮好友助力  0 未助力 1已助力
  // data.s_end: 0 判断活动是否结束  0否1是
  // data.is_end_expansion: 0,是否是自己结束膨胀  0否1是
  return (
    <div>
      {data.is_end === 0 && (
        <div className="btns">
          {data.oneself === 1 && data.is_end_expansion === 0 && (
            <button className="active" onClick={() => share()}>
              邀请好友助力
            </button>
          )}
          {data.oneself === 1 &&
            data.is_end_expansion === 1 &&
            data.amount !== data.limit_amount && (
              <button className="over">您已结束膨胀</button>
            )}
          {data.oneself === 1 &&
            data.is_end_expansion === 1 &&
            data.amount === data.limit_amount && (
              <button className="over">达到膨胀上限，快去使用吧</button>
            )}

          {data.oneself === 0 &&
            data.is_help === 0 &&
            data.is_end_expansion === 0 && (
              <button className="active" onClick={() => helpFriend(data.id)}>
                帮ta助力
              </button>
            )}

          {data.oneself === 0 &&
            data.is_help === 1 &&
            data.is_end_expansion === 0 && (
              <button className="active" onClick={() => share()}>
                邀请更多好友拿{data.limit_amount}元
              </button>
            )}
          {data.oneself === 0 &&
            data.is_end_expansion === 1 &&
            data.amount === data.limit_amount && (
              <button className="over">达到膨胀上限，快去使用吧</button>
            )}

          {data.oneself === 0 &&
            data.is_end_expansion === 1 &&
            data.amount !== data.limit_amount && (
              <button className="over">你的好友已结束助力</button>
            )}
        </div>
      )}
      {data.is_end === 1 && (
        <div className="btns">
          <button className="over">活动已结束</button>
        </div>
      )}

      {data.is_end === 0 && data.is_end_expansion === 0 && data.oneself === 1 && (
        <div className="overBtn">
          <p onClick={() => isendExpand(data)}>结束助力使用礼券</p>
        </div>
      )}
    </div>
  )
}

// 好友助力列表
function FriendList(props) {
  const data = props.data
  return (
    <div className="friend-list">
      <p className="title">
        <img
          src="https://cdn.julyedu.com/active19_717/m/expand-right.png"
          alt=""
        />
        <span>好友助力</span>
        <img
          src="https://cdn.julyedu.com/active19_717/m/expand-left.png"
          alt=""
        />
      </p>
      {data.help_list.length === 0 && (
        <div className="null-list">
          <p className="tips first-tips">还没有好友为你助力,</p>
          <p className="tips">赶紧去邀请好友吧！</p>
        </div>
      )}
      {data.help_list.length > 0 && (
        <div className="all-list">
          <p className="friend-status">
            <span className="FF19A0">{data.help_list.length}</span>位好友共助力
            <span className="FF19A0">{data.amount - data.start_amount}</span>元
          </p>
          <ul className="all-list-box">
            {data.help_list.map((item, index) => {
              return (
                <li className="item" key={index}>
                  <img className="avait" src={item.avatar} alt="" />
                  <span className="time">助力时间：{item.add_time}</span>
                  <span className="zlprice FF19A0">{item.amount}元</span>
                </li>
              )
            })}
          </ul>
        </div>
      )}
    </div>
  )
}

//预售课程
function CourseList(props) {
  const {
    data,
    isshowMore,
    getMoreCourseList,
    expandPaydj,
    expandPaywk,
    tostudy,
  } = props
  return (
    <div className="advance-sale-course">
      <p className="title">
        <img
          src="https://cdn.julyedu.com/active19_717/m/expand-right.png"
          alt=""
        />
        <span>预售课程</span>
        <img
          src="https://cdn.julyedu.com/active19_717/m/expand-left.png"
          alt=""
        />
      </p>
      <div className="course-list">
        <ul>
          {data.map((item, index) => {
            return (
              <li className="course-item" key={index}>
                <Link to={`/getDetail?id=${item.course_id}`}>
                  <img className="course-img" src={item.image_name} alt="" />
                </Link>
                <p className="old-price">
                  原价:<span>¥{item.price}</span>
                </p>
                <p className="handsel">
                  定金¥{item.deposit_amount}，可抵扣¥{item.deduction_amount}
                </p>
                <div className="btn">
                  {item.is_buy === 0 && (
                    /*eslint-disable-next-line*/
                    <a
                      className="to-expand-buy1"
                      href={"#"}
                      onClick={(e) => {
                        e.preventDefault()
                        expandPaydj(item.course_id)
                      }}
                    >
                      立即付定金
                    </a>
                  )}
                  {item.is_buy === 1 && (
                    /*eslint-disable-next-line*/
                    <a
                      className="to-expand-buy2"
                      href="#"
                      onClick={(e) => {
                        e.preventDefault()
                        expandPaywk(
                          item.course_id,
                          item.start_timestamp,
                          item.final_start_time
                        )
                      }}
                    >
                      立即付尾款
                    </a>
                  )}
                  {item.is_buy === 2 && (
                    <button
                      className="to-study"
                      onClick={() => tostudy(item.course_id)}
                    >
                      开始学习
                    </button>
                  )}
                </div>
              </li>
            )
          })}
        </ul>
      </div>
      {isshowMore && (
        <div className="more">
          <div onClick={() => getMoreCourseList()}>
            查看更多
            <img
              src="https://cdn.julyedu.com/active19_717/m/expand-btm.png"
              alt=""
            />
          </div>
        </div>
      )}
    </div>
  )
}

export default connect((state) => ({
  user: state.user,
}))(ExpandShare)
