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';
import money from '../../../../money.js';

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

const formItemLayout = {
  labelCol: { span: 4 },
  wrapperCol: { span: 10 },
};
const NUMBERS = {
  1: '第一年',
  2: '第二年',
  3: '第三年',
  4: '第四年',
  5: '第五年',
}

const EvaluateStep5 = Form.create({})(React.createClass({
  getInitialState() {
    return {
      loading: false,
      initialData: {},
      hasIncome: '1',
      type: '1',
      dataSource: []
    };
  },
  componentWillMount() {
    let initialData = this.props.data || {}, dataSource = initialData.forecastIncomes || [];
    let step4 = this.props.record && this.props.record[3] || {};
    let type = initialData.type || '1';
    if (step4.hasIncome == 2) {
      $.ajax({
        url: globalConfig.context + '/api/user/evaluate/step5/' + this.props.id
      }).done(function (res) {
        if (res.error && res.error.length) {
          message.error(res.error[0].message)
        } else if (res.data && res.data.length === 3) {
          for (let i = 0; i < 3; i++) {
            dataSource[i] = Object.assign({
              key: i,
              income: 0,
              unitPrice: 0,
              saleCount: 0,
              marketScale: 0,
              marketRate: 0,
              recommend: res.data[i] || 0
            }, dataSource[i]);
          }
          this.setState({
            loading: false,
            dataSource: dataSource
          })
        }
      }.bind(this)).fail(function () {
        this.setState({
          loading: false
        })
      }.bind(this));
    } else {
      for (let i = 0; i < 3; i++) {
        dataSource[i] = Object.assign({
          key: i,
          income: 0,
          unitPrice: 0,
          saleCount: 0,
          marketScale: 0,
          marketRate: 0
        }, dataSource[i] || {});
      }
      this.state.dataSource = dataSource;
    }
    this.state.initialData = initialData;
    this.state.type = type;
    this.state.hasIncome = String(step4.hasIncome) || '1'
  },
  next() {
    if (this.state.loading) {
      return;
    }
    this.props.form.validateFields((err, values) => {
      if (!err) {
        this.setState({
          loading: true
        })

        let incomes = [];
        for (let i = 0; i < 3; i++) {
          incomes.push({
            unitPrice: values['unitPrice' + i] || 0,
            saleCount: values['saleCount' + i] || 0,
            marketScale: values['marketScale' + i] || 0,
            marketRate: values['marketRate' + i] || 0,
            income: values['income' + i] || 0
          })
        }

        $.ajax({
          url: globalConfig.context + '/api/user/evaluate/step5',
          method: 'post',
          data: {
            id: this.props.id,
            type: values.type,
            forecastIncomes: JSON.stringify(incomes)
          }
        }).done(function (res) {
          if (res.error && res.error.length) {
            message.error(res.error[0].message)
          } else {
            if (this.props.next) {
              this.props.next({
                type: values.type,
                forecastIncomes: incomes
              });
            }
          }
        }.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.props.form.resetFields();
    this.setState({
      type: e.target.value,
    });
  },
  tableCols() {
    const { getFieldDecorator, getFieldValue, setFieldsValue } = this.props.form;
    const { type } = this.state;
    let cols = [{
      title: '年份',
      dataIndex: 'key',
      key: 'key',
      render: (text, it, idx) => {
        return <div>{NUMBERS[idx + 1]}</div>
      }
    }];
    switch (type) {
      case "2":
        function calc(rate, scale, key) {
          let fv = {};
          fv['income' + key] = (scale * rate / 100) | 0
          setFieldsValue(fv);
        }
        cols.push({
          title: '市场规模(元)',
          dataIndex: 'marketScale',
          key: 'marketScale',
          render: (text, it, idx) => {
            return getFieldDecorator('marketScale' + it.key, {
              initialValue: text || 0,
              rules: [{
                validator: (rule, value, callback) => {
                  if (!Number(value)) {
                    callback('请输入' + NUMBERS[idx + 1] + '市场规模!');
                  } else {
                    callback();
                  }
                },
              }]
            })(<InputNumber min={0} placeholder="请输入市场规模" onChange={value => {
              calc(Number(getFieldValue('marketRate' + it.key)) || 0, Number(value) || 0, it.key);
            }} />);
          }
        });
        cols.push({
          title: '技术覆盖率/市场份额(%)',
          dataIndex: 'marketRate',
          key: 'marketRate',
          render: (text, it, idx) => {
            return getFieldDecorator('marketRate' + it.key, {
              initialValue: text || 0,
              rules: [{
                validator: (rule, value, callback) => {
                  if (!Number(value)) {
                    callback('请输入' + NUMBERS[idx + 1] + '市场份额!');
                  } else {
                    callback();
                  }
                },
              }]
            })(<InputNumber min={0} placeholder="请输入市场份额" onChange={value => {
              calc(Number(value) || 0, getFieldValue('marketScale' + it.key) || 0, it.key);
            }} />);
          }
        });
        cols.push({
          title: '营业收入(元)',
          dataIndex: 'income',
          key: 'income',
          render: (text, it, idx) => {
            return getFieldDecorator('income' + it.key, {
              initialValue: text || 0
            })(<InputNumber min={0} disabled={true} />);
          }
        });
        break;
      case "3":
        function calc(rate, scale, key) {
          let fv = {};
          fv['income' + key] = (scale * rate) | 0
          setFieldsValue(fv);
        }
        cols.push({
          title: '单价(元)',
          dataIndex: 'unitPrice',
          key: 'unitPrice',
          render: (text, it, idx) => {
            return getFieldDecorator('unitPrice' + it.key, {
              initialValue: text || 0,
              rules: [{
                validator: (rule, value, callback) => {
                  if (!Number(value)) {
                    callback('请输入' + NUMBERS[idx + 1] + '单价!');
                  } else {
                    callback();
                  }
                },
              }]
            })(<InputNumber min={0} placeholder="请输入单价" onChange={value => {
              calc(Number(getFieldValue('saleCount' + it.key)) || 0, Number(value) || 0, it.key);
            }} />);
          }
        });
        cols.push({
          title: '销量',
          dataIndex: 'saleCount',
          key: 'saleCount',
          render: (text, it, idx) => {
            return getFieldDecorator('saleCount' + it.key, {
              initialValue: text || 0,
              rules: [{
                validator: (rule, value, callback) => {
                  if (!Number(value)) {
                    callback('请输入' + NUMBERS[idx + 1] + '销量!');
                  } else {
                    callback();
                  }
                },
              }]
            })(<InputNumber min={0} placeholder="请输入销量" onChange={value => {
              calc(Number(value) || 0, getFieldValue('unitPrice' + it.key) || 0, it.key);
            }} />);
          }
        });
        cols.push({
          title: '营业收入(元)',
          dataIndex: 'income',
          key: 'income',
          render: (text, it, idx) => {
            return getFieldDecorator('income' + it.key, {
              initialValue: text || 0
            })(<InputNumber min={0} disabled={true} />);
          }
        });
        break;
      default:
        cols.push({
          title: '营业收入(元)',
          dataIndex: 'income',
          key: 'income',
          render: (text, it, idx) => {
            return getFieldDecorator('income' + it.key, {
              initialValue: text || 0,
              rules: [{
                validator: (rule, value, callback) => {
                  if (!Number(value)) {
                    callback('请输入' + NUMBERS[idx + 1] + '预估营业收入!');
                  } else {
                    callback();
                  }
                },
              }]
            })(<InputNumber min={0} placeholder="请输入预估营业收入" />);
          }
        })
        break;
    }
    if (this.state.hasIncome == '2') {
      cols.push({
        title: '参考值(元)',
        dataIndex: 'recommend',
        key: 'recommend',
        render: (text) => {
          return money(text)
        }
      })
    }
    return cols
  },
  stringify(val) {
    return val && String(val)
  },
  render() {
    let { loading, dataSource, type } = this.state;
    const { getFieldDecorator, getFieldValue, setFieldsValue } = this.props.form;
    return (
      <Spin spinning={loading}>
        <div style={{ marginBottom: 10 }}>根据市场等，预测该技术应用于生产活动并产生收入情况。（选择以下三种方式中的一种预估方法）</div>
        <Form className="steps-form">
          <FormItem label="请选择预测方法" {...formItemLayout}>
            {getFieldDecorator('type', {
              initialValue: this.stringify(type)
            })(
              <RadioGroup size="large" onChange={this.onRadioChange}>
                <RadioButton value="1">直接输入预测值法</RadioButton>
                <RadioButton value="2">市场份额法</RadioButton>
                <RadioButton value="3">数量单价法</RadioButton>
              </RadioGroup>
              )}
          </FormItem>
          <Table pagination={false} columns={this.tableCols()} dataSource={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 EvaluateStep5;