import React, { Component } from 'react';
import './index.less';
import { Icon } from 'antd';
import Page from '@src/containers/Page';
import { formatDate, getMap } from '@src/services/Tools';
import Modal from '../../../components/Modal';
import UserAction from '../../../components/UserAction';
import UserPagination from '../../../components/UserPagination';
import { RealAuth } from '../../../components/OtherModal';
import Examination from '../../../components/Examination';
import VipRenew from '../../../components/VipRenew';
import CheckboxItem from '../../../components/CheckboxItem';
import { Course } from '../../../stores/course';
import { My } from '../../../stores/my';

export default class extends Page {
  initState() {
    return {
      filterMap: {},
      sortMap: {},
      // list: [
      //   {
      //     title: '比较对象对等问题',
      //     content:
      //       '从比较对象和句子结构我们能把DE排除掉,D选项中dffat和livestock不是比较对象,E选项中and 后面的句子太凌乱is of a kind ….is…结构出现了重大问题?从比较对象和句子结构我们能把DE排除掉,D选项中fat和livest。ock不是比较对象,E选项中and 后面的句子太凌乱is of a kind ….is…结构出现了重大问题?从比较对象和句子结构我们能把DE排除掉,D选项中fat和livestock不是比较对象,E选项中and 后面的句子太凌乱is of a kind ….is…结构出现了重大问题?从比较?对象和句子结构我们能把?DE排除掉,D选项中fat和livestock不是比较对象,E选项中and 后面的句子太凌乱is of a kind ….is…结构出现了重大问题?从比较对象和句子结。构我们能把DE排除掉,D选项中fat和livestock不是比较对象.',
      //   },
      //   {
      //     title: '比较对象对等问题',
      //     content:
      //       '从比较对象和句子结构我们能把DE排除掉,D选项中dffat和livestock不是比较对象,E选项中and 后面的句子太凌乱is of a kind ….is…结构出现了重大问题?从比较对象和句子结构我们能把DE排除掉,D选项中fat和livest。ock不是比较对象,E选项中and 后面的句子太凌乱is of a kind ….is…结构出现了重大问题?从比较对象和句子结构我们能把DE排除掉,D选项中fat和livestock不是比较对象,E选项中and 后面的句子太凌乱is of a kind ….is…结构出现了重大问题?从比较?对象和句子结构我们能把?DE排除掉,D选项中fat和livestock不是比较对象,E选项中and 后面的句子太凌乱is of a kind ….is…结构出现了重大问题?从比较对象和句子结。构我们能把DE排除掉,D选项中fat和livestock不是比较对象.',
      //   },
      //   {
      //     title: '比较对象对等问题',
      //     content:
      //       '从比较对象和句子结构我们能把DE排除掉,D选项中dffat和livestock不是比较对象,E选项中and 后面的句子太凌乱is of a kind ….is…结构出现了重大问题?从比较对象和句子结构我们能把DE排除掉,D选项中fat和livest。ock不是比较对象,E选项中and 后面的句子太凌乱is of a kind ….is…结构出现了重大问题?从比较对象和句子结构我们能把DE排除掉,D选项中fat和livestock不是比较对象,E选项中and 后面的句子太凌乱is of a kind ….is…结构出现了重大问题?从比较?对象和句子结构我们能把?DE排除掉,D选项中fat和livestock不是比较对象,E选项中and 后面的句子太凌乱is of a kind ….is…结构出现了重大问题?从比较对象和句子结。构我们能把DE排除掉,D选项中fat和livestock不是比较对象.',
      //   },
      // ],
      selectList: [],
      allChecked: false,
      showDetail: false,
    };
  }

  init() {
    const { id } = this.params;
    Course.get(id)
      .then(result => {
        const courseNoMap = getMap(result.courseNos, 'id');
        this.setState({ course: result, courseNoMap });
      });
  }

  initData() {
    const { id } = this.params;
    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);

