import React from 'react';
import { Form, Input, InputNumber, Card, Icon, Button, Row, Col, Upload, Affix } from 'antd';
import './index.less';
import Page from '@src/containers/Page';
import Block from '@src/components/Block';
// import FileUpload from '@src/components/FileUpload';
import { flattenObject, formatFormError } from '@src/services/Tools';
import { asyncSMessage } from '@src/services/AsyncTools';
import { System } from '../../../stores/system';

export default class extends Page {
  initData() {
    System.getIndex().then(result => {
      const { form } = this.props;
      form.setFieldsValue(flattenObject(result));
      this.setState({ load: true, data: result });
    });
  }

  addLength(field, info) {
    let { data } = this.state;
    data = data || {};
    data[field] = data[field] || [];
    data[field].push(info);
    this.setState({ data });
  }

  deleteLength(field, start, length) {
    let { data } = this.state;
    data = data || {};
    data[field] = data[field] || [];
    data[field].splite(start, length);
    this.setState({ data });
  }

  submit() {
    const { form } = this.props;
    form.validateFields((err) => {
      if (!err) {
        const data = form.getFieldsValue();
        data.class = Object.keys(data.class).map((key) => data.class[key]);
        data.activity = Object.keys(data.activity).map((key) => data.activity[key]);
        data.evaluation = Object.keys(data.evaluation).map((key) => data.evaluation[key]);
        System.setIndex(data)
          .then(() => {
            this.setState(data);
            asyncSMessage('保存成功');
          }).catch((e) => {
            form.setFields(formatFormError(data, e.result));
          });
      }
    });
  }

  renderPrepare() {
    const { getFieldDecorator } = this.props.form;
    return <Block>
      <h1>备考攻略</h1>
      <Form>
        <Form.Item labelCol={{ span: 5 }} wrapperCol={{ span: 16 }} label='自学-从零开始'>
          {getFieldDecorator('prepare.first', {
            rules: [
              { required: false, message: '请输入跳转地址' },
            ],
          })(
            <Input placeholder='请输入跳转地址' />,
          )}
        </Form.Item>
        <Form.Item labelCol={{ span: 5 }} wrapperCol={{ span: 16 }} label='自学-继续练习'>
          {getFieldDecorator('prepare.continue', {
            rules: [
              { required: false, message: '请输入跳转地址' },
            ],
          })(
            <Input placeholder='请输入跳转地址' />,
          )}
        </Form.Item>
        <Form.Item labelCol={{ span: 5 }} wrapperCol={{ span: 16 }} label='课程-初学'>
          {getFieldDecorator('prepare.classJunior', {
            rules: [
              { required: false, message: '请输入跳转地址' },
            ],
          })(
            <Input placeholder='请输入跳转地址' />,
          )}
        </Form.Item>
        <Form.Item labelCol={{ span: 5 }} wrapperCol={{ span: 16 }} label='课程-中级'>
          {getFieldDecorator('prepare.classMiddle', {
            rules: [
              { required: false, message: '请输入跳转地址' },
            ],
          })(
            <Input placeholder='请输入跳转地址' />,
          )}
        </Form.Item>
        <Form.Item labelCol={{ span: 5 }} wrapperCol={{ span: 16 }} label='课程-高级'>
          {getFieldDecorator('prepare.classSenior', {
            rules: [
              { required: false, message: '请输入跳转地址' },
            ],
          })(
            <Input placeholder='请输入跳转地址' />,
          )}
        </Form.Item>
      </Form>
    </Block>;
  }

