import React from 'react';
import { Form, Input, Tabs, DatePicker } from 'antd';
import './index.less';
import Page from '@src/containers/Page';
import Block from '@src/components/Block';
import Select from '@src/components/Select';
// import FileUpload from '@src/components/FileUpload';
import { formatFormError, generateSearch } from '@src/services/Tools';
import { asyncSMessage } from '@src/services/AsyncTools';
import { Preview } from '../../../stores/preview';
import { Exercise } from '../../../stores/exercise';
import { User } from '../../../stores/user';
import config from './index';

export default class extends Page {
  init() {
    Exercise.allStruct().then(result => {
      result = result.filter(row => row.level === 2).map(row => { row.title = `${row.titleZh}/${row.titleEn}`; row.value = row.id; return row; });
      this.setState({ exercise: result });
    });
  }

  initData() {
    const { id } = this.params;
    const { form } = this.props;
    let handler;
    if (id) {
      config.title = '编辑预习作业';
      handler = Preview.get({ id });
    } else {
      config.title = '添加预习作业';
      handler = Promise.resolve({});
    }
    handler
      .then(result => {
        form.setFieldsValue(result);
        generateSearch('userIds', { mode: 'multiple' }, this, (search) => {
          return User.list(search);
        }, (row) => {
          return {
            title: `${row.nickname}(${row.mobile})`,
            value: row.id,
          };
        }, result.userIds || [], null);
      });
  }

  submit() {
    const { form } = this.props;
    form.validateFields((err) => {
      if (!err) {
        const data = form.getFieldsValue();
        let handler;
        if (data.id) {
          handler = Preview.edit(data);
        } else {
          handler = Preview.add(data);
        }
        handler.then(() => {
          asyncSMessage('保存成功');
        }).catch((e) => {
          if (e.result) form.setFields(formatFormError(data, e.result));
        });
      }
    });
  }

  searchQuestion(values) {
    console.log(values);
  }

  renderBase() {
    const { getFieldDecorator } = this.props.form;
    return <Block>
      <Form>
        {getFieldDecorator('id')(<input hidden />)}
        <Form.Item labelCol={{ span: 5 }} wrapperCol={{ span: 16 }} label='选择课程'>
          {getFieldDecorator('category', {
            rules: [
              { required: true, message: '请选择课程' },
            ],
          })(
            <Select select={this.state.exercise} placeholder='请选择课程' />,
          )}
        </Form.Item>
        <Form.Item labelCol={{ span: 5 }} wrapperCol={{ span: 16 }} label='起止时间'>
          {getFieldDecorator('time', {
            rules: [
              { required: true, message: '请输入起止时间' },
            ],
          })(
            <DatePicker.RangePicker />,
          )}
        </Form.Item>
        <Form.Item labelCol={{ span: 5 }} wrapperCol={{ span: 16 }} label='作业标题'>
          {getFieldDecorator('title', {
            rules: [
              { required: true, message: '请输入作业标题' },
            ],
          })(
            <Input placeholder='请输入作业标题' />,
          )}
        </Form.Item>
        <Form.Item labelCol={{ span: 5 }} wrapperCol={{ span: 16 }} label='指定做题人'>
          {getFieldDecorator('userIds', {
            rules: [
              { required: true, message: '请指定做题人' },
            ],
          })(
            <Select {...this.state.userIds} placeholder='请指定做题人' />,
          )}
        </Form.Item>
        <Form.Item labelCol={{ span: 5 }} wrapperCol={{ span: 16 }} label='选择作业题'>
          {getFieldDecorator('questionIds', {
            rules: [
              { required: true, message: '请选择作业题' },
            ],
          })(
            <Select select={[]} mode='tags' maxTagCount={200} notFoundContent={null} placeholder='输入题目id, 逗号分隔' tokenSeparators={[',', '，']} onSelect={(values) => {
              this.searchQuestion(values);
            }} />,
          )}
        </Form.Item>
      </Form>
    </Block>;
  }

  renderTab() {
    return <Tabs activeKey='textbook' onChange={(tab) => {
      switch (tab) {
        case 'sentence':
          linkTo('/subject/sentence/question');
          break;
        case 'base':
          linkTo('/subject/question');
          break;
        default:
      }
    }}>
      <Tabs.TabPane key='base' tab='考试题型' />
      <Tabs.TabPane key='sentence' tab='长难句' />
      <Tabs.TabPane key='textbook' tab='数学机经' />
    </Tabs>;
  }

  renderView() {
    return <div flex >
      {this.renderTab()}
    </div>;
  }
}
