import React from 'react';
import './index.less';
import Page from '@src/containers/Page';
import { formatDate, formatMonth, getMap } from '@src/services/Tools';
import { Course } from '../../../stores/course';
import { My } from '../../../stores/my';
import { PrepareStatus, ExperiencePercent } from '../../../../Constant';

const PrepareStatusMap = getMap(PrepareStatus, 'value', 'short');
const ExperiencePercentMap = getMap(ExperiencePercent, 'value', 'label');

export default class extends Page {
  initState() {
    return {
      data: {},
    };
  }

  initData() {
    const { id } = this.params;
    Course.getExperience(id)
      .then(result => {
        this.setState({ data: result });
      });
    Course.experienceView(id);
  }

  onCollect() {
    const { data } = this.state;
    const { collect } = this.state;
    let collectStatus = false;
    if (collect !== undefined) {
      collectStatus = collect;
    } else {
      collectStatus = data.collect;
    }
    if (!collectStatus) {
      My.addExperienceCollect(data.id)
        .then(() => {
          this.setState({ collect: true });
        });
    } else {
      My.delExperienceCollect(data.id)
        .then(() => {
          this.setState({ collect: false });
        });
    }
  }

  renderView() {
    const { data = {}, collect } = this.state;
    let collectStatus = false;
    if (collect !== undefined) {
      collectStatus = collect;
    } else {
      collectStatus = data.collect;
    }
    return (
      <div>
        <div className="center">
          <div className="content">
            <div className="t-1 t-s-28">{data.title} </div>
            <div className="t-6 m-b-2">
              <span className="m-r-2">{data.updateTime && formatDate(data.updateTime, 'YYYY-MM-DD HH:mm:ss')}</span>
              <span className="m-r-2 m-l-1">阅读 {data.viewNumber || 0}</span>
              <span className="m-l-1 c-p" onClick={() => this.onCollect()}>
                {!collectStatus ? '收藏' : '取消收藏'}
              </span>
            </div>
            <div className="t-1">
              <span className="m-r-2">{data.user ? data.user.nickname : data.nickname}</span>
              <span className="m-r-2 m-l-1">{PrepareStatusMap[data.prepareStatus]}</span>
              <span className="m-r-2 m-l-1">备考:{!!data.experienceDay && formatMonth(data.experienceDay, false)}</span>
              <span className="m-r-2 m-l-1">考试时间:{data.experienceTime && formatDate(data.experienceTime, 'YYYY-MM-DD HH:mm:ss')}</span>
              <span className="m-r-2 m-l-1">{data.experienceScore}分 /提分 {ExperiencePercentMap[data.experiencePercent]}</span>
              {data.link && <a className="m-l-1 t-4" href={data.link} target="_blank">更多信息</a>}
            </div>
            <div className="detail t-1" dangerouslySetInnerHTML={{ __html: data.content }} />
          </div>
        </div>
      </div>
    );
  }
}