  renderUser() {
    const { getFieldDecorator } = this.props.form;
    return <Block>
      <h1>用户数据</h1>
      <Form>
        <Form.Item labelCol={{ span: 5 }} wrapperCol={{ span: 16 }} label='线下用户量'>
          {getFieldDecorator('user.numberOffline', {
            rules: [
              { required: false, message: '' },
            ],
          })(
            <InputNumber placeholder='请输入线下用户量' style={{ width: '200px' }} />,
          )}
        </Form.Item>

        <Form.Item labelCol={{ span: 5 }} wrapperCol={{ span: 16 }} label='700+学员数'>
          {getFieldDecorator('user.number700', {
            rules: [
              { required: false, message: '' },
            ],
          })(
            <InputNumber placeholder='请输入700+学员数' style={{ width: '200px' }} />,
          )}
        </Form.Item>

        <Form.Item labelCol={{ span: 5 }} wrapperCol={{ span: 16 }} label='学员平均分'>
          {getFieldDecorator('user.numberScore', {
            rules: [
              { required: false, message: '' },
            ],
          })(
            <InputNumber placeholder='请输入学员平均分' style={{ width: '200px' }} />,
          )}
        </Form.Item>
      </Form>
    </Block>;
  }

  renderClass() {
    const { getFieldDecorator, getFieldValue, setFieldsValue } = this.props.form;
    const { data } = this.state;
    const classes = data.class || [];
    return <Block>
      <h1>千行课堂</h1>
      <Form>
        <Row>
          {classes.map((row, index) => {
            const image = getFieldValue(`class.${index}.image`) || null;
            return <Col span={7} offset={index % 3 ? 1 : 0}><Card>
              <Button className="delete-button" size="small" onClick={() => {
                this.deleteLength('class', index, 1);
              }}>
                <Icon type="delete" />
              </Button>
              <Form.Item labelCol={{ span: 7 }} wrapperCol={{ span: 15 }} label='课程名称'>
                {getFieldDecorator(`class.${index}.title`, {
                  rules: [
                    { required: true, message: '输入课程名称' },
                  ],
                  initialValue: row.title,
                })(
                  <Input placeholder='请输入课程名称' />,
                )}
              </Form.Item>
              <Form.Item labelCol={{ span: 7 }} wrapperCol={{ span: 15 }} label='跳转链接'>
                {getFieldDecorator(`class.${index}.link`, {
                  rules: [
                    { required: true, message: '输入跳转链接' },
                  ],
                  initialValue: row.link,
                })(
                  <Input placeholder='请输入跳转链接' />,
                )}
              </Form.Item>
              <Form.Item labelCol={{ span: 7 }} wrapperCol={{ span: 15 }} label='背景图片'>
                {getFieldDecorator(`class.${index}.image`, {
                  rules: [
                    { required: true, message: '上传图片' },
                  ],
                })(
                  <Upload
                    listType="picture-card"
                    showUploadList={false}
                    beforeUpload={(file) => System.uploadImage(file).then((result) => {
                      setFieldsValue({ [`class.${index}.image`]: result });
                    })}
                    onChange={this.handleChange}
                  >
                    {image ? <img src={image} alt="avatar" /> : <div>
                      <Icon type={this.state.loading ? 'loading' : 'plus'} />
                      <div className="ant-upload-text">Upload</div>
                    </div>}
                  </Upload>,
                  // <FileUpload type='image'
                  //   onChange={(file) => System.uploadImage(file).then((result) => {
                  //     setFieldsValue({ [`class.${index}.image`]: result });
                  //   })}
                  // />,
                )}
              </Form.Item>
            </Card></Col>;
          })}
          <Col span={7} offset={classes.length % 3 ? 1 : 0}>
            <Card className="plus" onClick={() => {
              this.addLength('class', { title: '', link: '', image: '' });
            }}>
              <Icon type={'plus'} />
            </Card>
          </Col>
        </Row>
      </Form>
    </Block >;
  }