    My.listCourseNote(Object.assign({ courseId: id }, this.state.search))
      .then(result => {
        result.list = result.list.map(row => {
          row.key = row.courseNoId;
          return row;
        });
        this.setState({ list: result.list, total: result.total });
      });
  }

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

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

  onSort(value) {
    const keys = Object.keys(value);
    // this.search({ order: keys.length ? keys.join('|') : null, direction: keys.length ? Object.values(value).join('|') : null });
    const { sortMap } = this.state;
    const index = keys.length > 1 && sortMap[keys[0]] ? 1 : 0;
    this.search({ order: keys.length ? keys[index] : null, direction: keys.length ? value[keys[index]] : null }, false);
  }

  onChangePage(page) {
    this.search({ page }, false);
    this.initData();
  }

  onAll(checked) {
    const { selectList } = this.state;
    const { list = [] } = this.state;
    if (checked) {
      list.forEach(item => {
        if (selectList.indexOf(item.key) >= 0) return;
        selectList.push(item.key);
      });
    } else {
      list.forEach(item => {
        const index = selectList.indexOf(item.key);
        if (index < 0) return;
        selectList.splice(index, 1);
      });
    }
    this.setState({ selectList, allChecked: checked });
  }

  onSelect(selectList) {
    this.setState({ selectList, allCheckbox: false });
  }

  onAction(key) {
    const { info } = this.props.user;
    const { selectList } = this.state;
    switch (key) {
      case 'help':
        this.setState({ showTips: true });
        return;
      case 'clear':
        if (selectList.length === 0) {
          this.setState({ showWarn: true, warn: { title: '移除', content: '不可少于1篇,请重新选择' } });
          return;
        }
        this.setState({ showClearConfirm: true, clearInfo: { courseNoIds: selectList } });
        break;
      case 'export':
        if (!info.vip) {
          this.setState({ showVip: true });
          return;
        }
        if (selectList.length < 1) {
          this.setState({ showWarn: true, warn: { title: '导出', content: '不可小于1篇,请重新选择' } });
          return;
        }
        this.setState({ showExportConfirm: true, exportInfo: { courseNoIds: selectList } });
        break;
      default:
    }
  }

  clearNote() {
    const { exportInfo } = this.state;
    My.clearCourseNote(exportInfo.courseNoIds)
      .then(() => {
        this.refresh();
      })
      .then(e => {
        this.setState({ warn: { title: '移除', content: e.message }, showClearConfirm: false });
      });
  }

  export() {
    const { exportInfo } = this.state;
    this.setState({ showExportWait: true, showExportConfirm: false, showExportAuthConfirm: false });
    My.exportNoteCourse(exportInfo)
      .then((result) => {
        openLink(`/export/${result}`);
        this.setState({ showExportWait: false });
      })
      .catch(e => {
        this.setState({ warn: { title: '导出', content: e.message }, showExportWait: false });
      });
  }

  prevArticle() {
    const { article, list } = this.state;
    let index = 0;
    list.forEach((row, i) => {
      if (article.key === row.key) index = i;
    });
    index -= 1;
    if (index < 0) {
      index = list.length + index;
    }
    this.setState({ article: list[index] });
  }

  nextArticle() {
    const { article, list } = this.state;
    let index = 0;
    list.forEach((row, i) => {
      if (article.key === row.key) index = i;
    });
    index += 1;
    if (index >= list.length) {
      index -= list.length;
    }
    this.setState({ article: list[index] });
  }

  renderView() {
    const { course = {}, courseNoMap = {}, list = [], selectList = [], sortMap, filterMap, allChecked, total, page } = this.state;
    const {
      user: { info },
    } = this.props;
    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>
          <UserAction
            allCheckbox
            allChecked={allChecked}
            search
            defaultSearch={filterMap.keyword}
            btnList={[
              { title: '删除', key: 'delete' },
              { title: '导出', key: 'export', tag: 'vip', disabled: !info.vip },
            ]}
            sortList={[
              { right: true, label: '课时', key: 'courseNoId', fixed: true },
              { right: true, label: '更新时间', key: 'updateTime', fixed: true },
            ]}
            sortMap={sortMap}
            filterMap={filterMap}
            onFilter={value => this.onFilter(value)}
            onSearch={value => this.onSearch(value)}
            onSort={value => this.onSort(value)}
            onAll={checked => this.onAll(checked)}
            onAction={key => this.onAction(key)}
          />
          <div className="list">
            {list.map(item => {
              return <Note data={item} selectList={selectList} courseNoMap={courseNoMap} onSelect={(value) => this.onSelect(value)} onClick={() => this.setState({ showDetail: true, article: item })} />;
            })}
          </div>
          {total > 0 && list.length > 0 && (
            <UserPagination total={total} current={page} pageSize={this.state.search.size} onChange={p => this.onChangePage(p)} />
          )}
        </div>
        {this.renderModal()}
      </div>
    );
  }

  renderModal() {
    const { showWarn, warn = {}, showClearConfirm, clearInfo = {}, showVip, showExamination, showReal, showExportWait, showExportConfirm, exportInfo = {} } = this.state;
    const { info } = this.props.user;
    const { article = {} } = this.state;
    return [
      <NoteDetail
        show={this.state.showDetail}
        data={article}
        onClose={() => this.setState({ showDetail: false })}
        onPrev={() => this.prevArticle()}
        onNext={() => this.nextArticle()}
      />,
      <Modal show={showWarn} title={warn.title} confirmText="好的,知道了" btnAlign="center" onConfirm={() => this.setState({ showWarn: false })}>
        <div className="t-2 t-s-18">{warn.content}</div>
      </Modal>,
      <Modal show={showClearConfirm} title="移出" onConfirm={() => this.clearNote()} onCancel={() => this.setState({ showClearConfirm: false })}>
        <div className="t-2 t-s-18">
          当前选中的 <span className="t-4">{clearInfo.courseNoIds ? clearInfo.courseNoIds.length : 0}</span> 篇即将被移出笔记,移出后无法恢复,是否继续?
        </div>
      </Modal>,
      <Modal show={showExportConfirm} title="导出" confirmText="导出" onConfirm={() => this.export()} onCancel={() => this.setState({ showExportConfirm: false })}>
        <div className="t-2 t-s-18 m-b-5">
          当前共选中 <span className="t-4">{exportInfo.courseNoIds ? exportInfo.courseNoIds.length : 0}</span> 篇笔记,是否开始导出:
        </div>
      </Modal>,
      <Modal show={showExportWait} title="导出" confirmText="好的,知道了" btnAlign="center" onConfirm={() => this.setState({ showExportWait: false })}>
        <div className="t-2 t-s-18">正在下载中,请不要关闭当前页面!</div>
      </Modal>,
      <Examination
        show={showExamination}
        data={info}
        onConfirm={() => this.setState({ showExamination: false })}
        onCancel={() => this.setState({ showExamination: false })}
        onClose={() => this.setState({ showExamination: false })}
      />,
      <RealAuth show={showReal} data={info} onConfirm={() => this.setState({ showReal: false })} />,
      <VipRenew
        show={showVip}
        data={info}
        onReal={() => this.setState({ showVip: false, showReal: true })}
        onPrepare={() => this.setState({ showVip: false, showExamination: true })}
        onClose={(result) => {
          if (result) {
            this.refresh();
          } else {
            this.setState({ showVip: false });
          }
        }}
      />,
    ];
  }
}

