import React from 'react';
import './index.less';
import Page from '@src/containers/Page';
import { formatDate, getMap } from '@src/services/Tools';
import UserAction from '../../../components/UserAction';
import UserPagination from '../../../components/UserPagination';
import Tabs from '../../../components/Tabs';
import { OpenText } from '../../../components/Open';
import { Button } from '../../../components/Button';
import { Course } from '../../../stores/course';
import { My } from '../../../stores/my';

export default class extends Page {
  constructor(props) {
    props.size = 10;
    super(props);
  }

  initState() {
    return {
      filterMap: {},
      list: [],
      tab: 'special',
      answerSelect: [{ title: '全部', key: '' }, { title: '已回答', key: '1' }, { title: '未回答', key: '0' }],
    };
  }

  init() {
    const { id } = this.params;
    Course.get(id).then(result => {
      const courseNoSelect = result.courseNos.map(row => {
        return {
          title: row.title,
          key: `${row.id}`,
        };
      });
      courseNoSelect.unshift({
        title: '全部课时',
        key: '',
      });
      const courseNoMap = getMap(result.courseNos, 'id');
      const timelineSelect = [{ title: '全部区间', value: '' }];
      const max = Math.max(result.courseNos.map(row => row.time));
      let start = 0;
      let end = start + 5;
      while (start < max) {
        timelineSelect.push({
          title: `${start}:00~${end}:00`,
          key: `${start}`,
        });
        start += 5;
        end = Math.min(start + 5, max);
      }
      this.setState({ course: result, courseNoMap, courseNoSelect, timelineSelect });
    });
  }

  initData() {
    const data = Object.assign(this.state, this.state.search);
    if (data.order) {
      data.sortMap = { [data.order]: data.direction };
    }
    data.filterMap = this.state.search;
    this.setState(data);

    const { tab } = this.state;
    switch (tab) {
      case 'special':
        this.refreshSpecial();
        break;
      case 'my':
        this.refreshMy();
        break;
      default:
        break;
    }
  }

  refreshSpecial() {
    const { id } = this.params;
    this.setState({
      orderSelect: [
        { title: '无', key: '' },
        { title: '时间轴', key: 'position' },
        { title: '更新时间', key: 'updateTime' },
        { title: '查看次数', key: 'viewNumber' },
      ],
    });
    // paixu
    Course.listAsk(Object.assign({ courseId: id }, this.state.search)).then(result => {
      // 只显示单个提问
      if (this.state.search.askId) {
        const askId = Number(this.state.search.askId);
        result.list = result.list.filter(row => row.id === askId);
      }
      this.setState({ list: result.list, total: result.total });
    });
  }

  refreshMy() {
    const { id } = this.params;
    this.setState({
      orderSelect: [
        { title: '无', key: '' },
        { title: '时间轴', key: 'position' },
        { title: '更新时间', key: 'updateTime' },
      ],
    });
    My.listCourseAsk(Object.assign({ courseId: id }, this.state.search)).then(result => {
      this.setState({ list: result.list, total: result.total });
    });
  }

  onTabChange(tab) {
    const data = { tab };
    this.refreshQuery(data);
  }

  onFilter(value) {
    this.search(value, false);
    this.initData();
  }

  onSearch(value) {
    this.search({ keyword: value }, false);
    this.initData();
  }

  onAction() { }

  delAsk(id) {
    My.delCourseAsk(id).then(() => {
      this.refresh();
    });
  }

  viewAsk(id) {
    Course.askView(id);
  }

  renderView() {
    const { course = {}, courseNoMap = {} } = this.state;
    const { tab, courseNoSelect, answerSelect, timelineSelect, orderSelect, filterMap = {}, list = [] } = this.state;
    const { total, page } = this.state;
    const selectActionList = [
      {
        key: 'courseNoId',
        placeholder: '全部课时',
        select: courseNoSelect,
      },
    ];
    selectActionList.push({
      key: 'order',
      placeholder: '排序',
      select: orderSelect,
    });

    if (filterMap.order === 'position') {
      selectActionList.push({
        key: 'position',
        placeholder: '时间区间',
        select: timelineSelect,
      });
    }
    if (tab === 'my') {
      selectActionList.push({
        key: 'answerStatus',
        placeholder: '状态',
        select: answerSelect,
      });
    }

    return (
      <div>
        <div className="top content t-8">
          千行课堂 > 全部课程 > {course.title} > <span className="t-1">全部问答</span>
          <div className="f-r" onClick={() => linkTo(`/course/detail/${course.id}`)}>
            返回课程
          </div>
        </div>
        <div className="center content">
          <div className="t-1 t-s-20 m-b-2">{course.title}</div>
          <Tabs
            border
            type="division"
            theme="theme"
            size="small"
            space={2.5}
            width={100}
            active={tab}
            tabs={[{ key: 'special', title: '精选问答' }, { key: 'my', title: '我的提问' }]}
            onChange={key => this.onTabChange(key)}
          />
          <UserAction
            search
            defaultSearch={filterMap.keyword}
            selectList={selectActionList}
            filterMap={filterMap}
            onFilter={value => this.onFilter(value)}
            onSearch={value => this.onSearch(value)}
          />
          {list.map(item => {
            return (
              <div className="answer-item">
                <div className="t-2">
                  课时{(courseNoMap[item.key] || {}).no} {item.position}:00~{item.position + 5}:00
                </div>
                <div className="t-2">课程内容: {(courseNoMap[item.key] || {}).title}</div>

                {tab === 'my' && item.answerStatus === 0 && (
                  <div className="f-r">
                    <Button radius size="small" onClick={() => this.delAsk(item.id)}>
                      删除
                    </Button>
                  </div>
                )}
                <div>
                  <div className="small-tag">提问</div>
                  <div className="f-r t-2 t-s-12">{formatDate(item.createTime, 'YYYY-MM-DD HH:mm:ss')} <span hidden={tab === 'my'}>阅读 {item.viewNumber}</span></div>
                </div>
                <div className="desc">
                  <OpenText>{item.content}</OpenText>
                </div>
                {item.answerStatus > 0 && (
                  <div>
                    <div className="small-tag">回答</div>
                    <div className="f-r t-2 t-s-12">{formatDate(item.answerTime, 'YYYY-MM-DD HH:mm:ss')}</div>
                  </div>
                )}
                {item.answerStatus > 0 && (
                  <div className="desc">
                    <OpenText onOpen={() => tab !== 'my' && this.viewAsk(item.id)}>
                      {item.answerStatus === 2 ? '与课程内容无关,老师无法作出回答,敬请谅解。' : item.answer}
                    </OpenText>
                  </div>
                )}
              </div>
            );
          })}
          {total > 0 && list.length > 0 && (
            <UserPagination
              total={total}
              pageSize={this.state.search.size}
              current={page}
              onChange={p => this.onChangePage(p)}
            />
          )}
        </div>
      </div>
    );
  }
}