/* eslint-disable default-case */
import React, { Component } from "react"
import "./index.scss"
import { Link } from "react-router-dom"
import { browser, getParam, http } from "src/utils"
import { Toast } from "antd-mobile"
import { connect } from "react-redux"
import { WithFullSize } from "src/HOCs"
import { isEmpty } from "lodash"
import { addMessage, addResult, reselect } from "./store"

const messageType = {
  SYSTEM_MESSAGE: 1,
  USER_MESSAGE: 2,
  OPTIONS: 3,
}

class IntelligentRecommend extends Component {
  state = {
    showAnalyzing: false,
    systemAvatar:
      "https://img-public.julyedu.com/Public/Image/home/avatar_20191104.png",
    options: {
      data: [],
      messageId: 0,
    },
    next: {
      oid: 0,
      rid: 0,
    },
  }

  componentDidMount() {
    const { intelligentRecommend, reselect } = this.props
    if (isEmpty(intelligentRecommend.result)) {
      reselect()
      this.getMessage()
    }
  }

  handleSelect = (item) => {
    this.props.addMessage({
      type: messageType.USER_MESSAGE,
      content: item.describe,
      id: item.id,
    })
    this.setState(
      (state) => ({
        options: { data: [], messageId: 0 },
        next: {
          ...state.next,
          oid: item.id,
        },
      }),
      () => {
        this.getMessage()
      }
    )
  }

  getMessage = () => {
    const { oid, rid } = this.state.next
    http.get(`${API.home}/sys/icc/communicate/${oid}/${rid}`).then((res) => {
      const { data, code, msg } = res.data
      if (code === 200) {
        if (data.answer_type === 1) {
          this.setState(
            {
              showAnalyzing: true,
            },
            () => {
              setTimeout(() => {
                this.setState({ showAnalyzing: false })
                this.props.addResult({ ...data })
              }, Math.random() * 500 + 1000)
            }
          )
        } else {
          const message = {
            type: messageType.SYSTEM_MESSAGE,
            content: data.contents.find((item) => item.is_question),
          }
          const optionsData = data.contents.filter((item) => !item.is_question)
          this.props.addMessage(message)
          this.setState({
            options: {
              messageId: message.content.id,
              data: optionsData,
            },
            next: { rid: data.rid },
          })
        }
      } else {
        Toast.fail(msg)
      }
    })
  }

  consult = (e) => {
    e.preventDefault()
    let target = e.target
    http
      .post(`${API.home}/sys/icc/consult`, {
        rid: this.props.intelligentRecommend.result.rid,
      })
      .finally(() => {
        window.location.href = target.getAttribute("href")
      })
  }

  displayPrice = (price) => {
    let _price = price.toString()
    let decimal = _price.split(".")
    return parseInt(decimal[1]) === 0 ? decimal[0] : price
  }

  goBack = () => {
    const { state } = this.props.location
    if (browser.isWeixin && getParam("code") && getParam("state")) {
      window.history.go(-2)
    }
    if (state.records && state.records.length > 1) {
      window.history.go(-1)
    } else if (state.from && state.from.pathname) {
      window.location.replace(`${state.from.pathname}${state.from.search}`)
    } else {
      window.location.href = window.location.origin
    }
  }

