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

const FormItem = Form.Item;

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

const NUMBERS = {
  1: '第一年',
  2: '第二年',
  3: '第三年',
  4: '第四年',
  5: '第五年',
}

const getText = (map, key, field) => {
  if (field) {
    return map[key] ? (map[key][field || 'text'] || '') : key;
  }
  return map[key] ? map[key] : key;
}

const EvaluateStep8 = Form.create({})(React.createClass({
  getInitialState() {
    return {
      loading: true,
      record: {},
      industries: {},
      subIndustries: {},
      districts: {},
      value: 0,
      recommends: []
    };
  },
  componentWillMount() {
    let record = this.props.record || {}, dictMap = {};
    if (record[0] && record[0].industry) {
      this.loadData(record[0].industry);
    } else {
      this.state.loading = false;
    }
    this.state.record = record;
    this.state.value = this.props.value || 0;
    for (let key in dict) {
      if (dict.hasOwnProperty(key) && key != 'toMap') {
        dictMap[key] = dict.toMap(dict[key]);
      }
    }
    this.state.dictMap = dictMap;
  },
  loadData(pid) {
    $.when($.ajax({
      url: globalConfig.context + '/open/findIndustryCategory'
    }), $.ajax({
      url: globalConfig.context + '/open/findIndustryCategory',
      data: { id: pid }
    }), $.ajax({
      url: globalConfig.context + '/open/findDistrict'
    }), $.ajax({
      url: globalConfig.context + '/api/user/evaluate/step5/' + this.props.id
    })).done(function (industryRes, subIndustryRes, districtRes, recommendRes) {
      let i = {}, si = {}, d = { 0: "全国" }, r = [];
      if (industryRes[0] && industryRes[0].data) {
        industryRes[0].data.forEach(it => {
          i[String(it.id)] = it;
        })
      }
      if (subIndustryRes[0] && subIndustryRes[0].data) {
        subIndustryRes[0].data.forEach(it => {
          si[String(it.id)] = it;
        })
      }
      if (districtRes[0] && districtRes[0].data) {
        districtRes[0].data.forEach(it => {
          d[String(it.id)] = it.name;
        })
      }
      if (recommendRes[0] && recommendRes[0].data) {
        r = recommendRes[0].data;
      }
      this.setState({
        loading: false,
        industries: i,
        subIndustries: si,
        districts: d,
        recommends: r
      })
    }.bind(this)).fail(function () {
      this.setState({
        loading: false
      })
    }.bind(this));
  },
  next() {
    if (this.props.next) {
      this.props.next();
    }
  },
  prev() {
    if (this.props.prev) {
      this.props.prev();
    }
  },
  step1Col() {
    return [{ dataIndex: 'key', key: 'key', width: '40%', className: 'steps-cell-key' }, { dataIndex: 'text', key: 'text', width: '60%' }]
  },
  step4Col() {
    return [{
      title: '年份', dataIndex: 'year', key: 'year'
    }, {
      title: '营收', dataIndex: 'income', key: 'income', render: (text) => { return money(text || 0) + '元' }
    }, {
      title: '利润率', dataIndex: 'profit', key: 'profit', render: (text) => { return (text || 0) + '%' }
    }]
  },
  step5Col() {
    const step = this.state.record[4];
    let cols = [{
      title: '年份', dataIndex: 'key', key: 'key', render: (text) => { return NUMBERS[text + 1] }
    }]
    switch (step.type) {
      case "2":
        cols.push({ title: '市场规模', dataIndex: 'marketScale', key: 'marketScale', render: (text) => { return money(text || 0) + '元' } });
        cols.push({ title: '技术覆盖率/市场份额', dataIndex: 'marketRate', key: 'marketRate', render: (text) => { return (text || 0) + '%' } });
        break;
      case "3":
        cols.push({ title: '单价', dataIndex: 'unitPrice', key: 'unitPrice', render: (text) => { return money(text || 0) + '元' } });
        cols.push({ title: '销量', dataIndex: 'saleCount', key: 'saleCount' });
        break;
    }
    cols.push({ title: '营业收入', dataIndex: 'income', key: 'income', render: (text) => { return money(text || 0) + '元' } });
    if(this.state.record[3].hasIncome=='2') {
      cols.push({ title: '建议值', dataIndex: 'recommend', key: 'recommend', render: (text) => { return money(text || 0) + '元' } });
    }
    return cols;
  },
  step1Data() {
    const step = this.state.record[0], { industries, subIndustries, districts } = this.state;
    const { transferTypes, leftTimes } = this.state.dictMap;
    return step ? [{
      key: "技术名称",
      text: step.name
    }, {
      key: "所属主行业",
      text: getText(industries, String(step.industry), 'name')
    }, {
      key: "所属子行业",
      text: step.subIndustry.split(',').map(it => {
        return getText(subIndustries, it, 'name');
      }).join(',')
    }, {
      key: "转让方式",
      text: getText(transferTypes, String(step.transferType))
    }, {
      key: "预估技术剩余寿命",
      text: getText(leftTimes, String(step.timeLeft))
    }, {
      key: "转让区域",
      text: step.transferArea.split(',').map(it => {
        return districts[it] || it;
      }).join(',')
    }, {
      key: "评估基准日",
      text: step.benchmarkDate
    }, {
      key: "评估币种",
      text: step.currencyType
    }] : []
  },
  step2Data() {
    const step = this.state.record[1];
    const { accessMethods, legalStatus, maintenanceStatus, confidentialities, decidabilities, rightLimitations } = this.state.dictMap;
    return step ? [{
      key: "取得方式",
      text: getText(accessMethods, String(step.accessMethod))
    }, {
      key: "法律状态",
      text: getText(legalStatus, String(step.legalStatus))
    }, {
      key: "专利维护",
      text: getText(maintenanceStatus, String(step.patentMaintenance))
    }, {
      key: "保密性",
      text: getText(confidentialities, String(step.confidentiality))
    }, {
      key: "他人侵权的易判定性",
      text: getText(decidabilities, String(step.decidability))
    }, {
      key: "是否涉及质押、担保、诉讼等权利限制",
      text: getText(rightLimitations, String(step.hasRightLimitation))
    }] : []
  },
  step3Data() {
    const step = this.state.record[2];
    const { progressiveness, innovativeness, ripeness, alternatives,
      defensive, prospect, supplyAndDemand, rangeOfApplication, imitable, profitability } = this.state.dictMap;
    return step ? [{
      key: "先进性",
      text: getText(progressiveness, String(step.progressiveness))
    }, {
      key: "创新性",
      text: getText(innovativeness, String(step.innovativeness))
    }, {
      key: "成熟度",
      text: getText(ripeness, String(step.ripeness))
    }, {
      key: "替代性",
      text: getText(alternatives, String(step.alternatives))
    }, {
      key: "技术防御力",
      text: getText(defensive, String(step.defensive))
    }, {
      key: "技术领域发展前景",
      text: getText(prospect, String(step.prospect))
    }, {
      key: "供求关系",
      text: getText(supplyAndDemand, String(step.supplyAndDemand))
    }, {
      key: "产品应用范围",
      text: getText(rangeOfApplication, String(step.rangeOfApplication))
    }, {
      key: "遭他人模仿可能性",
      text: getText(imitable, String(step.imitable))
    }, {
      key: "独立获利能力",
      text: getText(profitability, String(step.profitability))
    }] : []
  },
  step4Data() {
    const step = this.state.record[3];
    return step.hasIncome == 2 && step.incomes || []
  },
  step5Data() {
    const step = this.state.record[4], { recommends } = this.state;
    let res = [];
    if (step.forecastIncomes) {
      step.forecastIncomes.forEach((it, idx) => {
        res.push(Object.assign({}, it, {
          key: idx,
          recommend: recommends[idx]
        }))
      })
    }
    return res
  },
  step6Data() {
    const step = this.state.record[5];
    return step ? [{
      key: "企业所得税率预估",
      text: step.taxRate + '%'
    }] : []
  },
  step7Data() {
    const step = this.state.record[6];
    const { political, technical, market, capital, management } = this.state.dictMap;
    return step ? [{
      key: "政策风险",
      text: getText(political, String(step.political))
    }, {
      key: "技术风险",
      text: getText(technical, String(step.technical))
    }, {
      key: "市场风险",
      text: getText(market, String(step.market))
    }, {
      key: "资金风险",
      text: getText(capital, String(step.capital))
    }, {
      key: "管理风险",
      text: getText(management, String(step.management))
    }] : []
  },
  step5Title() {
    const step = this.state.record[4];
    let title = "收入直接预估"
    switch (step.type) {
      case "2":
        title = "市场占比预估"
        break;
      case "3":
        title = "产品开发预估"
        break;
    }
    return title;
  },
  calc() {
    if(this.state.loading) {
      return;
    }
    this.setState({
      loading: true
    })
    $.ajax({
      url: globalConfig.context + '/api/user/evaluate/calc/' + this.props.id
    }).done(function (res) {
      let val = res && res.data || 0;
      this.setState({
        value: val,
        loading: false
      })
      if (this.props.next) {
        this.props.next(val)
      }
    }.bind(this)).fail(function () {
      this.setState({
        loading: false
      })
    }.bind(this));
  },
  render() {
    let { loading, record, value } = this.state;
    const tableProps = {
      showHeader: false,
      pagination: false,
      size: 'middle'
    }
    return (
      <Spin spinning={loading}>
        <div className="steps-result">
          <div className="steps-name">基本信息</div>
          <Table {...tableProps} columns={this.step1Col()} dataSource={this.step1Data()}></Table>
          <div className="steps-name">法律状况评估</div>
          <Table {...tableProps} columns={this.step1Col()} dataSource={this.step2Data()}></Table>
          <div className="steps-name">技术状况评估</div>
          <Table {...tableProps} columns={this.step1Col()} dataSource={this.step3Data()}></Table>
          <div className="steps-name">历史收入</div>
          <Table columns={this.step4Col()} dataSource={this.step4Data()} locale={{ emptyText: "无历史收入" }} rowKey="year" pagination={false} size="middle"></Table>
          <div className="steps-name">收入预估</div>
          <Table columns={this.step5Col()} dataSource={this.step5Data()} pagination={false} size="middle" showHeader={true} title={this.step5Title}></Table>
          <div className="steps-name">所得税预估</div>
          <Table {...tableProps} columns={this.step1Col()} dataSource={this.step6Data()}></Table>
          <div className="steps-name">风险预估</div>
          <Table {...tableProps} columns={this.step1Col()} dataSource={this.step7Data()}></Table>
          {
            value ? <div><div className="steps-name">价值评估结果：</div>
              <div className="steps-value">{money(value)}元</div></div> : <div />
          }
        </div>
        <div className="steps-action">
          {
            value ? <Button type="primary" onClick={() => window.open(globalConfig.context + '/user/account/evaluateInfo?id=' + this.props.id)}>查看评估报告</Button>
              : <Button type="primary" onClick={this.calc}>确认表单，开始估值</Button>
          }
          <Button style={{ marginLeft: 8 }} onClick={() => this.prev()}>上一步</Button>
        </div>
      </Spin>
    )
  },
}));

export default EvaluateStep8;