/* eslint-disable */
import React, { Component } from "react"
import { Accordion, Toast } from "antd-mobile"
import { HeaderBar, CallApp } from "src/common"
import { http, getParam, browser } from "src/utils"
import "./index.scss"
import { connect } from "react-redux"
import Mask from "./../poup/index.js"
import ShareRank from "src/components/detail/shareRank"

class PythonStudy extends Component {
  constructor(props) {
    super(props)
    this.state = {
      toApp: false,
      courseInfo: "",
      orderId: "",
      syllabus: "",
      learning: "",
      isShowChannel: window.sessionStorage.getItem("isShowSiteWindowByChannel"),
    }
  }

  componentDidMount() {
    this.fetchCourseDetail()
  }

  fetchCourseDetail = () => {
    const { buyTry } = this.props

    http
      .get(
        `${API["home"]}/web/it_detail?course_id=${getParam(
          "id"
        )}&is_pay=1&buy_try=${buyTry}`
      )
      .then((res) => {
        const { data, code, msg } = res.data
        if (code === 200) {
          this.setState({
            courseInfo: data.course_info,
            syllabus: data.syllabus,
            learning: data.learning,
          })
        } else {
          Toast.info(msg, 2)
        }
      })
  }

  Change = (data) => {
    let cn = ["一", "二", "三", "四", "五", "六", "七", "八", "九", "十"]
    let newStr = ""
    let str = data.toString()
    let ci = Number(str) % 10
    let cs = Math.floor(Number(str) / 10)
    let cv = ""
    if (str.length > 1) {
      if (cs == 1) {
        cv = ci >= 1 ? cn[9] + cn[ci - 1] : cn[9]
      } else {
        cv = ci > 1 ? cn[cs - 1] + cn[9] + cn[ci - 1] : cn[cs - 1] + cn[9]
      }
    } else {
      cv = cn[ci - 1]
    }
    newStr = str.replace(str, cv)
    return newStr
  }

  onChange = (key) => {
    console.log(key)
  }

  toPythonHome = (isUnlock) => {
    if (Number(isUnlock) === 1) {
      this.setState({
        toApp: true,
      })
    }
  }

  toLearn = () => {
    this.setState({
      toApp: true,
    })
  }
  closePop = () => {
    this.setState({
      toApp: false,
    })
  }

  creatOid = () => {
    http
      .post(`${API["base-api"]}/sys/it_baoming/create`, {
        course_id: getParam("id"),
      })
      .then((res) => {
        const { errno, data, msg } = res.data
        if (errno === 200) {
          this.setState({
            orderId: data.oid,
          })
          this.weixinPay(data.oid)
        } else {
          Toast.info(msg, 2)
        }
      })
  }
  // 微信支付
  weixinPay = (orderId) => {
    // 微信内部-支付
    if (browser.isWeixin) {
      let url =
        window.location.origin +
        window.location.pathname +
        "?id=" +
        getParam("id")
      window.location.href =
        "https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx23dac6775ac82877&redirect_uri=" +
        encodeURIComponent(url + "&aa=bb&oid=" + orderId).toLowerCase() +
        "&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect"
    } else {
      // 微信外部-支付
      http
        .get(`${API["base-api"]}/pay/wxpay/wap_charge/oid/${orderId}`)
        .then((res) => {
          if (res.data.errno === 0) {
            window.location.href =
              res.data.data.url +
              "&redirect_url=" +
              encodeURIComponent(
                window.location.href + "&weixinpay=1&oid=" + orderId
              ).toLowerCase()
          } else {
            Toast.info(res.data.msg, 2)
          }
        })
    }
  }

