/**
 * Created by baoyinghai on 11/17/16.
 *
 * 有数据字典的组件  服务器端返回的是由逗号隔开的字符串. 前端提交时为数组. 如果选项为空, 则返回数组或字符串的时候是null
 */
import React from 'react';
import { Form, Tooltip } from '../../../../components/mxa';
import InputAnalyser from './analyser/InputAnalyser';
import DatePickerAnalyser from './analyser/DatePickerAnalyser';
import InputNumberAnalyser from './analyser/InputNumberAnalyser';
import SelectAnalyser from './analyser/SelectAnalyser'; // add
import CascaderAnalyser from './analyser/CascaderAnalyser';
import CheckboxAnalyser from './analyser/CheckboxAnalyser'; // add
import RadioAnalyser from './analyser/RadioAnalyser';
import TimePickerAnalyser from './analyser/TimePickerAnalyser';
import SwitchAnalyser from './analyser/SwitchAnalyser';
import CheckboxGroupAnalyser from './analyser/CheckboxGroupAnalyser'; // add
import RadioGroupAnalyser from './analyser/RadioGroupAnalyser';
import ModalInputAnalyser from './analyser/ModalInputAnalyser';
import TextAreaAnalyser from './analyser/TextAreaAnalyser';
import YearPickerAnalyser from './analyser/YearPickerAnalyser';
import PasswordInputAnalyser from './analyser/PasswordInputAnalyser';
import TransferAnalyser from './analyser/TransferAnalyser';
import TextAnalyser from './analyser/TextAnalyser';
import InnerListAnalyser from './analyser/InnerListAnalyser';
import UploadAnalyser from './analyser/UploadAnalyser';
import { getValueByKey } from '../../../utils/MapUtils';
import { createFunc } from '../../../utils/JSExecutor';
import createRules from '../formValidator';
import { VIEW, EDIT } from '../constant';
import { createComp } from './compRefactHelper';

const FormItem = Form.Item;

const FormItemMap = {
  INPUT: InputAnalyser,
  DATEPICKER: DatePickerAnalyser,
  INPUTNUMBER: InputNumberAnalyser,
  SELECT: SelectAnalyser,
  CASCADER: CascaderAnalyser,
  CHECKBOX: CheckboxAnalyser,
  RADIO: RadioAnalyser,
  TIMEPICKER: TimePickerAnalyser,
  SWITCH: SwitchAnalyser,
  CHECKBOXGROUP: CheckboxGroupAnalyser,
  RADIOGROUP: RadioGroupAnalyser,
  MODALINPUT: ModalInputAnalyser,
  TEXTAREA: TextAreaAnalyser,
  YEARPICKER: YearPickerAnalyser,
  PASSWORDINPUT: PasswordInputAnalyser,
  TEXTLINK: TextAnalyser,
  TRANSFER: TransferAnalyser,
  INNERLIST: InnerListAnalyser,
  UPLOAD: UploadAnalyser,
  defaultAnalyser: InputAnalyser
};

// function isArray(o) {
//   return Object.prototype.toString.call(o) === '[object Array]';
// }


const getBindParameter = (props, record) => {
  const { defaultValue, initValueSource } = record;
  if (defaultValue) {
    return defaultValue;
  }
  let params = {};
  if (props && props.params) {
    params = props.params;
  }
  const cache = { ...params, ...getValueByKey(props, {}, 'query') };
  if (initValueSource && initValueSource.bindParameter) {
    if (initValueSource.bindParameter.value) {
      return initValueSource.bindParameter.value;
    } else if (cache[initValueSource.bindParameter.name]) {
      return cache[initValueSource.bindParameter.name];
    }
  }
  return cache[record.name];
};

/* eslint-disable */
const transFromtoDate = (data, compRender, record) => {
  if(data && record.type === 'Long') {
    return data - 0;
  }
  //  if (compRender === FormItemMap.DATEPICKER || compRender === FormItemMap.TIMEPICKER) {
  //    return data && moment(new Date(data));
  //  }
  return data;
};

// 表单项
// hasFeedback={model === 'edit'}
const formAnalyser = (compRender, model, props) => (formItemLayout, record, getFieldDecorator, detailResult, changeInitValue, replaceMain) => {
  // TODO: if result is true or false
  const initData = (detailResult && detailResult[record.name]) || getBindParameter(props, record);
  const compRenderData = { record, props, changeInitValue, replaceMain };
  const visibleStyle = record.isVisible ? {} : { display: 'none' };
  const analyserName = getValueByKey(record, 'default', 'displayComponent', 'componentType');
  const formItemJSX = (
    <FormItem
      style={visibleStyle}
      key={record.description}
      {...formItemLayout}
      label={record.description}
    >
      {renderCompItem(getFieldDecorator, record, props, compRender, model, initData, compRenderData)}
    </FormItem>
  );
  if (analyserName === 'UPLOAD') {
    return (
      <div>
        {formItemJSX}
         <span>
            提示信息:<br />
            1、文件大小不得超过10MB<br />
            2、文件名不能包含美元符号、逗号、斜杠、反斜杠<br />
            3、文件类型仅支持静态图片、office(doc、docx、xls、xlsx、ppt、pptx)文档、pdf文档和普通文本文档。<br />
            4、文件名长度不能超过100个字符。<br />
          </span>
      </div>
    )
  }
  return formItemJSX;
};

const renderCompItem = (getFieldDecorator, record, props, compRender, model, initData, compRenderData) => {
  if (record.isReadonly && record.displayComponent.componentType === 'INPUT' && props.dataSource.detailResult && props.dataSource.detailResult[record.name]) {
    return (
      <Tooltip title={props.dataSource.detailResult[record.name]} placement="topLeft">
        {getFieldDecorator(record.name, {
          rules: (props.createRules && props.createRules(record, props.form)) || createRules(record, props.form, props.isModalInputMappingItem),
          initialValue: transFromtoDate(initData, compRender, record) })((compRender[model](compRenderData)))
        }
      </Tooltip>
    );
  }
  return (
    <div>
      {getFieldDecorator(record.name, {
        rules: (props.createRules && props.createRules(record, props.form)) || createRules(record, props.form, props.isModalInputMappingItem),
        initialValue: transFromtoDate(initData, compRender, record) })((compRender[model](compRenderData)))
      }
    </div>
  );
};

const chooseAnalyser = (record, props, changeDataSourceVisable, changeInitValue) => {
  const analyserName = getValueByKey(record, 'default', 'displayComponent', 'componentType');
  // console.log(analyserName);
  if (record.relatedFunc) {
    return createComp(FormItemMap[analyserName], changeDataSourceVisable, createFunc(record.relatedFunc), changeInitValue, props.form && props.form.getFieldValue);
  }
  const ret = props.renderAnalyser && props.renderAnalyser(analyserName, record, changeDataSourceVisable);
  return ret || FormItemMap[analyserName] || FormItemMap.defaultAnalyser;
};

const renderFuc = (formItemLayout, record, getFieldDecorator, detailResult, props, changeDataSourceVisable, changeInitValue, replaceMain) => {
  return formAnalyser(chooseAnalyser(record, props, changeDataSourceVisable, changeInitValue), props.model, props)(formItemLayout, record, getFieldDecorator, detailResult, changeInitValue, replaceMain);
};

export const renderFormComp = (fieldContent) => {
  const analyserName = getValueByKey(fieldContent, 'default', 'displayComponent', 'componentType');
  return FormItemMap[analyserName][EDIT];
};

export default renderFuc;
