import React from 'react';
import moment from 'moment';
import { DatePicker, Checkbox, Modal, Form, Input, Row, Col, Button, Upload } from 'antd';
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 { formatDate } from '@src/services/Tools';
import { asyncSMessage, asyncForm } from '@src/services/AsyncTools';
import { UserUrl } from '../../../../Constant';
import { Course } from '../../../stores/course';
import { User } from '../../../stores/user';
import { System } from '../../../stores/system';


export default class extends Page {
  init() {
    this.videoColumns = [{
      title: '时间段',
      dataIndex: 'time',
      render: (text) => {
        return `${formatDate(text.startTime, 'YYYY-MM-DD')}~${formatDate(text.endTime, 'YYYY-MM-DD')}`;
      },
    }, {
      title: '学员id',
      dataIndex: 'userId',
    }, {
      title: '学员名称',
      dataIndex: 'user.nickname',
    }, {
      title: '手机号',
      dataIndex: 'user.mobile',
    }, {
      title: '操作',
      dataIndex: 'handler',
      render: (text, record) => {
        return <div className="table-button">
          {<a onClick={() => {
            this.deleteOnlineStudent(record);
          }}>删除</a>}
        </div>;
      },
    }];

    this.vsAction = [{
      key: 'addAppointment',
      name: '添加预约',
    }];
    this.vsList = [{
      key: 'id',
      type: 'hidden',
    }, {
      key: 'title',
      type: 'input',
      name: '课程名称',
    }, {
      key: 'timerange',
      type: 'daterange',
      showTime: true,
      name: '上课时间',
    }, {
      key: 'channel',
      type: 'input',
      name: '频道号',
    }];
    this.vsColumns = [{
      title: '课时序号',
      dataIndex: 'no',
      render: (text) => {
        const { data } = this.state;
        return `${text}/${data.vsNumber}`;
      },
    }, {
      title: '上课时间',
      dataIndex: 'time',
      render: (text, record) => {
        return <DatePicker.RangePicker showTime value={[record.startTime, record.endTime]} onChange={(value) => {
          this.changeAppointment(record.id, { startTime: value[0], endTime: value[1] });
        }} />;
      },
    }, {
      title: '课程名称',
      dataIndex: 'title',
    }, {
      title: '频道号',
      dataIndex: 'channel',
    }, {
      title: '学习进度',
      dataIndex: 'isFinish',
      render: (text, record) => {
        return <Checkbox checked={text > 0} onChange={(e) => {
          this.changeAppointment(record.id, { isFinish: e.target.value ? 1 : 0 });
        }} />;
      },
    }, {
      title: '预习作业',
      dataIndex: 'userPaper',
      render: (text, record) => {
        return text ? <a onClick={() => {
          User.locationUser(record.userId, `${UserUrl}/paper/report/${record.reportId}`);
        }}>查看{text.times > 0 ? '(已完成)' : ''}</a> : '';
      },
    }, {
      title: '笔记批阅',
      dataIndex: 'noteList',
      render: (text, record) => {
        return <a onClick={() => {
          this.noteAction(record);
        }}>查看</a>;
      },
    }, {
      title: '课后补充',
      dataIndex: 'supplyList',
      render: (text, record) => {
        return <a onClick={() => {
          this.supplyAction(record);
        }}>查看</a>;
      },
    }];
  }

  initData() {
    const { id } = this.params;
    let handler;
    if (id) {
      handler = Course.listStudy({ ids: [id] });
    }

    handler
      .then(result => {
        const [row] = result.list;
        if (!row) {
          asyncSMessage('记录不存在');
          return;
        }
        const { course } = row;
        this.setState({ module: course.courseModule });
        this.setState({ data: row });
        this.refresh();
      });
  }

  refresh() {
    // const { id } = this.params;
    const { module } = this.state;
    switch (module) {
      case 'video':
        this.refreshVideo();
        break;
      case 'online':
        break;
      case 'vs':
        this.refreshVs();
        break;
      default:
    }
  }

  refreshVideo() {
    // const { id } = this.params;
    // Course.listStudentOnline(Object.assign({ courseId: id }, this.state.search)).then(result => {
    //   this.setTableData(result.list, result.total);
    // });
  }

  refreshVs() {
    const { id } = this.params;
    User.listCourseAppointment(Object.assign({ courseId: id }, this.state.search)).then(result => {
      result.list = result.list.map(row => {
        row.startTime = moment(row.startTime);
        row.endTime = moment(row.endTime);
        return row;
      });
      this.setTableData(result.list, result.total);
    });
  }

