import React from 'react';
import { Form, Select, Input, Cascader, Spin, message, Button, DatePicker } from 'antd';
import ajax from 'jquery/src/ajax/xhr.js'
import $ from 'jquery/src/ajax';
import moment from 'moment';
import { transferTypes, leftTimes } from './dict.js';

const FormItem = Form.Item;
const Option = Select.Option;
const MonthPicker = DatePicker.MonthPicker;

const formItemLayout = {
  labelCol: { span: 4 },
  wrapperCol: { span: 10 },
};
const currency = ['人民币 (RMB)', '美金 (USD)', '台币(TWD)', '港币 (HKD)', '澳门元(MOP)', '欧元 (EUR)', '英镑 (GBP)', '日元 (JPY)', '澳大利亚元 (AUD)', '巴西里亚尔(BRL)', '加拿大元 (CAD)', '瑞士法郎 (CHF)', '丹麦克朗(DKK)', '印尼卢比 (IDR)', '韩国元 (KRW)', '林吉特(MYR)', '新西兰元 (NZD)', '菲律宾比索 (PHP)', '瑞典克朗 (SEK)', '新加坡元 (SGD)', '泰国铢 (THB)', '越南盾 (VND)', '南非兰特 (ZAR)']

const EvaluateStep1 = Form.create({})(React.createClass({
  getInitialState() {
    return {
      loading: true,
      industry: [],
      district: [],
      subIndustries: {},
      subIndustry: [],
      initialData: {}
    };
  },
  componentWillMount() {
      this.loadData();
      this.state.initialData = this.props.data || {};
  },
  componentWillReceiveProps(nextProps) {
      if(!this.props.visible&&nextProps.visible){
        this.setState({
          initialData:nextProps.data
        })
        this.loadData()
      }
	},
  loadData() {
    $.when($.ajax({
      url: globalConfig.context + '/open/findIndustryCategory'
    }), $.ajax({
      url: globalConfig.context + '/open/findDistrict'
    })).done(function (industryRes, districtRes) {
      let i = [], d = [{
        id: 0, level: 0, pid: 0, name: '全国'
      }];
      if (industryRes[0] && industryRes[0].data) {
        i = industryRes[0].data;
      }
      if (districtRes[0] && districtRes[0].data) {
        d = d.concat(districtRes[0].data);
      }
      this.setState({
        loading: false,
        industry: i,
        district: d
      });
      if (this.state.initialData) {
        this.changeFormField({
          'industry': this.stringify(this.state.initialData.industry),
          'transferArea': this.state.initialData.transferArea && this.state.initialData.transferArea.split(',')
        });
        this.loadSubIndustry(this.state.initialData.industry, this.state.initialData.subIndustry)
      }
    }.bind(this)).fail(function () {
      this.setState({
        loading: false
      })
    }.bind(this));
  },
  loadIndustry(pid, initValue) {
    if (this.industryLoader) {
      this.industryLoader.abort();
    }
    this.setState({
      loading: true
    })
    this.industryLoader = $.ajax({
      url: globalConfig.context + '/open/findIndustryCategory',
      method: 'get',
      data: {
        id: pid || 0
      }
    }).done(function (res) {
      if (res.data && res.data.length) {
        this.state.subIndustries[pid] = res.data;
        this.setState({
          loading: false,
          subIndustry: res.data
        })
        if (initValue) {
          this.changeFormField({
            'subIndustry': initValue.split(',')
          });
        }
      }
    }.bind(this)).always(function () {
      this.setState({
        loading: false
      })
    }.bind(this));
  },
  loadSubIndustry(pid, initValue) {
    let { subIndustries } = this.state;
    pid = Number(pid);
    this.changeFormField({
      'subIndustry': []
    });
    if (subIndustries[pid]) {
      this.setState({
        subIndustry: subIndustries[pid]
      })
    } else {
      this.loadIndustry(pid, initValue)
    }
  },
  subIndustryChanged(values) {
    let warn = false
    while (values.length > 3) {
      values.pop();
      warn = true;
    }
    if (warn) {
      message.warn("子行业最多选择三个！")
      this.changeFormField({
        'subIndustry': values
      });
    }
  },
  districtChanged(values) {
    let warn = false
    values.forEach((val) => {
      if (val === '0') {
        warn = true;
      }
    });
    if (warn) {
      this.changeFormField({
        'transferArea': ['0']
      });
    }
  },
  changeFormField(data) {
    setTimeout(function () {
      this.props.form.setFieldsValue(data);
    }.bind(this), 10);
  },
  next() {
    if (this.state.loading) {
      return;
    }
    this.props.form.validateFields((err, values) => {
      if (!err) {
        this.setState({
          loading: true
        })
        values.id = this.props.id;
        values.subIndustry = values.subIndustry.join(',');
        values.transferArea = values.transferArea.join(',');
        values.benchmarkDate = values.benchmarkDate.format('YYYY-MM-DD')
        $.ajax({
          url: globalConfig.context + '/api/user/evaluate/step1',
          method: 'post',
          data: values
        }).done(function (res) {
          if (res.error && res.error.length) {
            message.error(res.error[0].message)
          } else {
            if (this.props.next) {
              this.props.next(values);
            }
          }
        }.bind(this)).fail(function () {
          this.setState({
            loading: false
          })
        }.bind(this));
      }
    });
  },
  onDateChange(date) {
    date && date.date(1)
    this.changeFormField({
      'benchmarkDate': date
    });
  },
  stringify(val) {
    return val && String(val)
  },
  render() {
    const { getFieldDecorator } = this.props.form;
    let { subIndustry, industry, district, loading} = this.state;
    let initialData=this.state.initialData||{};
    return (
      <Spin spinning={loading}>
        <Form className="steps-form">
          <FormItem label="技术名称" {...formItemLayout}>
            {getFieldDecorator('name', {
              rules: [{ required: true, message: '请输入技术名称!' }],
              initialValue: initialData.name
            })(
              <Input placeholder="请输入技术名称" />
              )}
          </FormItem>
          <FormItem label="所属主行业" {...formItemLayout}>
            {getFieldDecorator('industry', {
              rules: [{ required: true, message: '请选择技术所属主行业!' }],
              initialValue:initialData.industry
            })(
              <Select placeholder="请选择技术所属主行业" onChange={this.loadSubIndustry}>
                {industry.map((it) => {
                  return <Option key={it.id} value={String(it.id)}>{it.name}</Option>
                })}
              </Select>
              )}
          </FormItem>
          <FormItem label="所属子行业" {...formItemLayout}>
            {getFieldDecorator('subIndustry', {
              rules: [{ required: true, message: '请选择技术所属子行业!' }],
              initialValue:initialData.subIndustry
            })(
              <Select placeholder="请选择技术所属子行业" allowClear={true} multiple={true} onChange={this.subIndustryChanged}>
                {
                  subIndustry.length ? subIndustry.map((it) => {
                    return <Option key={it.id} value={String(it.id)}>{it.name}</Option>
                  }) : []
                }
              </Select>
              )}
          </FormItem>
          <FormItem label="转让方式" {...formItemLayout}>
            {getFieldDecorator('transferType', {
              rules: [{ required: true, message: '请选择技术转让方式!' }],
              initialValue: this.stringify(initialData.transferType)
            })(
              <Select placeholder="请选择技术转让方式">
                {transferTypes.map((it) => {
                  return <Option key={it.id} value={it.id}>{it.text}</Option>
                })}
              </Select>
              )}
          </FormItem>
          <FormItem label="预估技术剩余寿命" {...formItemLayout}>
            {getFieldDecorator('timeLeft', {
              rules: [{ required: true, message: '请选择技术剩余寿命!' }],
              initialValue: this.stringify(initialData.timeLeft)
            })(
              <Select placeholder="请选择技术剩余寿命">
                {leftTimes.map((it) => {
                  return <Option key={it.id} value={it.id}>{it.text}</Option>
                })}
              </Select>
              )}
          </FormItem>
          <FormItem label="转让区域" {...formItemLayout}>
            {getFieldDecorator('transferArea', {
              rules: [{ required: true, message: '请选择技术转让区域!' }],
              initialValue:initialData.transferArea
            })(
              <Select placeholder="请选择技术转让区域" allowClear={true} multiple={true} onChange={this.districtChanged}>
                {district.map((it) => {
                  return <Option key={it.id} value={String(it.id)}>{it.name}</Option>
                })}
              </Select>
              )}
          </FormItem>
          <FormItem label="评估基准日" {...formItemLayout}>
            {getFieldDecorator('benchmarkDate', {
              rules: [{ required: true, message: '请输入评估基准日!' }],
              initialValue: initialData.benchmarkDate ? moment(initialData.benchmarkDate, 'YYYY-MM-DD') : null
            })(
              <MonthPicker allowClear={false} onChange={this.onDateChange} placeholder="请输入评估基准日" format="YYYY-MM-DD" />
              )}
          </FormItem>
          <FormItem label="评估币种" {...formItemLayout}>
            {getFieldDecorator('currencyType', {
              rules: [{ required: true, message: '请选择评估币种!' }],
              initialValue: initialData.currencyType || '人民币 (RMB)'
            })(
              <Select placeholder="请选择评估币种">
                {currency.map((it, idx) => {
                  return <Option key={idx} value={it}>{it}</Option>
                })}
              </Select>
              )}
          </FormItem>
        </Form>
        <div className="steps-action">
          <Button type="primary" onClick={this.next}>保存，下一步</Button>
        </div>
      </Spin>
    )
  },
}));

export default EvaluateStep1;