/* eslint-disable eqeqeq, jsx-a11y/anchor-is-valid */
import React, { Component } from "react"
import "./index.scss"
import { http, SendMessageToApp, getParam } from "src/utils"
import { withRouter } from "react-router-dom"
import { connect } from "react-redux"
import { Toast } from "antd-mobile"
import cookie from "js-cookie"
import { setCurrentUser, startFetchUser } from "src/store/userAction"
import { addDays } from "date-fns"

@connect(
  (state) => ({
    user: state.user,
  }),
  { setCurrentUser, startFetchUser }
)
class NewVip extends Component {
  state = {
    userInfoList: [],
    isSetmeal: [],
    isshowPrice: false,
    notice_content: "", // 提示
    countdown: "", // 倒计时
    cutindex: 0,
    lowPrice: "",
    tobuyID: "",
    list1: [
      {
        img: "https://img-public.julyedu.com/Public/Image/c192bec978.png",
        src: "/getDetail?id=483",
      },
      {
        img: "https://img-public.julyedu.com/Public/Image/4e2f24f67b.png",
        src: "/getDetail?id=481",
      },
      {
        img: "https://img-public.julyedu.com/Public/Image/3694b667bb.png",
        src: "/getDetail?id=485",
      },
      {
        img: "https://img-public.julyedu.com/Public/Image/485613bef6.png",
        src: "/getDetail?id=487",
      },
      {
        img: "https://img-public.julyedu.com/Public/Image/442a5af2fd.png",
        src: "/getDetail?id=488",
      },
      {
        img: "https://img-public.julyedu.com/Public/Image/22501871f6.png",
        src: "/getDetail?id=493",
      },
      {
        img: "https://img-public.julyedu.com/Public/Image/a8ab9841f9.png",
        src: "/getDetail?id=449",
      },
      {
        img: "https://img-public.julyedu.com/Public/Image/749464d0cd.png",
        src: "/getDetail?id=450",
      },
      {
        img: "https://img-public.julyedu.com/Public/Image/4fcd7b8189.png",
        src: "/getDetail?id=453",
      },
      {
        img: "https://cdn.julyedu.com/19VIP/newvip/h5/more2.png",
        src: "",
      },
    ], // 特权1
    list2: [
      {
        img: "https://img-public.julyedu.com/Public/Image/6db33ec193.jpg",
        src: "/getDetail?id=325",
      },
      {
        img: "https://img-public.julyedu.com/Public/Image/f310fc5aa7.png",
        src: "/getDetail?id=313",
      },
      {
        img: "https://img-public.julyedu.com/Public/Image/ff4825cdc1.jpg",
        src: "/getDetail?id=360",
      },
      {
        img: "https://img-public.julyedu.com/Public/Image/21419154fd.jpg",
        src: "/getDetail?id=350",
      },
      {
        img: "https://img-public.julyedu.com/Public/Image/221196d9f9.jpg",
        src: "/getDetail?id=330",
      },
      {
        img: "https://cdn.julyedu.com/19VIP/newvip/h5/more1.png",
        src: "",
      },
    ], // 特权2
    teaList: [
      {
        img: "https://img-public.julyedu.com/Public/Image/39cab09dd4.png",
        name: "推荐王老师",
      },
      {
        img: "https://img-public.julyedu.com/Public/Image/36447c04dc.png",
        name: "NLP陈博士",
      },
      {
        img: "https://img-public.julyedu.com/Public/Image/8cc442f2eb.png",
        name: "CV Seven博士",
      },
      {
        img: "https://img-public.julyedu.com/Public/Image/4ea154193d.png",
        name: "CV 刘老师",
      },
      {
        img: "https://img-public.julyedu.com/Public/Image/48ffb4702a.png",
        name: "AI Lab孙老师",
      },
      {
        img: "https://img-public.julyedu.com/Public/Image/7c7496f9e1.png",
        name: "CV 庞博士",
      },
      {
        img: "https://img-public.julyedu.com/Public/Image/cf9b1d22f5.png",
        name: "管博士",
      },
      {
        img: "https://img-public.julyedu.com/Public/Image/17baeda1a1.png",
        name: "推荐殷老师",
      },
    ], // 讲师
    tip: [
      "365*24小时不间断使用",
      "超高性能GPU硬件环境",
      "预装主流DL框架和数据集",
      "可自由上传私人数据集",
    ],
  }

  componentDidMount() {
    this.fetchNotice()
    this.fetchVipBag()

    // 获取App登录信息
    window["loginInfo"] = (result) => {
      this.loginInfo(result)
    }
    document.title =
      "VIP年卡[¥999买一年送一年，含5个大模型小课和200个小课，尊享GPU云平台]"
  }

  // 获取app登录数据
  loginInfo = (result) => {
    this.setState(
      {
        userInfoList: result,
      },
      () => {
        if (this.state.userInfoList.length) {
          this.props.startFetchUser()
          this.appLogin()
        }
      }
    )
  }

