import React from 'react';
import { Form, Input, Button, Row, Col, InputNumber, Switch } from 'antd';
import './index.less';
import Editor from '@src/components/Editor';
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, getMap } from '@src/services/Tools';
import { asyncSMessage } from '@src/services/AsyncTools';
import { Sentence } from '../../../stores/sentence';
import config from './index';

export default class extends Page {
  constructor(props) {
    super(props);
    this.structMap = {};
    this.partList = [];

    const { id } = this.params;

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

  init() {
    Sentence.getStruct().then(result => {
      return this.refreshStruct(result);
    });
  }

  refreshStruct(result) {
    result = result || {};
    result.chapters = result.chapters || [];
    const chapters = result.chapters.map((row, index) => { row.value = index + 1; return row; }).filter(row => !row.exercise);
    this.structMap = getMap(chapters, 'value');
    this.setState({ struct: result, chapters });
  }

  refreshPart(chapter) {
    const { form } = this.props;
    const { id } = this.params;
    Sentence.listArticle({ chapter }).then(result => {
      this.partList = result.list.map(row => row.part);
      if (id) {
        this.partList = this.partList.filter(row => row !== this.data.part);
      }
      form.validateFields(['part'], { force: true });
    });
  }

  initData() {
    const { id } = this.params;
    const { form } = this.props;
    let handler;
    if (id) {
      handler = Sentence.getArticle({ id }).then((result) => {
        this.refreshPart(result.chapter);
        return result;
      });
    } else {
      handler = Promise.resolve({ part: 1 });
    }
    handler
      .then(result => {
        this.data = result;
        form.setFieldsValue(result);
      });
  }

  submit() {
    const { form } = this.props;
    form.validateFields((err) => {
      if (!err) {
        const data = form.getFieldsValue();
        data.isTrail = data.isTrail ? 1 : 0;
        let handler;
        if (data.id) {
          handler = Sentence.editArticle(data);
        } else {
          handler = Sentence.addArticle(data);
        }
        handler.then(() => {
          asyncSMessage('保存成功');
          goBack();
        }).catch((e) => {
          if (e.result) form.setFields(formatFormError(data, e.result));
        });
      }
    });
  }

  renderBase() {
    const { getFieldDecorator } = this.props.form;
    return <Block>
      <Form>
        {getFieldDecorator('id')(<input hidden />)}
        <Form.Item labelCol={{ span: 5 }} wrapperCol={{ span: 16 }} label='Chapter'>
          {getFieldDecorator('chapter', {
            rules: [
              { required: true, message: '请选择章节' },
            ],
          })(
            <Select select={this.state.chapters} placeholder='请选择章节' onChange={(v) => {
              this.refreshPart(v);
            }} />,
          )}
        </Form.Item>
        <Form.Item labelCol={{ span: 5 }} wrapperCol={{ span: 16 }} label='Part'>
          {getFieldDecorator('part', {
            rules: [
              { required: true, message: '请输入Part' },
              {
                validator: (rule, value, callback) => {
                  if (this.partList.indexOf(value) >= 0) callback('该part已被使用');
                  else 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>;
  }

  renderContent() {
    const { getFieldDecorator } = this.props.form;
    return <Block flex>
      <Form>
        <Form.Item label='文章录入'>
          {getFieldDecorator('content', {
          })(
            <Editor placeholder='输入内容' />,
          )}
        </Form.Item>
      </Form>
    </Block>;
  }

  renderView() {
    return <div flex>
      {this.renderBase()}
      {this.renderContent()}
      <Row type="flex" justify="center">
        <Col>
          <Button type="primary" onClick={() => {
            this.submit();
          }}>保存</Button>
        </Col>
      </Row>
    </div>;
  }
}
