import React from 'react';
import { Button, Tabs, Row, Col, Form, Input } from 'antd';
import './index.less';
import Page from '@src/containers/Page';
import Block from '@src/components/Block';
import ActionLayout from '@src/layouts/ActionLayout';
import TableLayout from '@src/layouts/TableLayout';
import { formatFormError, formatDate } from '@src/services/Tools';
import { asyncSMessage, asyncForm } from '@src/services/AsyncTools';
import { System } from '../../../stores/system';

export default class extends Page {
  init() {
    this.itemList = [{
      key: 'id',
      type: 'hidden',
    }, {
      key: 'title',
      type: 'input',
      name: '标题',
    }, {
      key: 'content',
      type: 'textarea',
      name: '内容',
    }, {
      key: 'link',
      type: 'input',
      name: '链接地址',
    }, {
      key: 'sendTime',
      type: 'date',
      name: '发送时间',
    }];

    this.columns = [{
      title: '消息标题',
      dataIndex: 'title',
    }, {
      title: '消息内容',
      dataIndex: 'content',
    }, {
      title: '发送时间',
      dataIndex: 'sendTime',
      render: (text) => {
        return formatDate(text);
      },
    }, {
      title: '操作',
      dataIndex: 'handler',
      render: (text, record) => {
        return <div className="table-button">
          {(
            <a onClick={() => {
              this.editAction(record);
            }}>编辑</a>
          )}
        </div>;
      },
    }];

    this.actionList = [{
      key: 'add',
      name: '增加',
    }];

    this.state.tab = 'template';
  }

  initData() {
    this.refresh(this.state.tab);
  }

  refresh(tab) {
    if (tab === 'template') {
      return this.refreshTemplate();
    }
    if (tab === 'custom') {
      return this.refreshCustom();
    }
    return Promise.reject();
  }

  refreshTemplate() {
    return System.getMessageTemplate().then(result => {
      this.setState({ template: result || {} });
    });
  }

  refreshCustom() {
    return System.listMessage().then((result) => {
      this.setState({ list: result.list, total: result.total });
    });
  }

  submit(tab) {
    let handler;
    if (tab === 'template') {
      handler = this.submitTemplate();
    }
    handler.then(() => {
      asyncSMessage('保存成功');
    });
  }

  submitTemplate() {
    const { form } = this.props;
    form.validateFields((err) => {
      if (!err) {
        const data = form.getFieldsValue();
        System.setMessageTemplate(data)
          .then(() => {
            this.setState(data);
            asyncSMessage('保存成功');
          }).catch((e) => {
            form.setFields(formatFormError(data, e.result));
          });
      }
    });
  }

  submitCustom() {
    const { exercise } = this.state;
    return System.setExerciseTime(exercise);
  }

  addAction() {
    asyncForm('创建消息', this.itemList, {}, data => {
      return System.addMessage(data).then(() => {
        asyncSMessage('添加成功!');
        this.refresh('custom');
      });
    });
  }

  editAction(row) {
    asyncForm('编辑消息', this.itemList, row, data => {
      return System.editMessage(data).then(() => {
        asyncSMessage('编辑成功!');
        this.refresh('custom');
      });
    });
  }

  renderTemplate() {
    const { getFieldDecorator } = this.props.form;
    return <div>
      <Block>
        <h1>购买消息</h1>
        <Form>
          <Form.Item help='可插入自定义字段' />
          <Form.Item>
            {getFieldDecorator('pay.content', {
              rules: [
                { required: false, message: '请输入购买消息内容' },
              ],
            })(
              <Input.TextArea />,
            )}
          </Form.Item>
          <Form.Item label='链接地址'>
            {getFieldDecorator('pay.link')(
              <Input placeholder='请输入跳转地址' />,
            )}
          </Form.Item>
        </Form>
      </Block>
      <Block>
        <h1>换库消息</h1>
        <Form>
          <Form.Item help='可插入自定义字段' />
          <Form.Item>
            {getFieldDecorator('library.content', {
              rules: [
                { required: false, message: '请输入换库消息内容' },
              ],
            })(
              <Input.TextArea />,
            )}
          </Form.Item>
          <Form.Item label='链接地址'>
            {getFieldDecorator('library.link')(
              <Input placeholder='请输入跳转地址' />,
            )}
          </Form.Item>
        </Form>
      </Block>
      <Block>
        <h1>课程消息</h1>
        <Form>
          <Form.Item help='可插入自定义字段' />
          <Form.Item>
            {getFieldDecorator('course.content', {
              rules: [
                { required: false, message: '请输入课程消息内容' },
              ],
            })(
              <Input.TextArea />,
            )}
          </Form.Item>
          <Form.Item label='链接地址'>
            {getFieldDecorator('course.link')(
              <Input placeholder='请输入跳转地址' />,
            )}
          </Form.Item>
        </Form>
      </Block>
    </div>;
  }

  renderCustom() {
    return <Block flex>
      <ActionLayout
        itemList={this.actionList}
        selectedKeys={this.state.selectedKeys}
        onAction={key => this.onAction(key)}
      />
      <TableLayout
        columns={this.columns}
        list={this.state.list}
        pagination={false}
        loading={this.props.core.loading}
      />
    </Block>;
  }

  renderView() {
    const { tab } = this.state;
    return <div>
      <Tabs activeKey={tab} onChange={(value) => {
        this.setState({ tab: value, selectedKeys: [], checkedKeys: [] });
        this.refresh(value);
      }}>
        <Tabs.TabPane tab="模版消息" key="template">
          {this.renderTemplate()}
        </Tabs.TabPane>
        <Tabs.TabPane tab="自定义消息" key="custom">
          {this.renderCustom()}
        </Tabs.TabPane>
      </Tabs>
      {tab !== 'custom' && <Row type="flex" justify="center">
        <Col>
          <Button type="primary" onClick={() => {
            this.submit(tab);
          }}>保存</Button>
        </Col>
      </Row>}

    </div>;
  }
}