import React from 'react';
import { Link } from 'react-router-dom';
import './index.less';
import Page from '@src/containers/Page';
import Block from '@src/components/Block';
import FilterLayout from '@src/layouts/FilterLayout';
// import ActionLayout from '@src/layouts/ActionLayout';
import TableLayout from '@src/layouts/TableLayout';
import { getMap, formatTreeData, formatDate, bindSearch } from '@src/services/Tools';
import { asyncSMessage } from '@src/services/AsyncTools';
import { CourseModule, CourseStatus } from '../../../../Constant';
import { Course } from '../../../stores/course';
import { Exercise } from '../../../stores/exercise';
import { User } from '../../../stores/user';

const CourseModuleMap = getMap(CourseModule, 'value', 'label');
const CourseStatusMap = getMap(CourseStatus, 'value', 'label');

export default class extends Page {
  constructor(props) {
    super(props);
    this.exerciseMap = {};

    this.filterForm = [{
      key: 'courseModule',
      type: 'select',
      name: '类型',
      allowClear: true,
      select: CourseModule,
    }, {
      key: 'structId',
      type: 'tree',
      allowClear: true,
      name: '学科',
      select: [],
      placeholder: '请选择',
      number: true,
    }, {
      key: 'courseId',
      type: 'select',
      name: '课程名称',
      allowClear: true,
      select: [],
      number: true,
    }, {
      key: 'userId',
      type: 'select',
      name: '学生',
      allowClear: true,
      select: [],
      number: true,
    }, {
      key: 'teacher',
      type: 'input',
      name: '老师',
    }];

    this.columns = [{
      title: '学生id',
      dataIndex: 'userId',
      render: (text, record) => {
        return `${text}/${record.user ? record.user.nickname : ''}`;
      },
    }, {
      title: '课程类型',
      dataIndex: 'course.courseModule',
      render: (text) => {
        return CourseModuleMap[text] || text;
      },
    }, {
      title: '课程名称',
      dataIndex: 'course.title',
    }, {
      title: '授课老师',
      dataIndex: 'teacher',
      render: (text, record) => {
        return text || record.course.teacher;
      },
    }, {
      title: '有效期',
      dataIndex: 'time',
      render: (text, record) => {
        return record.isUsed ? `${formatDate(record.useStartTime, 'YYYY-MM-DD')}~${formatDate(record.useEndTime, 'YYYY-MM-DD')}` : '';
      },
    }, {
      title: '上次学习时间',
      dataIndex: 'lastTime',
      render: (text) => {
        return text ? `${formatDate(text, 'YYYY-MM-DD HH:mm:ss')}` : '';
      },
    }, {
      title: '状态',
      dataIndex: 'status',
      render: (text, record) => {
        let status = 0;
        if (record.isUsed) {
          const end = new Date(record.useEndTime);
          status = 1;
          if (new Date().getTime() > end.getTime()) {
            status = 2;
          }
        }
        return CourseStatusMap[status] || status;
      },
    }, {
      title: '操作',
      dataIndex: 'handler',
      render: (text, record) => {
        return <div className="table-button">
          {<Link to={`/course/study/detail/${record.id}`}>查看</Link>}
          {record.isUsed > 0 && !record.isStop && (
            <a onClick={() => {
              this.stopAction(record.id);
            }}>停用</a>
          )}
        </div>;
      },
    }];

    Exercise.courseStruct().then((result) => {
      const list = result.map(row => { row.title = `${row.titleZh}`; row.value = row.id; return row; });
      this.filterForm[1].tree = formatTreeData(list, 'id', 'title', 'parentId');
      this.exerciseMap = getMap(result.map(row => {
        row.title = `${row.titleZh}`;
        row.value = row.id;
        return row;
      }), 'id', 'title');

      this.setState({ exercise: result });
    });

    bindSearch(this.filterForm, 'userId', this, (search) => {
      return User.list(search);
    }, (row) => {
      return {
        title: `${row.nickname}(${row.mobile})`,
        value: row.id,
      };
    }, this.state.search.userId ? Number(this.state.search.userId) : null, null);
    bindSearch(this.filterForm, 'courseId', this, (search) => {
      return Course.list(search);
    }, (row) => {
      return {
        title: row.title,
        value: row.id,
      };
    }, this.state.search.courseId ? Number(this.state.search.courseId) : null, null);
  }

  init() {
    Course.list().then((result) => {
      this.filterForm[2].select = result.list.map(row => {
        row.value = row.id;
        return row;
      });
    });
  }

  initData() {
    Course.listStudy(this.state.search).then(result => {
      this.setTableData(result.list, result.total);
    });
  }

  stopAction(id) {
    return Course.editStudy({ id, isStop: 1 }).then(() => {
      asyncSMessage('停用成功!');
      this.refresh();
    });
  }

  renderView() {
    const { exercise } = this.state;
    return <Block flex>
      {exercise && <FilterLayout
        show
        itemList={this.filterForm}
        data={this.state.search}
        onChange={data => {
          data.page = 1;
          this.search(data);
        }} />}
      <TableLayout
        columns={this.tableSort(this.columns)}
        list={this.state.list}
        pagination={this.state.page}
        loading={this.props.core.loading}
        onChange={(pagination, filters, sorter) => this.tableChange(pagination, filters, sorter)}
        onSelect={(keys, rows) => this.tableSelect(keys, rows)}
        selectedKeys={this.state.selectedKeys}
      />
    </Block>;
  }
}