import React from 'react';
import { Form, Button, Row, Col, List, Icon, Switch, Typography, Input } from 'antd';
import './index.less';
import Editor from '@src/components/Editor';
import Page from '@src/containers/Page';
import Block from '@src/components/Block';
import DragList from '@src/components/DragList';
// import FileUpload from '@src/components/FileUpload';
import { formatFormError, formatDate, getMap } from '@src/services/Tools';
import { asyncSMessage } from '@src/services/AsyncTools';
import { PcUrl, AskTarget, QuestionType, AskModule } from '../../../../Constant';
// import { User } from '../../../stores/user';
import { Question } from '../../../stores/question';

const QuestionTypeMap = getMap(QuestionType, 'value', 'label');
const AskTargetMap = getMap(AskTarget, 'value', 'label');
const AskModuleMap = getMap(AskModule, 'value', 'label');
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;
    let handler;
    if (id) {
      handler = Question.getAsk({ id });
    } else {
      handler = Promise.resolve({ others: [] });
    }
    handler
      .then(result => {
        result.ignoreStatus = result.answerStatus === 2;
        const { getFieldDecorator, setFieldsValue } = this.props.form;
        getFieldDecorator('id');
        getFieldDecorator('answer');
        getFieldDecorator('showStatus');
        setFieldsValue({ id: result.id, answer: result.answer, showStatus: result.showStatus });
        this.setState({ data: result });
      });
  }

  orderQuestion(oldIndex, newIndex) {
    const { data } = this.state;
    const { others = [] } = data;
    const tmp = others[oldIndex];
    others[oldIndex] = others[newIndex];
    others[newIndex] = tmp;
    this.setState({ others });
  }

  addOrder() {
    const { data } = this.state;
    const { others } = data;
    others.push(data);
    this.setState({ data });
  }

  removeOrder() {
    const { data } = this.state;
    const { others } = data;
    data.others = others.filter(row => row.id !== data.id);
    this.setState({ data });
  }

  submit() {
    const { form } = this.props;
    form.validateFields((err) => {
      if (!err) {
        const data = form.getFieldsValue();
        data.showStatus = data.showStatus ? 1 : 0;
        data.other = this.state.data.others.map(row => row.id);
        Question.editAsk(data).then(() => {
          asyncSMessage('保存成功');
        }).catch((e) => {
          if (e.result) form.setFields(formatFormError(data, e.result));
        });
      }
    });
  }

  ignore() {
    const { data } = this.state;
    Question.editAsk({ id: data.id, ignoreStatus: 1 }).then(() => {
      asyncSMessage('操作成功');
      goBack();
    });
  }

  renderBase() {
    const { data } = this.state;
    const { question = {}, questionNo = {} } = data;
    return <Block>
      <h1>题目信息</h1>
      <Form>
        <Form.Item labelCol={{ span: 5 }} wrapperCol={{ span: 16 }} label='板块'>
          {AskModuleMap[data.askModule]}
        </Form.Item>
        <Form.Item labelCol={{ span: 5 }} wrapperCol={{ span: 16 }} label='题型'>
          {QuestionTypeMap[question.questionType]}
        </Form.Item>
        <Form.Item labelCol={{ span: 5 }} wrapperCol={{ span: 16 }} label='题目id'>
          <a href='' target='_blank'>{questionNo.no}</a>
        </Form.Item>
      </Form>
    </Block>;
  }

  renderAsk() {
    const { getFieldDecorator, getFieldValue } = this.props.form;
    const { data, editContent } = this.state;
    const { user = {}, createTime, target, originContent, content } = data;
    return <Block>
      <h1>提问信息</h1>
      <Form>
        <Form.Item labelCol={{ span: 5 }} wrapperCol={{ span: 16 }} label='用户姓名'>
          {user.realName}
        </Form.Item>
        <Form.Item labelCol={{ span: 5 }} wrapperCol={{ span: 16 }} label='提问时间'>
          {formatDate(createTime)}
        </Form.Item>
        <Form.Item labelCol={{ span: 5 }} wrapperCol={{ span: 16 }} label='提问模块'>
          {AskTargetMap[target]}
        </Form.Item>
        <Form.Item labelCol={{ span: 5 }} wrapperCol={{ span: 16 }} label='提问内容'>
          {originContent}
        </Form.Item>
        <Form.Item labelCol={{ span: 5 }} wrapperCol={{ span: 16 }} label='提问详情'>
          {!editContent && content}
          {getFieldDecorator('content', {
          })(
            editContent ? <Input.TextArea placeholder='输入内容' /> : <input hidden />,
          )}
          <Switch checked={editContent} checkedChildren='编辑模式' unCheckedChildren='关闭' onChange={(value) => {
            data.content = getFieldValue('content');
            this.setState({ editContent: value, data });
          }} />
        </Form.Item>
      </Form>
    </Block>;
  }

  renderQuestionList() {
    return <Block>
      <h1>该题目的展示中问题</h1>
      <DragList
        loading={this.props.core.loading}
        dataSource={this.state.data.others || []}
        handle={'.icon'}
        onMove={(oldIndex, newIndex) => {
          this.orderQuestion(oldIndex, newIndex);
        }}
        renderItem={(item) => (
          <List.Item actions={[<Icon type='bars' className='icon' />, <Typography.Text copyable={{ text: `${PcUrl}/paper/question/${this.state.data.userQuestionId}?askId=${item.id}` }} />]}>
            <Row style={{ width: '100%' }}>
              <Col span={11}>问题:<span dangerouslySetInnerHTML={{ __html: item.content }} /></Col>
              <Col span={11} offset={1}>答复:<span dangerouslySetInnerHTML={{ __html: item.answer }} /></Col>
            </Row>
          </List.Item>
        )}
      /></Block>;
  }

  renderAnswer() {
    const { getFieldDecorator } = this.props.form;
    return <Block>
      <Form>
        {getFieldDecorator('id')(<input hidden />)}
        <Form.Item label='教师回复'>
          {getFieldDecorator('answer', {
          })(
            <Editor placeholder='输入内容' />,
          )}
        </Form.Item>
        <Row type="flex" justify="center">
          <Col span={12}>
            <Form.Item labelCol={{ span: 12 }} wrapperCol={{ span: 10 }} label='显示状态'>
              {getFieldDecorator('showStatus', {
                valuePropName: 'checked',
              })(
                <Switch onChange={(value) => {
                  if (value) {
                    this.addOrder();
                  } else {
                    this.removeOrder();
                  }
                }} checkedChildren='on' unCheckedChildren='off' />,
              )}
            </Form.Item>
          </Col>
        </Row>
      </Form>
    </Block>;
  }

  renderView() {
    return <div flex>
      {this.renderBase()}
      {this.renderAsk()}
      {this.renderQuestionList()}
      {this.renderAnswer()}

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