class NoteDetail extends Component {
  render() {
    const { show, data, onClose, onPrev, onNext } = this.props;
    return (
      <Modal
        className="note-detail-modal"
        body={false}
        show={show}
        width={720}
        maskClosable
        close={false}
        onClose={onClose}
        title={data.title}
        center
      >
        <Icon type="left" className="prev" onClick={() => onPrev && onPrev()} />
        <Icon type="right" className="next" onClick={() => onNext && onNext()} />
        <div className="t-2 t-s-18 detail" dangerouslySetInnerHTML={{ __html: data.content }} />
      </Modal>
    );
  }
}

class Note extends Component {
  onSelect() {
    const { data, onSelect, selectList } = this.props;
    const index = selectList.indexOf(data.key);
    if (index >= 0) {
      selectList.splice(index, 1);
    } else {
      selectList.push(data.key);
    }
    onSelect(selectList);
  }

  render() {
    const { data, selectList, onClick, courseNoMap = {} } = this.props;
    return (
      <div className="note-item p-t-2 b-b">
        <div className="t-1 t-s-14 f-w-b m-b-5">
          <CheckboxItem theme="white" checked={selectList.indexOf(data.key) >= 0} onClick={() => this.onSelect()} />
          <span className="t-2 m-l-5 m-r-5" onClick={() => onClick && onClick()}>课时{(courseNoMap[data.key] || {}).no}</span>
          <span onClick={() => onClick && onClick()}>{(courseNoMap[data.key] || {}).title}</span>
          <div className="f-r t-3 t-s-12 f-w-d">
            <span>{formatDate(data.updateTime, 'YYYY-MM-DD HH:mm:ss')}</span>
          </div>
        </div>
        <div className="t-2 m-b-2 detail" dangerouslySetInnerHTML={{ __html: data.content }} />
      </div>
    );
  }
}