  render() {
    const { user } = this.props
    const uid = user && user.data && user.data.uid
    const { courseInfo, syllabus, learning, toApp } = this.state
    return (
      <div className="python-study">
        <HeaderBar title="机器学习小课" arrow={true} />
        <div className="python-study__header">
          <div className="python-study__course">
            <h2 className="python-study__course-name">机器学习小课</h2>
            {courseInfo.buy_try == 0 && (
              <p className="python-study__course-contact">
                <span>
                  {courseInfo.contact_type == 1
                    ? "上课请加QQ学习群"
                    : "添加助教微信入群"}
                  :{courseInfo.course_qq}
                </span>
                <span>并备注您的学号:{uid}</span>
              </p>
            )}
          </div>
          {learning.schedule > 0 && (
            <div className="python-study__progress">
              <h2 className="python-study__progress-title">
                学习进度
                {!!learning.day && (
                  <span>
                    (已连续学习<span>{learning.day}</span>天)
                  </span>
                )}
              </h2>
              <div className="python-study__progress-bar">
                <i style={{ width: learning.schedule + "%" }} />
                <span
                  className="python-study__progress-tip"
                  style={{ left: learning.schedule + "%" }}
                >
                  {learning.schedule + "%"}
                </span>
              </div>
            </div>
          )}

          {this.state.isShowChannel == 1 && <CallApp className="toapp" />}
        </div>
        {!!courseInfo.is_dist && (
          <div className={"dist-wrapper"}>
            <ShareRank courseInfo={courseInfo} />
          </div>
        )}
        <Accordion
          defaultActiveKey="0"
          className="python-study__stage"
          onChange={this.onChange}
        >
          {syllabus &&
            syllabus.length > 0 &&
            syllabus.map((syllabusItem, index) => {
              let header = `第${this.Change(syllabusItem.stage)}阶段:${
                syllabusItem.name
              }`
              return (
                <Accordion.Panel header={header} className="pad" key={index}>
                  {syllabusItem.lessons &&
                    syllabusItem.lessons.length > 0 &&
                    syllabusItem.lessons.map((lessonsItem, index) => {
                      return (
                        <div key={index}>
                          <h2 className="python-study__pass">
                            第{lessonsItem.shut}关 {lessonsItem.name}
                            {lessonsItem.complete == 1 && (
                              <i className="python-study__pass-tag">闯关完成</i>
                            )}
                          </h2>

                          <div
                            className="python-study__subject"
                            style={{
                              opacity:
                                lessonsItem.info.is_unlock == 0 ? ".6" : "1",
                            }}
                            onClick={() => {
                              this.toPythonHome(lessonsItem.info.is_unlock)
                            }}
                            key={index}
                          >
                            <img
                              className="python-study__subject-icon"
                              src={lessonsItem.info.img_url}
                              alt=""
                            />
                            {lessonsItem.info.is_unlock == 1 &&
                              lessonsItem.info.complete == 1 && (
                                <i
                                  className="python-study__subject-status"
                                  data-status="complete"
                                />
                              )}
                            {lessonsItem.info.is_unlock == 0 && (
                              <i
                                className="python-study__subject-status"
                                data-status="lock"
                              />
                            )}
                            <div className="python-study__subject-content">
                              <h2 className="python-study__subject-title text-overflow-1">
                                {lessonsItem.info.name}
                              </h2>
                            </div>
                          </div>

                          {lessonsItem.project && (
                            <div
                              className="python-study__subject"
                              style={{
                                opacity:
                                  lessonsItem.project.is_unlock == 0
                                    ? ".6"
                                    : "1",
                              }}
                              onClick={() => {
                                this.toPythonHome(lessonsItem.project.is_unlock)
                              }}
                            >
                              <img
                                className="python-study__subject-icon"
                                src="https://julyedu-cdn.oss-cn-beijing.aliyuncs.com/mlCourse/m/project-icon.png"
                                alt=""
                              />
                              {lessonsItem.project.is_unlock == 1 &&
                                lessonsItem.project.complete == 1 && (
                                  <i
                                    className="python-study__subject-status"
                                    data-status="complete"
                                  />
                                )}
                              {lessonsItem.project.is_unlock == 1 &&
                                lessonsItem.project.complete == 0 && (
                                  <i
                                    className="python-study__subject-status"
                                    data-status="lock"
                                  />
                                )}
                              <div className="python-study__subject-content">
                                <h2 className="python-study__subject-title text-overflow-1">
                                  {lessonsItem.project.name}
                                </h2>
                                {lessonsItem.project.is_must == 1 && (
                                  <span className="python-study__subject-tag">
                                    必做练习
                                  </span>
                                )}
                              </div>
                            </div>
                          )}
                        </div>
                      )
                    })}
                  {index === 0 &&
                    syllabus[0].lessons[2].info.complete == 1 &&
                    courseInfo.buy_try == 1 && (
                      <div className="study-end">
                        试学结束,<span>{courseInfo.price1}元</span>学习全部课时
                        <a
                          className="tobuy"
                          onClick={() => {
                            this.creatOid()
                          }}
                        >
                          立即报名
                        </a>
                      </div>
                    )}
                </Accordion.Panel>
              )
            })}
        </Accordion>
        {learning.schedule == 0 && (
          <span onClick={this.toLearn} className="python-study__button">
            开始学习
          </span>
        )}
        {learning.schedule != 0 && learning.schedule != 100 && (
          <span onClick={this.toLearn} className="python-study__button">
            继续学习
          </span>
        )}
        {learning.schedule == 100 && (
          <button className="python-study__button python-study__over">
            已学完全部课时
          </button>
        )}

        {toApp && <Mask closePop={this.closePop} type={2} />}
      </div>
    )
  }
}

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