import React from 'react';
import { Spin, Form, Button, message, Radio, Table, InputNumber } from 'antd';
import ajax from 'jquery/src/ajax/xhr.js'
import $ from 'jquery/src/ajax';

const RadioButton = Radio.Button;
const RadioGroup = Radio.Group;
const FormItem = Form.Item;

const formItemLayout = {
  labelCol: { span: 4 },
  wrapperCol: { span: 10 },
};

const now = new Date();

const EvaluateStep4 = Form.create({})(React.createClass({
  getInitialState() {
    return {
      loading: false,
      initialData: {},
      hasIncome: '1',
      dataSource: []
    };
  },
  componentWillMount() {
    let initialData = this.props.data || {}, dataSource = [];
    if (initialData.incomes) {
      dataSource = initialData.incomes;
    } else {
      let step1 = this.props.record && this.props.record[0] || {};
      let year = now.getFullYear();//Number(step1.benchmarkDate && step1.benchmarkDate.split('-')[0]) || now.getFullYear();
      for (let i = 1; i < 4; i++) {
        dataSource.push({
          year: year - i,
          income: '',
          profit: ''
        })
      }
    }
    this.state.dataSource = dataSource;
    this.state.initialData = initialData;
    this.state.hasIncome = initialData.hasIncome || '1'
  },
  next() {
    if (this.state.loading) {
      return;
    }
    this.props.form.validateFields((err, values) => {
      if (!err) {
        this.setState({
          loading: true
        })
        let data = {
          id: this.props.id,
          hasIncome: values.hasIncome
        }, val = {
          hasIncome: values.hasIncome
        }
        if (data.hasIncome == 2) {
          let incomes = [], year = 0;
          for (let i = 0; i < 3; i++) {
            year = this.state.dataSource[i].year;
            incomes.push({
              year: year,
              income: values['income' + year] || 0,
              profit: values['profit' + year] || 0
            })
          }
          data.incomes = JSON.stringify(incomes);
          val.incomes = incomes;
        }
        $.ajax({
          url: globalConfig.context + '/api/user/evaluate/step4',
          method: 'post',
          data: data
        }).done(function (res) {
          if (res.error && res.error.length) {
            message.error(res.error[0].message)
          } else {
            if (this.props.next) {
              this.props.next(val);
            }
          }
        }.bind(this)).fail(function () {
          this.setState({
            loading: false
          })
        }.bind(this));
      } else {
        for (let field in err) {
          if (err.hasOwnProperty(field)) {
            message.error(err[field].errors[0].message)
            break;
          }
        }
      }
    });
  },
  prev() {
    if (this.props.prev) {
      this.props.prev();
    }
  },
  onRadioChange(e) {
    this.setState({
      hasIncome: e.target.value,
    });
  },
  tableCols() {
    const { getFieldDecorator } = this.props.form;
    return [
      {
        title: '年份',
        dataIndex: 'year',
        key: 'year',
        render: (text, it) => {
          return <div>{text}</div>
        }
      },
      {
        title: '营收(元)',
        dataIndex: 'income',
        key: 'income',
        render: (text, it, index) => {
          let rules = [];
          if (index === 0) {
            rules.push({ required: index === 0, message: '请输入' + it.year + '营收情况!' })
            rules.push({
              validator: (rule, value, callback) => {
                if (!Number(value)) {
                  callback('请输入' + it.year + '营收情况!' );
                } else {
                  callback();
                }
              },
            })
          }
          return getFieldDecorator('income' + it.year, {
            initialValue: text || 0,
            rules: rules
          })(<InputNumber min={0} placeholder="请输入营收情况" />);
        }
      },
      {
        title: '利润率（%）',
        dataIndex: 'profit',
        key: 'profit',
        render: (text, it, index) => {
          let rules = [];
          if (index === 0) {
            rules.push({ required: index === 0, message: '请输入' + it.year + '利润率!' })
            rules.push({
              validator: (rule, value, callback) => {
                if (!Number(value)) {
                  callback('请输入' + it.year + '利润率!' );
                } else {
                  callback();
                }
              },
            })
          }
          return getFieldDecorator('profit' + it.year, {
            initialValue: text || 0,
            rules: rules
          })(<InputNumber min={0} placeholder="请输入利润率" />);
        }
      },
    ]
  },
  stringify(val) {
    return val && String(val)
  },
  render() {
    let { loading, initialData } = this.state;
    const { getFieldDecorator } = this.props.form;
    return (
      <Spin spinning={loading}>
        <div style={{ marginBottom: 10 }}>若该技术曾被应用于生产活动并产生收益，可选择【有历史收入】，若否，请选择【无历史收入】。</div>
        <Form className="steps-form">
          <FormItem label="是否有历史收入" {...formItemLayout}>
            {getFieldDecorator('hasIncome', {
              initialValue: this.stringify(initialData.hasIncome) || '1'
            })(
              <RadioGroup size="large" onChange={this.onRadioChange}>
                <RadioButton value="1">无历史收入</RadioButton>
                <RadioButton value="2">有历史收入</RadioButton>
              </RadioGroup>
              )}
          </FormItem>
          {
            this.state.hasIncome == 1 ?
              <div style={{ marginTop: 10 }}>无历史收入, 请直接进入下一步</div> :
              <Table pagination={false} rowKey="year" columns={this.tableCols()} dataSource={this.state.dataSource} />
          }
        </Form>
        <div className="steps-action">
          <Button type="primary" onClick={() => this.next()}>保存，下一步</Button>
          <Button style={{ marginLeft: 8 }} onClick={() => this.prev()}>上一步</Button>
        </div>
      </Spin>
    )
  },
}));

export default EvaluateStep4;