import React from 'react';
import { Form, Button, Row, Col, Upload } from 'antd';
import './index.less';
// import Editor from '@src/components/Editor';
import Page from '@src/containers/Page';
import Block from '@src/components/Block';
// import Radio from '@src/components/Radio';
// import TreeSelect from '@src/components/TreeSelect';
// import EditTableCell from '@src/components/EditTableCell';
import ActionLayout from '@src/layouts/ActionLayout';
import TableLayout from '@src/layouts/TableLayout';
import { formatDate } from '@src/services/Tools';
import { asyncSMessage, asyncForm, asyncDelConfirm } from '@src/services/AsyncTools';
// import { SwitchSelect, DataType } from '../../../../Constant';
// import { User } from '../../../stores/user';
// import { Exercise } from '../../../stores/exercise';
import { Course } from '../../../stores/course';
import { System } from '../../../stores/system';

export default class extends Page {
  initState() {
    return { history: false };
  }

  init() {
    this.exerciseMap = {};
    this.actionList = [{
      key: 'addHistory',
      type: 'primary',
      name: '新增版本',
    }];
    this.itemList = [{
      key: 'id',
      type: 'hidden',
    }, {
      key: 'time',
      type: 'date',
      name: '更新时间',
    }, {
      key: 'position',
      type: 'input',
      name: '更新位置',
    }, {
      key: 'originContent',
      type: 'input',
      name: '原内容',
    }, {
      key: 'content',
      type: 'input',
      name: '更改为',
    }, {
      key: 'version',
      type: 'input',
      name: '更新至',
    }];
    this.columns = [{
      title: '更新时间',
      dataIndex: 'time',
      render: (text) => {
        return formatDate(text);
      },
    }, {
      title: '版本名称',
      dataIndex: 'version',
    }, {
      title: '位置',
      dataIndex: 'position',
    }, {
      title: '原内容',
      dataIndex: 'originContent',
    }, {
      title: '更正为',
      dataIndex: 'content',
    }, {
      title: '更新至',
      dataIndex: 'version',
    }, {
      title: '操作',
      dataIndex: 'handler',
      render: (text, record) => {
        return <div className="table-button">
          {(
            <a onClick={() => {
              this.changeHistory(record);
            }}>编辑</a>
          )}
          {(
            <a onClick={() => {
              this.deleteHistory(record);
            }}>删除</a>
          )}
        </div>;
      },
    }];
  }

  initData() {
    const { id } = this.params;
    let handler;
    if (id) {
      handler = Course.getData({ id });
    } else {
      handler = Promise.resolve({ structId: 0 });
    }
    handler
      .then(result => {
        const { setFieldsValue } = this.props.form;
        setFieldsValue(result);
        this.setState({ data: result });
        this.refreshHistory();
      });
  }

  refreshHistory() {
    const { id } = this.params;
    Course.listDataHistory({ dataId: id }).then(result => {
      this.setState({ list: result.list, total: result.total, history: true });
    });
  }

  addHistory() {
    asyncForm('创建', this.itemList, {}, data => {
      return Course.addDataHistory(data).then(() => {
        asyncSMessage('添加成功!');
        this.refreshHistory();
      });
    });
  }

  changeHistory(record) {
    asyncForm('修改', this.itemList, record, data => {
      return Course.editDataHistory(data).then(() => {
        asyncSMessage('修改成功!');
        this.refreshHistory();
      });
    });
  }

  deleteHistory(record) {
    asyncDelConfirm('删除确认', '是否删除选中记录?', () => {
      return Course.delDataHistory(record).then(() => {
        asyncSMessage('删除成功!');
        this.refreshHistory();
      });
    });
  }

  renderFile() {
    const { getFieldDecorator, setFieldsValue, getFieldValue } = this.props.form;
    const resource = getFieldValue('resource');
    const trailResource = getFieldValue('trailResource');
    return <Block>
      <h1>资料文件</h1>
      <Form.Item labelCol={{ span: 5 }} wrapperCol={{ span: 16 }} label='正式版本'>
        {resource && <a href={resource} target="_blank">访问</a>}
        {getFieldDecorator('resource', {
          rules: [
            { required: true, message: '上传文件' },
          ],
        })(
          <Upload
            showUploadList={false}
            beforeUpload={(file) => System.uploadImage(file).then((result) => {
              setFieldsValue({ resource: result.url });
              return Promise.reject();
            })}
          >
            <Button>上传文件</Button>
          </Upload>,
        )}
      </Form.Item>
      <Form.Item labelCol={{ span: 5 }} wrapperCol={{ span: 16 }} label='试用版本'>
        {trailResource && <a href={trailResource} target="_blank">访问</a>}
        {getFieldDecorator('trailResource', {
          rules: [
            { required: true, message: '上传文件' },
          ],
        })(
          <Upload
            showUploadList={false}
            beforeUpload={(file) => System.uploadImage(file).then((result) => {
              setFieldsValue({ trailResource: result.url });
              return Promise.reject();
            })}
          >
            <Button>上传文件</Button>
          </Upload>,
        )}
      </Form.Item>
    </Block>;
  }

  renderHistory() {
    return <Block>
      <h1>资料版本</h1>
      <ActionLayout
        itemList={this.actionList}
        selectedKeys={this.state.selectedKeys}
        onAction={key => this.onAction(key)}
      />
      <TableLayout
        columns={this.tableSort(this.columns)}
        list={this.state.list}
        pagination={false}
        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() {
    const { history } = this.state;
    return <div flex>
      {this.renderBase()}
      {this.renderFile()}
      {history && this.renderHistory()}

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