  changeAppointment(id, data) {
    data.id = id;
    return User.editCourseAppointment(data).then(() => {
      this.refreshVs();
      this.cleanInfo();
    });
  }

  addAppointmentAction() {
    const { id } = this.params;
    asyncForm('添加', this.vsList, {}, info => {
      const { data } = this.state;
      ([info.startTime, info.endTime] = info.timerange);
      return User.addCourseAppointment(Object.assign({ recordId: id, userId: data.userId, courseId: data.courseId, noteList: [], supplyList: [] }, info)).then(() => {
        asyncSMessage('添加成功!');
        this.refreshVs();
      });
    }).catch(err => {
      console.log(err);
    });
  }

  noteAction(record) {
    this.open(record, 'note');
  }

  supplyAction(record) {
    this.open(record, 'supply');
  }

  deleteAppointment(row) {
    User.delCourseAppointment({ id: row.id }).then(() => {
      asyncSMessage('删除成功!');
      this.refresh();
    });
  }

  changeInfo(key, data) {
    const info = this.state[key] || {};
    this.setState({ [key]: Object.assign(info, data) });
  }

  cleanInfo() {
    this.setState({ supplyInfo: null, noteInfo: null });
  }

  renderVs() {
    const { data, page } = this.state;
    return <Block flex>
      {data.vsNumber > page.total && <ActionLayout
        itemList={this.vsAction}
        selectedKeys={this.state.selectedKeys}
        onAction={key => this.onAction(key)}
      />}
      <TableLayout
        columns={this.vsColumns}
        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}
      />
      {this.state.note && <Modal visible closable title='课后笔记' footer={null} onCancel={() => {
        this.cleanInfo();
        this.close(false, 'note');
      }}>
        {(this.state.note.noteList || []).map(row => {
          return <p>{formatDate(row.time)}: {<a href={row.url} target='_blank'>{row.name}</a>}</p>;
        })}
        <Form>
          <Row>
            <Col span={1}><Upload
              showUploadList={false}
              beforeUpload={(file) => System.uploadImage(file).then((result) => {
                this.changeInfo('noteInfo', { url: result.url, name: file.name, time: new Date() });
                return Promise.reject();
              })}
            >
              <Button>上传文档{(this.state.noteInfo || {}).url ? '(已上传)' : ''}</Button>
            </Upload></Col>
            <Col span={1} offset={20}><Button type='primary' onClick={() => {
              if (!this.state.noteInfo || !this.state.noteInfo.url) return;
              let { noteList = [] } = this.state.note;
              noteList = noteList || [];
              noteList.push(this.state.noteInfo);
              this.changeAppointment(this.state.note.id, { noteList });
            }}>发布</Button></Col>
          </Row>
        </Form>
      </Modal>}
      {this.state.supply && <Modal visible closable title='课后补充' footer={null} onCancel={() => {
        this.cleanInfo();
        this.close(false, 'supply');
      }}>
        {(this.state.supply.supplyList || []).map(row => {
          return [<p>{formatDate(row.time)}:{<a href={row.url} target='_blank'>{row.name}</a>}</p>, <p>留言 - {row.content}</p>];
        })}
        <Form>
          <Row>
            <Col span={12}>
              <Input value={(this.state.supplyInfo || {}).content || ''} onChange={value => {
                this.changeInfo('supplyInfo', { content: value });
              }} />
            </Col>
            <Col span={1}><Upload
              showUploadList={false}
              beforeUpload={(file) => System.uploadImage(file).then((result) => {
                this.changeInfo('supplyInfo', { url: result.url, name: file.name, time: new Date() });
                return Promise.reject();
              })}
            >
              <Button>上传文档{(this.state.supplyInfo || {}).url ? '(已上传)' : ''}</Button>
            </Upload></Col>
            <Col span={1} offset={8}><Button type='primary' onClick={() => {
              if (!this.state.supplyInfo || !this.state.supplyInfo.url) return;
              let { supplyList = [] } = this.state.supply;
              supplyList = supplyList || [];
              supplyList.push(this.state.supplyInfo);
              this.changeAppointment(this.state.supply.id, { supplyList });
            }}>发布</Button></Col>
          </Row>
        </Form>
      </Modal>}
    </Block>;
  }

  renderVideo() {
    return <Block flex>
      <TableLayout
        columns={this.videoColumns}
        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>;
  }

  renderView() {
    switch (this.state.module) {
      case 'online':
        return [];
      case 'vs':
        return [this.renderVs()];
      case 'video':
        return [this.renderVideo()];
      default:
        return <div />;
    }
  }
}