  renderActivity() {
    const { getFieldDecorator, getFieldValue, setFieldsValue } = this.props.form;
    const { data } = this.state;
    const activity = data.activity || [];
    return <Block>
      <h1>活动信息</h1>
      <Form>
        <Row>
          {activity.map((row, index) => {
            const image = getFieldValue(`activity.${index}.image`) || null;
            return <Col span={7} offset={index % 3 ? 1 : 0}><Card>
              <Button className="delete-button" size="small" onClick={() => {
                this.deleteLength('activity', index, 1);
              }}>
                <Icon type="delete" />
              </Button>
              <Form.Item labelCol={{ span: 7 }} wrapperCol={{ span: 15 }} label='跳转链接'>
                {getFieldDecorator(`activity.${index}.link`, {
                  rules: [
                    { required: true, message: '输入跳转链接' },
                  ],
                  initialValue: row.link,
                })(
                  <Input placeholder='请输入跳转链接' />,
                )}
              </Form.Item>
              <Form.Item labelCol={{ span: 7 }} wrapperCol={{ span: 15 }} label='活动图片'>
                {getFieldDecorator(`activity.${index}.image`, {
                  rules: [
                    { required: true, message: '上传图片' },
                  ],
                })(
                  <Upload
                    listType="picture-card"
                    showUploadList={false}
                    beforeUpload={(file) => System.uploadImage(file).then((result) => {
                      setFieldsValue({ [`claactivityss.${index}.image`]: result });
                    })}
                    onChange={this.handleChange}
                  >
                    {image ? <img src={image} alt="avatar" /> : <div>
                      <Icon type={this.state.loading ? 'loading' : 'plus'} />
                      <div className="ant-upload-text">Upload</div>
                    </div>}
                  </Upload>,
                  // <FileUpload type='image'
                  //   onChange={(file) => System.uploadImage(file).then((result) => {
                  //     setFieldsValue({ [`class.${index}.image`]: result });
                  //   })}
                  // />,
                )}
              </Form.Item>
            </Card></Col>;
          })}
          <Col span={7} offset={activity.length % 3 ? 1 : 0}>
            <Card className="plus" onClick={() => {
              this.addLength('activity', { link: '', image: '' });
            }}>
              <Icon type={'plus'} />
            </Card>
          </Col>
        </Row>
      </Form>
    </Block>;
  }

  renderEvaluation() {
    const { getFieldDecorator, getFieldValue, setFieldsValue } = this.props.form;
    const { data } = this.state;
    const evaluation = data.evaluation || [];
    return <Block>
      <h1>学员评价</h1>
      <Form>
        <Row>
          {evaluation.map((row, index) => {
            const avatar = getFieldValue(`evaluation.${index}.avatar`) || null;
            return <Col span={7} offset={index % 3 ? 1 : 0}><Card>
              <Button className="delete-button" size="small" onClick={() => {
                this.deleteLength('evaluation', index, 1);
              }}>
                <Icon type="delete" />
              </Button>
              <Form.Item labelCol={{ span: 7 }} wrapperCol={{ span: 15 }} label='学员昵称'>
                {getFieldDecorator(`evaluation.${index}.nickname`, {
                  rules: [
                    { required: true, message: '输入学员昵称' },
                  ],
                  initialValue: row.nickname,
                })(
                  <Input placeholder='请输入学员昵称' />,
                )}
              </Form.Item>
              <Form.Item labelCol={{ span: 7 }} wrapperCol={{ span: 15 }} label='学员头像'>
                {getFieldDecorator(`evaluation.${index}.avatar`, {
                  rules: [
                    { required: true, message: '上传图片' },
                  ],
                })(
                  <Upload
                    listType="picture-card"
                    showUploadList={false}
                    beforeUpload={(file) => System.uploadImage(file).then((result) => {
                      setFieldsValue({ [`evaluation.${index}.avatar`]: result });
                    })}
                  >
                    {avatar ? <img src={avatar} alt="avatar" /> : <div>
                      <Icon type={this.state.loading ? 'loading' : 'plus'} />
                      <div className="ant-upload-text">Upload</div>
                    </div>}
                  </Upload>,
                  // <FileUpload type='image'
                  //   onChange={(file) => System.uploadImage(file).then((result) => {
                  //     setFieldsValue({ [`class.${index}.image`]: result });
                  //   })}
                  // />,
                )}
              </Form.Item>
              <Form.Item labelCol={{ span: 7 }} wrapperCol={{ span: 15 }} label='评价内容'>
                {getFieldDecorator(`evaluation.${index}.content`, {
                  rules: [
                    { required: true, message: '输入评价内容' },
                  ],
                  initialValue: row.content,
                })(
                  <Input placeholder='请输入评价内容' />,
                )}
              </Form.Item>
            </Card></Col>;
          })}
          <Col span={7} offset={evaluation.length % 3 ? 1 : 0}>
            <Card className="plus" onClick={() => {
              this.addLength('evaluation', { title: '', link: '', image: '' });
            }}>
              <Icon type={'plus'} />
            </Card>
          </Col>
        </Row>
      </Form>
    </Block>;
  }