  render() {
    const { showAnalyzing, systemAvatar, options } = this.state
    const {
      user,
      intelligentRecommend: { result, processing },
      reselect,
    } = this.props
    const recommends = result.contents
    return (
      <div id={"intelligent-recommend"}>
        <div className="head">
          <div>
            <div className="go-back">
              <i
                className="iconfont iconiconfront-68"
                onClick={this.goBack}
              ></i>
            </div>
            <div className={"title"}>七月在线智能选课</div>
          </div>
          <button
            onClick={() => {
              this.setState(
                {
                  next: { oid: 0, rid: 0 },
                  options: { messageId: 0, data: [] },
                },
                () => {
                  reselect()
                  this.getMessage()
                }
              )
            }}
          >
            重新选课
          </button>
        </div>
        <div className="dialog-box">
          {!!processing.length &&
            // eslint-disable-next-line array-callback-return
            processing.map((item, index) => {
              switch (item.type) {
                case messageType.SYSTEM_MESSAGE:
                  return (
                    <React.Fragment key={index}>
                      <Message
                        text={item.content.describe}
                        identity={"system"}
                        avatar={systemAvatar}
                      />
                      {options.messageId === item.content.id && (
                        <Options
                          options={options.data}
                          handleSelect={this.handleSelect}
                        />
                      )}
                    </React.Fragment>
                  )
                case messageType.USER_MESSAGE:
                  return (
                    <Message
                      text={item.content}
                      identity={"user"}
                      avatar={user.data.avatar}
                      key={index + 2}
                    />
                  )
              }
            })}
          {showAnalyzing && <div className="analyzing">努力分析中...</div>}
        </div>

        {!isEmpty(recommends) && (
          <div className="result">
            <div className="title">根据您目前的情况，推荐结果如下</div>
            <div className="obtained">
              <div
                className={"subtitle"}
                dangerouslySetInnerHTML={{ __html: recommends.skill_title }}
              ></div>
              <div
                className={"skill"}
                dangerouslySetInnerHTML={{ __html: recommends.skill_desc }}
              ></div>
            </div>
            <div className="obtained">
              <div
                className={"subtitle"}
                dangerouslySetInnerHTML={{ __html: recommends.project_title }}
              ></div>
              <div
                className={"skill project"}
                dangerouslySetInnerHTML={{ __html: recommends.project_desc }}
              ></div>
              {/*<ul>
                <li className={'skill project'}>·技能描述、技能描述</li>
                <li className={'skill project'}>·工作及项目描述、工作及项目描述、项目描述</li>
              </ul>*/}
            </div>
            <div className={"salary-section"}>
              <div
                className={"subtitle"}
                dangerouslySetInnerHTML={{ __html: recommends.salary_title }}
              ></div>
              <div
                className={"salary"}
                dangerouslySetInnerHTML={{ __html: recommends.salary_desc }}
              ></div>
            </div>
            <div className="recommends">
              <div>想获得以上技能，向您推荐：</div>
              <ul className={"courses"}>
                {!!recommends.courses.length &&
                  recommends.courses.map((item) => {
                    return (
                      <li
                        className={"course"}
                        key={item.course_id}
                        onClick={(e) => {
                          if (e.target.nodeName.toLowerCase() !== "a") {
                            if (item.course_id) {
                              this.props.history.push(
                                `/detail?id=${item.course_id}`
                              )
                            } else {
                              this.props.history.push(
                                `/play?id=${item.v_course_id}`
                              )
                            }
                          }
                        }}
                      >
                        <div className="cover">
                          <img src={item.img_url} alt="" />
                        </div>
                        <div className="info">
                          <div className={"title"}>{item.recmd_title}</div>
                          <div className={"des"}>{item.recmd_desc}</div>
                          <div className="bar">
                            {item.c_type === 1 && (
                              <React.Fragment key={item.course_id}>
                                <div className="prices">
                                  <span className={"price"}>
                                    ￥{this.displayPrice(item.price_sale)}
                                  </span>
                                  <span className={"old-price"}>
                                    ￥{this.displayPrice(item.price_original)}
                                  </span>
                                </div>
                                <Link
                                  className={"register"}
                                  to={`/detail?id=${item.course_id}`}
                                >
                                  {item.second_btn}
                                </Link>
                              </React.Fragment>
                            )}
                            {item.c_type === 2 && (
                              <React.Fragment key={item.course_id}>
                                <a
                                  href="https://live.easyliao.com/live/chat.do?c=27526&g=53481&config=81372"
                                  className={"contact"}
                                  onClick={this.consult}
                                >
                                  {item.consult}
                                </a>
                                <Link
                                  className={"register"}
                                  to={`/detail?id=${item.course_id}`}
                                >
                                  {item.second_btn}
                                </Link>
                              </React.Fragment>
                            )}
                            {item.c_type === 0 && (
                              <Link
                                className={"study"}
                                to={`/play?id=${item.v_course_id}`}
                              >
                                {item.second_btn}
                              </Link>
                            )}
                          </div>
                        </div>
                      </li>
                    )
                  })}
              </ul>
            </div>
          </div>
        )}
      </div>
    )
  }
}

function Message({ text, avatar, identity }) {
  return (
    <div className={`message clearfix ${identity}`}>
      <div className="avatar">
        <img src={avatar} alt="" />
      </div>
      <div className={`text`}>{text}</div>
    </div>
  )
}

function Options({ options, handleSelect }) {
  return (
    <ul className={"options"}>
      {!!options.length &&
        options.map((item) => {
          return (
            <li onClick={() => handleSelect(item)} key={item.id}>
              <button>{item.describe}</button>
            </li>
          )
        })}
    </ul>
  )
}

export default connect(
  ({ user, intelligentRecommend }) => ({ user, intelligentRecommend }),
  { addMessage, addResult, reselect }
)(WithFullSize(IntelligentRecommend))
