import React from 'react';
import { Form, Input, InputNumber, Tabs, Switch, Checkbox, Row, Col, Button } from 'antd';
import './index.less';
import Page from '@src/containers/Page';
import Block from '@src/components/Block';
import Editor from '@src/components/Editor';
import Select from '@src/components/Select';
// import FileUpload from '@src/components/FileUpload';
import { formatFormError } from '@src/services/Tools';
import { asyncSMessage } from '@src/services/AsyncTools';
import { SentenceOption } from '../../../../Constant';
import { Preview } from '../../../stores/preview';
import { Exercise } from '../../../stores/exercise';
import { Sentence } from '../../../stores/sentence';
import config from './index';

export default class extends Page {
  constructor(props) {
    super(props);

    const { id } = this.params;

    if (id) {
      config.title = '编辑长难句题目';
    } else {
      config.title = '添加长难句题目';
    }
  }

  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) {
      handler = Preview.get({ id });
    } else {
      handler = Promise.resolve({ no: 1 });
    }
    handler
      .then(result => {
        form.setFieldsValue(result);
      });
  }

  submit() {
    const { form } = this.props;
    form.validateFields((err) => {
      if (!err) {
        const data = form.getFieldsValue();
        data.isTrail = data.isTrail ? 1 : 0;
        data.question.description = data.question.stem.replace(/<[^>]+>/g, '');
        let handler;
        if (data.id) {
          handler = Sentence.editQuestion(data);
        } else {
          handler = Sentence.addQuestion(data);
        }
        handler.then(() => {
          asyncSMessage('保存成功');
        }).catch((e) => {
          if (e.result) form.setFields(formatFormError(data, e.result));
        });
      }
    });
  }

  renderTitle() {
    const { getFieldDecorator } = this.props.form;
    return <Block>
      <Form>
        {getFieldDecorator('id')(<input hidden />)}
        <Form.Item labelCol={{ span: 5 }} wrapperCol={{ span: 16 }} label='题目序号'>
          {getFieldDecorator('no', {
            rules: [
              { required: true, message: '请输入序号' },
              // {
              //   validator: (rule, value, callback) => {
              //     if (this.partList.indexOf(value) >= 0) callback('该part已被使用');
              //     else callback();
              //     callback();
              //   },
              // },
            ],
          })(
            <InputNumber min={1} precision={0} formatter={(v) => parseInt(v, 10) || 1} />,
          )}
        </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('isTrail', {
            valuePropName: 'checked',
          })(
            <Switch checkedChildren='on' unCheckedChildren='off' />,
          )}
        </Form.Item>
      </Form>
    </Block>;
  }

  renderBase() {
    const { getFieldDecorator } = this.props.form;
    return <Block flex>
      <h1>题干信息</h1>
      <Form>
        {getFieldDecorator('question.id')(<input hidden />)}
        <Form.Item>
          {getFieldDecorator('question.stem', {
          })(
            <Editor placeholder='请输入内容' />,
          )}
        </Form.Item>
      </Form>
    </Block>;
  }

  renderAnswer() {
    const { getFieldDecorator } = this.props.form;
    return <Block flex>
      <h1>题目答案</h1>
      <table boarder cellSpacing className='answer'>
        <tr>
          <td>主语</td>
          <td>
            <Form.Item>
              {getFieldDecorator('question.answer.subject')(
                <Select mode='tags' maxTagCount={200} notFoundContent={null} tokenSeparators={[',', '，']} />,
              )}
            </Form.Item>
          </td>
        </tr>
        <tr>
          <td>谓语</td>
          <td><Form.Item>
            {getFieldDecorator('question.answer.predicate')(
              <Select mode='tags' maxTagCount={200} notFoundContent={null} tokenSeparators={[',', '，']} />,
            )}
          </Form.Item></td>
        </tr>
        <tr>
          <td>宾语</td>
          <td><Form.Item>
            {getFieldDecorator('question.answer.object')(
              <Select mode='tags' maxTagCount={200} notFoundContent={null} tokenSeparators={[',', '，']} />,
            )}
          </Form.Item></td>
        </tr>
      </table>
    </Block>;
  }

  renderOption() {
    const { getFieldDecorator } = this.props.form;
    return <Block flex>
      <h1>选项信息（长难句）</h1>
      <Form>
        <Form.Item>
          {getFieldDecorator('question.answer.options')(
            <Checkbox.Group options={SentenceOption} />,
          )}
        </Form.Item>
      </Form>
    </Block>;
  }

  renderQX() {
    const { getFieldDecorator } = this.props.form;
    return <Block flex>
      <Form>
        <Form.Item label='千行解析'>
          {getFieldDecorator('question.qxContent', {
          })(
            <Editor placeholder='输入内容' />,
          )}
        </Form.Item>
      </Form>
    </Block>;
  }

  renderChinese() {
    const { getFieldDecorator } = this.props.form;
    return <Block flex>
      <Form>
        <Form.Item label='中文解析'>
          {getFieldDecorator('chinese', {
          })(
            <Editor placeholder='输入内容' />,
          )}
        </Form.Item>
      </Form>
    </Block>;
  }

  renderTab() {
    return <Tabs activeKey='sentence' onChange={(tab) => {
      switch (tab) {
        case 'textbook':
          linkTo('/subject/textbook/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()}
      {this.renderTitle()}
      {this.renderBase()}
      {this.renderAnswer()}
      {this.renderOption()}
      {this.renderQX()}
      {this.renderChinese()}
      <Row type="flex" justify="center">
        <Col>
          <Button type="primary" onClick={() => {
            this.submit();
          }}>保存</Button>
        </Col>
      </Row>
    </div>;
  }
}