  renderContact() {
    const { getFieldDecorator, setFieldsValue, getFieldValue } = this.props.form;
    const wechatImage = getFieldValue('contact.wechatImage');
    const weiboImage = getFieldValue('contacct.weiboImage');
    return <Block>
      <Form>
        <h1>联系方式</h1>
        <Form.Item labelCol={{ span: 5 }} wrapperCol={{ span: 16 }} label='电话'>
          {getFieldDecorator('contact.phone', {
            rules: [
              { required: false, message: '请输入电话' },
            ],
          })(
            <Input placeholder='请输入电话' />,
          )}
        </Form.Item>
        <Form.Item labelCol={{ span: 5 }} wrapperCol={{ span: 16 }} label='邮箱'>
          {getFieldDecorator('contact.email', {
            rules: [
              { required: false, message: '请输入邮箱' },
            ],
          })(
            <Input placeholder='请输入邮箱' />,
          )}
        </Form.Item>
        <Form.Item labelCol={{ span: 5 }} wrapperCol={{ span: 16 }} label='微信号'>
          {getFieldDecorator('contact.wechat', {
            rules: [
              { required: false, message: '请输入微信号' },
            ],
          })(
            <Input placeholder='请输入微信号' />,
          )}
        </Form.Item>

        <Form.Item labelCol={{ span: 5 }} wrapperCol={{ span: 16 }} label='公众号二维码'>
          {getFieldDecorator('contact.wechatImage')(
            <Upload
              listType="picture-card"
              showUploadList={false}
              beforeUpload={(file) => {
                System.uploadImage(file).then((result) => {
                  setFieldsValue({ 'contact.wechatImage': result });
                });
              }
              }
            >
              {wechatImage ? <img src={wechatImage} alt="avatar" /> : <div>
                <Icon type={this.state.loading ? 'loading' : 'plus'} />
                <div className="ant-upload-text">Upload</div>
              </div>}
            </Upload>,
          )}
        </Form.Item>
        <Form.Item labelCol={{ span: 5 }} wrapperCol={{ span: 16 }} label='微博二维码'>
          {getFieldDecorator('contact.weiboImage')(
            <Upload
              listType="picture-card"
              showUploadList={false}
              beforeUpload={(file) => System.uploadImage(file).then((result) => {
                setFieldsValue({ 'contact.weiboImage': result });
              })}
            >
              {weiboImage ? <img src={weiboImage} alt="avatar" /> : <div>
                <Icon type={this.state.loading ? 'loading' : 'plus'} />
                <div className="ant-upload-text">Upload</div>
              </div>}
            </Upload>,
          )}
        </Form.Item>
      </Form>
    </Block>;
  }

  renderView() {
    return <div >
      {this.renderPrepare()}
      {this.renderUser()}
      {this.renderClass()}
      {this.renderActivity()}
      {this.renderEvaluation()}
      {this.renderContact()}
      <Affix style={{ position: 'absolute', bottom: '50px', right: '50px' }}>
        <Button type="primary" onClick={() => {
          this.submit();
        }}>保存</Button>
      </Affix>
    </div>;
  }
}