  // 保存cookie
  appLogin = () => {
    let expires = addDays(new Date(), 90)
    this.state.userInfoList.forEach((item, index) => {
      cookie.set("token", item.token, {
        expires,
        path: "/",
        domain: ".julyedu.com",
      })
      cookie.set("plat", item.plat, {
        expires,
        path: "/",
        domain: ".julyedu.com",
      })
      cookie.set("uid", item.uid, {
        expires,
        path: "/",
        domain: ".julyedu.com",
      })
      cookie.set("uname", item.uname, {
        expires,
        path: "/",
        domain: ".julyedu.com",
      })
      cookie.set("avatar_file", item.avatar_file, {
        expires,
        path: "/",
        domain: ".julyedu.com",
      })
    })

    if (cookie.get("token") && cookie.get("uid")) {
      this.fetchNotice()
      this.fetchVipBag()
    }

    this.props.setCurrentUser(this.transformUser(this.state.userInfoList))
  }
  transformUser = (res) => {
    let payload
    res.forEach((item, index) => {
      payload = {
        hasError: false,
        data: {
          username: item.uname,
          avatar: item.avatar_file,
          token: item.token,
          uid: item.uid,
        },
        isFetching: false,
      }
    })
    return payload
  }

  fetchVipBag = () => {
    const _this = this
    http.get(`${API.home}/sys/vip_bag`).then((res) => {
      const { code, data, msg } = res.data
      if (code === 200) {
        _this.setState({
          isSetmeal: data,
        })

        let lowPrice = Math.min.apply(
          Math,
          _this.state.isSetmeal.map((item) => {
            return item.price1
          })
        )
        _this.setState({
          lowPrice: lowPrice,
        })

        _this.setState({
          cutindex: _this.state.isSetmeal.findIndex(
            (item) => item.price1 == lowPrice
          ),
        })
        _this.setState({
          tobuyID: _this.state.isSetmeal[_this.state.cutindex].course_id,
        })
      } else {
        Toast.info(msg, 2, null, false)
      }
    })
  }

  fetchNotice = () => {
    const _this = this
    http.get(`${API.home}/sys/notice`).then((res) => {
      const { code, data, msg } = res.data
      if (code === 200) {
        _this.setState({
          notice_content: data.notice_content,
          date: data.date,
        })

        let date = data.date * 1000,
          day = 0,
          hours = 0,
          minutes = 0,
          seconds = 0
        setInterval(function () {
          date -= 1000
          day = `${parseInt(date / (60 * 60 * 24 * 1000))}`
          hours = `${parseInt(
            (date - day * 86400000) / (60 * 60 * 1000)
          )}`.padStart(2, 0)
          minutes = `${parseInt(
            (date - day * 86400000 - hours * 3600000) / 60000
          )}`.padStart(2, 0)
          seconds = `${parseInt(
            (date - day * 86400000 - hours * 3600000 - minutes * 60000) / 1000
          )}`.padStart(2, 0)
          _this.setState({
            countdown: `剩余${day}天${hours}时${minutes}分${seconds}秒`,
          })
        }, 1000)
      } else {
        Toast.info(msg, 2, null, false)
      }
    })
  }

  // 立即购买显示弹窗
  showPrice = () => {
    const isLogin = !this.props.user.hasError
    if (!isLogin) {
      this.toLogin()
    } else {
      this.setState({
        isshowPrice: true,
      })
    }
  }

  toLogin = () => {
    if (!getParam("version")) {
      this.props.history.push("/passport")
    } else {
      SendMessageToApp("toLogin")
    }
  }

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

  // 选择
  tochecked = (item, index) => {
    this.setState({
      cutindex: index,
      tobuyID: item.course_id,
    })
  }

  // 弹窗中的去购买
  tobuy = () => {
    const { isSetmeal, cutindex, tobuyID } = this.state
    let id = tobuyID === "" ? isSetmeal[cutindex].course_id : tobuyID
    if (!getParam("version")) {
      http
        .get(`${API["base-api"]}/m/cart/addtopreorder/[${id}]`)
        .then((res) => {
          if (res.data.errno === 0) {
            this.props.history.push(`/order?id=${id}`, { simple: 1 })
          } else {
            Toast.info(res.data.msg, 2, null, false)
          }
        })
    } else {
      SendMessageToApp("toPay", id)
    }
  }

  render() {
    const {
      notice_content,
      date,
      countdown,
      list1,
      list2,
      tip,
      teaList,
      isSetmeal,
      cutindex,
      isshowPrice,
      lowPrice,
    } = this.state
    return (
      <div className="new-vip">
        {/*banner*/}
        <div className="banner">
          <img
            src="https://cdn.julyedu.com/19VIP/newvip/h5/vip-banner.png"
            alt=""
          />
        </div>

        {/*vip倒计时*/}
        {(notice_content || date) && (
          <div className="notice">
            {notice_content && (
              <div className="tip">
                <img
                  src="https://cdn.julyedu.com/19VIP/newvip/h5/linlin_icon.png"
                  alt=""
                />
                <span>{notice_content}</span>
              </div>
            )}
            {date && <div className="time">{countdown}</div>}
          </div>
        )}

        {/*VIP尊享五大服务*/}
        <div className="privilege-box">
          <div className="privilege-name">VIP尊享五大服务</div>

          {/*特权1*/}
          <div className="privilege-content">
            <PrivilegeTitle num="一" title="最新课程抢先学" />
            <PrivilegeCourse data={list1} />
          </div>

          <Connect position={"left"} />
          <Connect position={"right"} />

          {/*特权2*/}
          <div className="privilege-content">
            <PrivilegeTitle num="二" title="畅学全平台视频课程" />
            <PrivilegeCourse data={list2} />
          </div>

          <Connect position={"left"} />
          <Connect position={"right"} />

          {/*特权3*/}
          <div className="privilege-content">
            <PrivilegeTitle num="三" title="GPU&CPU双云平台免费用" />

            <div className="privilege-list-row">
              <div className="privilege-list-gpu">
                <img
                  src="https://cdn.julyedu.com/19VIP/newvip/h5/gpu1_bj%402x.png"
                  alt=""
                />
                <img
                  src="https://cdn.julyedu.com/19VIP/newvip/h5/gpu2_bj%402x.png"
                  alt=""
                />
              </div>

              <div className="privilege-list-tip">
                {tip.map((item, index) => {
                  return (
                    <div className="privilege-tip-item" key={index}>
                      <span>{index + 1}</span>
                      {item}
                    </div>
                  )
                })}
              </div>
            </div>
          </div>

          <Connect position={"left"} />
          <Connect position={"right"} />

          {/*特权4*/}
          <div className="privilege-content">
            <PrivilegeTitle num="四" title="讲师/助教团队24小时答疑" />

            <p className={"privilege-teacher"}>
              多达100人的AI师资团队提供咨询、答疑服务，助力涨薪
            </p>

            <TeacherList data={teaList} />
          </div>

          <Connect position={"left"} />
          <Connect position={"right"} />

          {/*特权5*/}
          <div className="privilege-content">
            <PrivilegeTitle num="五" title="在线作业及测评平台" />

            <div className="privilege-test">
              <img
                src="https://cdn.julyedu.com/19VIP/newvip/h5/ce1_bj%402x.png"
                alt=""
              />
              <img
                src="https://cdn.julyedu.com/19VIP/newvip/h5/ce2_bj%402x.png"
                alt=""
              />
            </div>
          </div>
        </div>
        <div className="tobuy" onClick={() => this.showPrice()}>
          {lowPrice}元 立即报名
        </div>

        {isshowPrice && (
          <div>
            <div className="checkout-mbc" onClick={() => this.close()}></div>
            <div className="checkout-box">
              <div className="title">
                <span>选择套餐</span>
                <span className={"close"} onClick={() => this.close()}>
                  &#10005;
                </span>
              </div>
              {isSetmeal.map((item, index) => {
                return (
                  <div
                    className={`checkout-list ${
                      cutindex === index ? "list-checked" : "list-check"
                    }`}
                    key={index}
                    onClick={() => this.tochecked(item, index)}
                  >
                    <div className="type">{item.bag_name}</div>
                    <div className="center">
                      {item.discounts_reason === "首购特惠" && (
                        <div className="discounts-reason">
                          {item.discounts_reason}
                        </div>
                      )}
                      {item.discounts_reason !== "首购特惠" && (
                        <div className="discounts-reason discounts-reason2">
                          {item.discounts_reason}
                        </div>
                      )}
                      <div className="price">
                        ¥<span className={"new-price"}>{item.price1}</span>
                        <s className={"old-price"}>¥{item.price0}</s>
                      </div>
                    </div>
                    <div className="check-box">
                      <span
                        className={`${
                          cutindex === index ? "checked" : "check"
                        }`}
                      ></span>
                    </div>
                  </div>
                )
              })}

              <button className="check-tobuy" onClick={() => this.tobuy()}>
                立即购买
              </button>
            </div>
          </div>
        )}
      </div>
    )
  }
}

function PrivilegeTitle(props) {
  return (
    <div className="privilege-title">
      <img src="https://cdn.julyedu.com/19VIP/newvip/h5/viplog.png" alt="" />
      <span>服务{props.num}</span> {props.title}
    </div>
  )
}

function PrivilegeCourse(props) {
  return (
    <div className="privilege-list">
      {props.data.map((item, index) => {
        return (
          <div key={index}>
            {item.src === "" && (
              <a className={"course-box"}>
                <img src={item.img} alt="" />
              </a>
            )}
            {item.src !== "" && (
              <a className={"course-box"} href={item.src}>
                <img src={item.img} alt="" />
              </a>
            )}
          </div>
        )
      })}
    </div>
  )
}

function TeacherList(props) {
  return (
    <div className="teacher-list">
      {props.data.map((item, index) => {
        return (
          <div className="teacher-item" key={index}>
            <img src={item.img} alt="" />
            <span>{item.name}</span>
          </div>
        )
      })}
    </div>
  )
}

function Connect(props) {
  return (
    <div className={`connect ${props.position}`}>
      <span className="top"></span>
      <span className="con"></span>
      <span className="bottom"></span>
    </div>
  )
}

export default withRouter(NewVip)
