import React from 'react'
import { Input, Select, DatePicker, Icon, InputNumber, Switch, Checkbox, TimePicker, Tree, Popover, TreeSelect } from 'antd'
import moment from 'moment'
import { extendRule, getDataFieldValue, initFilter, setDataFieldValue, getDataFieldValueByCol } from '../../utils/common'
import DropDownPagination from '../../components/common/DropDownPagination';
import { CascaderInput, CheckToInput, TreeSelectInput } from '@woowalker/feui';
import ScannerComponent from '../../components/common/ScannerComponent';
import styles from '../Component.css';
import FromModal from '../../components/FormModal';
import MultiSelectPagination from '../../components/common/MultiSelectPagination'
import Attachment from '../../components/common/Attachment'

const CheckboxGroup = Checkbox.Group;
const Option = Select.Option
const { MonthPicker, RangePicker } = DatePicker
const { TextArea } = Input;
const TreeNode = Tree.TreeNode;
const TreeSelectNode = TreeSelect.TreeNode;

class ComponentBase extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      data: {},
    }
    this.compositioning = false;
  };

  componentDidMount() {
    if (typeof this.props.onRegDestroyCacheDataFunc === 'function') {
      this.props.onRegDestroyCacheDataFunc(() => this.onDestroyCacheData());
    }
    const onRegDestroyCacheDataFunc = this.props.data ? this.props.data.onRegDestroyCacheDataFunc : null;
    if (typeof onRegDestroyCacheDataFunc === 'function') {
      onRegDestroyCacheDataFunc(() => this.onDestroyCacheData());
    }
  };

  componentWillReceiveProps(NextProps) {

  }

  componentWillUnmount() {
    this.onDestroyCacheData();
  }

  /*
  销毁缓存数据
   */
  onDestroyCacheData() {

  }

  /*
    获取控件值 即转换值为实际控件值
   */
  getControlValue({ controlType, value, data }) {
    if (controlType === 4) {//单选控件
      value = (value != null) && (value.toString().toLowerCase() === 'true' || value.toString().toLowerCase() === '1');
    }
    else if (controlType === 5) {//多选控件
      const { enumName } = data ? data : {};
      if (enumName) {//存在枚举

      }
      else {
        value = value != null && (value.toString().toLowerCase() === 'true' || value.toString().toLowerCase() === '1')
      }
    }
    else if (controlType === 3) {//下拉
      value = (value !== null && value !== undefined && value !== '') ? parseInt(value, 10) : null;
    }
    else if (controlType === 2) {//日期
      //value=(value!==null&&value!==undefined&&value!=='')?moment(value):null;
    }
    else if (value === null || value === 'null') {
      value = '';
    }
    return value;
  }

  /*
  根据保存字段、导航字段填充下拉分页控件值
  record：已选择记录
  data：填充目的对象
  saveField：保存字段列表
  navField：导航字段列表
  * */
  fillDropDownSelectRecord({ record, data, saveField, labelField, navField, field, idField }) {
    if (data === undefined || data === null) return;
    const navFields = navField ? navField.split(',') : ['ID'];
    const labelFields = labelField ? labelField : 'NAME';
    const saveFields = saveField ? saveField.split(',') : [];
    if (saveFields && navFields && navFields.length === saveFields.length) {
      saveFields.forEach((n, i) => {
        setDataFieldValue(data, n, getDataFieldValue(record, navFields[i]));
      });
      if (labelFields && field) {
        setDataFieldValue(data, field, getDataFieldValue(record, labelFields));
      }
    }
    if (idField) {
      setDataFieldValue(data, idField, getDataFieldValue(record, 'ID'));
    }
    if (!record && field) {
      setDataFieldValue(data, field, null);
    }
  }

  /*
    根据控件配置获取控件
    controlType:控件类型  参考后台枚举PFControlTypeEnum
    field:字段名
    value: 控件值
    isRequire:是否必填
    caseType:转换类型 0-不处理 1-转大写 2-转小写
    disabled: 控件是否失效
    promptInfo: 控件提示信息
    onChange: 控件值改变时事件
    showFormCode:显示表单编号
    showFormId:显示表单  数据ID
    editFormCode: 编辑表单编号
    onBlur:控件失去焦点时事件
    style:样式
    data:特殊数据  用于承接控件特殊数据
         1-文本       onPressEnter:回车事件
         3-下拉选择   enumName：枚举名称（必填）
         5-多选控件  enumName：枚举名称（可选）
         7-数值       editFormData：编辑表单数据（存在editFormCode必填）
         9-分页下拉   api:数据API（必填）  onSelect：选中项事件（必填），选中后调用该事件
                      showField：下拉显示字段,navField：导航字段,labelField：显示字段,filterField：过滤字段,sortField：排序字段,sortOrder：排序方式,saveField:保存字段
                      onFilter：过滤事件（可选），在获取下拉数据时调用
                      onChangeHandle：改变事件（可选）， 分页下拉控件改变时调用
                      width：宽度（可选）
          11-下拉树选择
                  treeData;树数据,onSelect:选中节点事件,multiple：是否多选,onLoadData:加载树节点数据,sort:排序字段,order:排序方式}=data?data:{};

   */
  getControl(colConfig, record) {
    let {
      controlType,
      field,
      value,
      disabled,
      promptInfo,
      style,
      caseType,
      isRequire,
      onChange,
      showFormCode,
      showFormId,
      editFormCode,
      editFormFilter,
      editFormFilterValue,
      data,
      height,
      onBlur,
      label
    } = colConfig || {};



    if (controlType === 1) { // 文本输入框
      const isShowSrcBtn = showFormCode && showFormId;
      const inputProps = {
        placeholder: promptInfo,
        // allowClear: true, // allowClear会引起DOM节点没有这个属性的错误, antd低于3.12.0不支持
        style: isShowSrcBtn ? { ...style, width: '80%' } : { ...style, width: '100%' },
        value,
        disabled,
        onChange: e => {
          if (e !== null && e !== undefined) {
            let tmpValue = (e && e.target && e.target.value ? e.target.value : (typeof e === 'object' ? null : e));
            if (tmpValue && caseType && caseType === 1) {
              if (!this.compositioning) {
                tmpValue = tmpValue.toString().toUpperCase();
              }
            }
            else if (tmpValue && caseType && caseType === 2) {
              if (!this.compositioning) {
                tmpValue = tmpValue.toString().toLowerCase();
              }
            }
            if (typeof onChange === 'function') {
              onChange({
                field: field,
                value: tmpValue,
                colConfig,
                thisRef: this,
              })
            }
          }
        },
        onCompositionStart: e => {
          this.compositioning = true;
        },
        onCompositionEnd: e => {
          this.compositioning = false;
        },
        onBlur: () => {
          if (!disabled) {
            let tmpValue = value;
            if (tmpValue) {
              tmpValue = tmpValue.toString().replace(/(^\s*)|(\s*$)/g, "");
            }
            if (typeof onChange === 'function') {
              onChange({
                field: field,
                value: tmpValue,
                colConfig,
                thisRef: this,
              })
            }
          }
          if (typeof onBlur === 'function') {
            onBlur({
              field: field,
              colConfig,
              thisRef: this,
            })
          }
        },
        onPressEnter: (e) => {
          if (!disabled) {
            let tmpValue = value;
            if (tmpValue) {
              tmpValue = tmpValue.toString().replace(/(^\s*)|(\s*$)/g, "");
            }
            if (typeof onChange === 'function') {
              onChange({
                field: field,
                value: tmpValue,
                colConfig,
                thisRef: this,
              })
            }
          }
          const onPressEnter = data ? data.onPressEnter : null;
          if (typeof onPressEnter === 'function') {
            onPressEnter({
              field: field,
              colConfig,
              e,
              thisRef: this,
            });
          }
        },

      }
      return (
        <>
          <Input {...inputProps} />
          {
            isShowSrcBtn ? <FromModal formCode={showFormCode} data={{ id: showFormId, isShow: true }}>
              <Icon type="info-circle" style={{ marginLeft: 8, fontSize: 20 }} />
            </FromModal> : null
          }
        </>
      )
    }
    else if (controlType === 2) { // 时间控件：日期选择 ==> date: 日
      const datePickerProps = {
        title: promptInfo,
        disabled,
        style,
        allowClear: !isRequire,
        value: value ? moment(value) : null,
        onChange: (e, datestring) => {
          if (typeof onChange === 'function') {
            onChange({
              field: field,
              value: datestring,
              colConfig,
              thisRef: this,
            })
          }
        },
        onBlur: () => {
          if (typeof onBlur === 'function') {
            onBlur({
              field: field,
              colConfig,
              thisRef: this,
            })
          }
        }
      }
      return <><DatePicker {...datePickerProps} /></>
    }
    else if (controlType === 3) { // 单选下拉
      const enums = this.props.app ? this.props.app.enums : null;
      const enumName = data ? data.enumName : null;
      let options = data && !enumName && data.options ? data.options.split(',') : [];
      if (typeof value === 'string') {
        value = +value;
      }
      const selectProps = {
        title: promptInfo,
        disabled,
        value,
        showSearch: true,
        optionFilterProp: "children",
        allowClear: !isRequire,
        style: { width: '100%', minWidth: 80, ...style },
        onChange: (e) => {
          let tmpValue = (e && e.target && e.target.value ? e.target.value : (typeof e === 'object' ? null : e));
          if (typeof onChange === 'function') {
            onChange({
              field: field,
              value: tmpValue,
              colConfig,
              thisRef: this,
            })
          }
        },
        onBlur: () => {
          if (typeof onBlur === 'function') {
            onBlur({
              field: field,
              colConfig,
              thisRef: this,
            })
          }
        }
      }
      return (
        <>
          <Select {...selectProps}>
            {
              enumName && enums && enums[enumName] && enums[enumName].options ? enums[enumName].options.map(t => {
                return <Option value={t.value} key={field + t.value} >{t.label}</Option>
              }) : null
            }
            {
              options && options.length ? options.map((item, key) => {
                let paris = item.split(":");
                return <Option key={key} value={+paris[1]}>{paris[0]}</Option>
              }) : null
            }
          </Select>
        </>
      )
    }
    else if (controlType === 4) { // 开关控件：Switch
      const switchProps = {
        title: promptInfo,
        style,
        disabled,
        checked: value,
        checkedChildren: "是",
        unCheckedChildren: "否",
        onChange: e => {
          let tmpValue = (e && e.target && e.target.value ? e.target.value : (typeof e === 'object' ? null : e));
          if (typeof onChange === 'function') {
            onChange({
              field: field,
              value: tmpValue,
              colConfig,
              thisRef: this
            })
          }
        },
        onBlur: () => {
          if (typeof onBlur === 'function') {
            onBlur({
              field: field,
              colConfig,
              thisRef: this,
            })
          }
        }
      }

      return <><Switch {...switchProps} /></>
    }
    else if (controlType === 5) { // 复选框控件：CheckBox
      const enumName = data ? data.enumName : null;
      if (enumName) {
        const enums = this.props.app ? this.props.app.enums : null;
        const checkOptions = enumName && enums && enums[enumName] && enums[enumName].options ? enums[enumName].options : null;
        const tmp = value ? value.split('_') : [];
        const tmpValues = [];
        tmp.forEach((n, i) => {
          if (n !== '')
            tmpValues.push(+n);
        });

        const checkboxGroupProps = {
          title: promptInfo,
          style,
          options: checkOptions,
          disabled,
          value: tmpValues,
          onChange: (e) => {
            let tmpValue = e;
            if (typeof onChange === 'function') {
              onChange({
                field: field,
                value: tmpValue ? ("_" + tmpValue.join('_') + "_") : '',
                colConfig,
                thisRef: this,
              })
            }
          },
          onBlur: () => {
            if (typeof onBlur === 'function') {
              onBlur({
                field: field,
                colConfig,
                thisRef: this,
              })
            }
          }
        }

        return <><CheckboxGroup {...checkboxGroupProps} /></>
      } else {
        const switchProps = {
          title: promptInfo,
          style,
          disabled,
          checked: value,
          checkedChildren: "是",
          unCheckedChildren: "否",
          onChange: e => {
            let tmpValue = (e && e.target && e.target.value ? e.target.value : (typeof e === 'object' ? null : e));
            if (typeof onChange === 'function') {
              onChange({
                field: field,
                value: tmpValue,
                colConfig,
                thisRef: this,
              })
            }
          },
          onBlur: () => {
            if (typeof onBlur === 'function') {
              onBlur({
                field: field,
                colConfig,
                thisRef: this,
              })
            }
          }
        }
        return <><Switch {...switchProps} /></>
      }
    }
    else if (controlType === 6) { // 多行输入：TextArea
      const textAreaProps = {
        rows: height ? height : 4,
        placeholder: promptInfo,
        style,
        value,
        disabled,
        onChange: e => {
          if (e !== null && e !== undefined) {
            let tmpValue = (e.target && e.target.value ? e.target.value : (typeof e === 'object' ? null : e));
            if (tmpValue && caseType && caseType === 1) {
              tmpValue = tmpValue.toString().toUpperCase();
            }
            else if (tmpValue && caseType && caseType === 2) {
              tmpValue = tmpValue.toString().toLowerCase();
            }
            if (typeof onChange === 'function') {
              onChange({
                field: field,
                value: tmpValue,
                colConfig,
                thisRef: this,
              })
            }
          }
        },
        onBlur: () => {
          if (typeof onBlur === 'function') {
            onBlur({
              field: field,
              colConfig,
              thisRef: this,
            })
          }
        }
      }
      return <><TextArea {...textAreaProps} /></>
    }
    else if (controlType === 7) { // 数字输入：InputNumber
      let editFormData = editFormCode ? (data ? data.editFormData : null) : null;
      let inputNumberProps = {
        placeholder: promptInfo,
        disabled,
        value,
        style: editFormCode ? { ...style, width: '80%' } : { ...style, width: '100%' },
        onChange: e => {
          if (e !== null && e !== undefined) {
            // let tmpValue = (e.target && e.target.value ? e.target.value : (typeof e === 'object' ? null : e));
            let tmpValue = "";
            if (e.target && e.target.value && !isNaN(e.target.value)) {
              tmpValue = +e.target.value;
            } else if (!isNaN(e)) {
              tmpValue = +e
            } else {
              tmpValue = null
            }
            if (typeof onChange === 'function') {
              onChange({
                field: field,
                value: tmpValue,
                colConfig,
                thisRef: this,
              })
            }
          }
        },
        onBlur: () => {
          if (typeof onBlur === 'function') {
            onBlur({
              field: field,
              colConfig,
              thisRef: this,
            })
          }
        }
      }
      //最大最小步长d
      if (data?.isCheckMin) {
        inputNumberProps['min'] = data?.minVal;
      }
      if (data?.isCheckMax) {
        inputNumberProps['max'] = data?.maxVal;
      }
      if (data?.step) {
        inputNumberProps['step'] = data?.step;
      }


      return (
        <>
          <InputNumber {...inputNumberProps} />
          {
            editFormCode
              ? <FromModal
                formCode={editFormCode}
                data={editFormData}>
                <Icon type="edit" style={{ marginLeft: 8, fontSize: 20 }} />
              </FromModal>
              : null
          }
        </>
      )
    }
    else if (controlType === 8) { // 时分秒控件：TimePicker ==> 17:55:55
      let format = "HH:mm:ss"
      if (promptInfo != null && promptInfo.length > 0 && promptInfo.indexOf("00") > -1) {
        format = promptInfo
        promptInfo = label
      }
      return (
        <>
          <TimePicker
            format={format}
            title={promptInfo}
            disabled={disabled}
            allowClear={!isRequire}
            style={style}
            value={value ? moment(value, (value.indexOf('-') > -1 ? 'YYYY-MM-DD HH:mm:ss' : 'HH:mm:ss')) : null}
            onChange={(e, datestring) => {
              if (typeof onChange === 'function') {
                onChange({
                  field: field,
                  value: datestring,
                  colConfig,
                  thisRef: this,
                })
              }
            }}
            onBlur={() => {
              if (typeof onBlur === 'function') {
                onBlur({
                  field: field,
                  colConfig,
                  thisRef: this,
                })
              }
            }}
          />
        </>
      )
    }
    else if (controlType === 9) { // 分页下拉
      const { api, onLoadData, onSelect } = data || {};
      //var dataValue = getDataFieldValue(record, field, value);
      return <>
        <DropDownPagination
          api={api}
          key={record?.ID + field}
          value={value}
          disabled={disabled}
          style={style}
          record={record}
          colConfig={colConfig}
          showFormCode={showFormCode}
          editFormCode={editFormCode}
          editFormFilter={editFormFilter}
          editFormFilterValue={editFormFilterValue}
          thisRef={this}
          showFormId={showFormId}
          placeholder={promptInfo}
          onLoadData={onLoadData}
          onSelect={onSelect}
          data={data}
          onChange={({ value }) => {
            if (typeof onChange === 'function') {
              onChange({
                field: field,
                value: value,
                colConfig,
                thisRef: this,
              })
            }
          }}
          onBlur={() => {
            if (typeof onBlur === 'function') {
              onBlur({
                field: field,
                colConfig,
                thisRef: this,
              })
            }
          }}
        />
      </>
    }
    else if (controlType === 10) { // 时间控件：区间选择精确到日
      const temps = value ? value.split(',') : null;
      return (
        <>
          <RangePicker
            title={promptInfo}
            allowClear={!isRequire}
            disabled={disabled}
            style={style}
            value={temps && temps.length ? [moment(temps[0]), moment(temps[1])] : null}
            onChange={(e, datestring) => {
              if (typeof onChange === 'function') {
                onChange({
                  field: field,
                  value: (datestring && datestring.length === 2 && datestring[0] && datestring[1] ? datestring.join(',') : null),
                  colConfig,
                  thisRef: this,
                })
              }
            }}
            onBlur={() => {
              if (typeof onBlur === 'function') {
                onBlur({
                  field: field,
                  colConfig,
                  thisRef: this,
                })
              }
            }}
          />
        </>
      )
    }
    else if (controlType === 11) { // 下拉树选择
      let { api, onLoadData, onSelect } = data || {}
      return <>
        <TreeSelectInput
          api={api}
          data={data}
          value={value}
          record={record}
          colConfig={colConfig}
          thisRef={this}
          onLoadData={onLoadData}
          onSelect={onSelect}
          onChange={({ value }) => {
            if (typeof onChange === 'function') {
              onChange({
                field: field,
                value: value,
                colConfig,
                thisRef: this
              })
            }
          }}
          onBlur={() => {
            if (typeof onBlur === 'function') {
              onBlur({
                field: field,
                colConfig,
                thisRef: this
              })
            }
          }}
        />
      </>
    }
    else if (controlType === 12) { // 下拉多选
      const enums = this.props.app ? this.props.app.enums : null;
      const enumName = data ? data.enumName : null;
      const checkedData = [];
      let options = data && !enumName && data.options ? data.options.split(',') : [];
      const tmp = value ? value.split('_') : [];
      const tempValue = [];
      tmp.forEach((n, i) => {
        if (n !== '')
          tempValue.push(n);
      });
      //根据枚举名称获取树数据
      if (enumName && enums && enums[enumName] && enums[enumName].options && enums[enumName].options.length) {
        enums[enumName].options.forEach(t => {
          checkedData.push({
            label: t.label,
            value: t.value,
            key: t.value,
          });
        });
      }
      if (options && options.length) {
        options.forEach(item => {
          let paris = item.split(":");
          checkedData.push({
            label: paris[0],
            value: +paris[1],
            key: +paris[1],
          });
        });
      }

      return <>
        <CheckToInput
          checkedData={checkedData}
          value={tempValue}
          promptInfo={promptInfo}
          style={{ width: '100%', ...style, }}
          disabled={disabled}
          onChange={(changeValue) => {
            if (typeof onChange === 'function') {
              onChange({
                field: field,
                value: changeValue && changeValue.length ? ("_" + changeValue.join('_') + "_") : null,
                colConfig,
                thisRef: this,
              })
            }
          }}
        />
      </>
    }
    else if (controlType === 13) { // 扫描
      const { api, onSelect, onScan, onPressEnter } = data ? data : {};
      return <>
        <ScannerComponent
          api={api}
          value={value}
          disabled={disabled}
          style={style}
          colConfig={colConfig}
          showFormCode={showFormCode}
          thisRef={this}
          showFormId={showFormId}
          placeholder={promptInfo}
          onSelect={onSelect}
          data={data}
          onChange={({ value }) => {
            if (typeof onChange === 'function') {
              onChange({
                field: field,
                value: value,
                colConfig,
                thisRef: this,
              })
            }
          }}
          onBlur={() => {
            if (typeof onBlur === 'function') {
              onBlur({
                field: field,
                colConfig,
                thisRef: this,
              })
            }
          }}
          onScan={(scanParam) => {
            if (typeof onScan === 'function') {
              onScan({
                ...scanParam, field, colConfig,
                thisRef: this,
              });
            }
            if (typeof onPressEnter === 'function') {
              onPressEnter({
                ...scanParam, field, colConfig,
                thisRef: this,
              });
            }
          }}
        />
      </>
    }
    else if (controlType === 14) { // 系统序列号控件
      const codeRuleType = data.codeRuleType;
      return <>
        <Input
          placeholder={promptInfo}
          disabled={disabled}
          style={codeRuleType ? { width: '80%' } : { width: '100%' }}
          value={value}
          onChange={(e) => {
            if (e !== null && e !== undefined) {
              let tmpValue = (e.target && e.target.value ? e.target.value : (typeof e === 'object' ? null : e));
              if (tmpValue && caseType && caseType === 1) {
                tmpValue = tmpValue.toString().toLowerCase();
              }
              else if (tmpValue && caseType && caseType === 2) {
                tmpValue = tmpValue.toString().toUpperCase();
              }
              if (typeof onChange === 'function') {
                onChange({
                  field: field,
                  value: tmpValue,
                  colConfig,
                  thisRef: this,
                })
              }
            }
          }}
          onBlur={() => {
            if (!disabled) {
              let tmpValue = value;
              if (tmpValue) {
                tmpValue = tmpValue.toString().replace(/(^\s*)|(\s*$)/g, "");
              }
              if (typeof onChange === 'function') {
                onChange({
                  field: field,
                  value: tmpValue,
                  colConfig,
                  thisRef: this,
                })
              }
            }
            if (typeof onBlur === 'function') {
              onBlur({
                field: field,
                colConfig,
                thisRef: this,
              })
            }
          }}
        />
        {
          codeRuleType
            ? (
              <Icon
                type="info-circle"
                style={{ marginLeft: 8, fontSize: 20 }}
                onClick={() => {
                  if (typeof data.onGetCodeRule === 'function') {
                    data.onGetCodeRule((code) => {
                      if (typeof onChange === 'function') {
                        onChange({
                          field: field,
                          value: code,
                          colConfig,
                          thisRef: this,
                        })
                      }
                    }, codeRuleType)
                  }
                }}
              />
            )
            : null
        }
      </>
    }
    else if (controlType === 15) { // 时间控件：年月日时分秒 ==> DatePicker showTime
      return (
        <>
          <DatePicker
            placeholder={promptInfo}
            format="YYYY-MM-DD HH:mm:ss"
            showTime
            allowClear={!isRequire}
            disabled={disabled}
            style={style}
            value={value ? moment(value) : null}
            onChange={(e, datestring) => {
              if (typeof onChange === 'function') {
                onChange({
                  field: field,
                  value: datestring,
                  colConfig,
                  thisRef: this,
                })
              }
            }}
            onBlur={() => {
              if (typeof onBlur === 'function') {
                onBlur({
                  field: field,
                  colConfig,
                  thisRef: this,
                })
              }
            }}
          />
        </>
      )
    }
    else if (controlType === 16) { // 密码控件
      return (
        <>
          <Input
            placeholder={promptInfo}
            disabled={disabled}
            style={style}
            value={value}
            type="password"
            onChange={(e) => {
              if (e !== null && e !== undefined) {
                let tmpValue = (e.target && e.target.value ? e.target.value : (typeof e === 'object' ? null : e));
                if (tmpValue && caseType && caseType === 1) {
                  tmpValue = tmpValue.toString().toLowerCase();
                }
                else if (tmpValue && caseType && caseType === 2) {
                  tmpValue = tmpValue.toString().toUpperCase();
                }
                if (typeof onChange === 'function') {
                  onChange({
                    field: field,
                    value: tmpValue,
                    colConfig,
                    thisRef: this,
                  })
                }
              }
            }}
            onBlur={() => {
              if (!disabled) {
                let tmpValue = value;
                if (tmpValue) {
                  tmpValue = tmpValue.toString().replace(/(^\s*)|(\s*$)/g, "");
                }
                if (typeof onChange === 'function') {
                  onChange({
                    field: field,
                    value: tmpValue,
                    colConfig,
                    thisRef: this,
                  })
                }
              }
              if (typeof onBlur === 'function') {
                onBlur({
                  field: field,
                  colConfig,
                  thisRef: this,
                })
              }
            }}
          />
        </>
      )
    }
    else if (controlType === 17) { // 级联组件
      const { api, onLoadData, onSelect } = data || {};
      return <>
        <CascaderInput
          api={api}
          value={value}
          disabled={disabled}
          style={style}
          record={record}
          colConfig={colConfig}
          showFormCode={showFormCode}
          thisRef={this}
          showFormId={showFormId}
          placeholder={promptInfo}
          onLoadData={onLoadData}
          onSelect={onSelect}
          data={data}
          onChange={({ value }) => {
            if (typeof onChange === 'function') {
              onChange({
                field: field,
                value: value,
                colConfig,
                thisRef: this,
              })
            }
          }}
          onBlur={() => {
            if (typeof onBlur === 'function') {
              onBlur({
                field: field,
                colConfig,
                thisRef: this,
              })
            }
          }}
        />
      </>
    }
    else if (controlType === 18) { // 月份选择
      const monthPickerProps = {
        title: promptInfo,
        disabled,
        style,
        allowClear: !isRequire,
        value: value ? moment(value) : null,
        onChange: (e, datestring) => {
          const monthFormat = moment(datestring).format('YYYY-MM-DD')
          if (typeof onChange === 'function') {
            onChange({
              field: field,
              value: monthFormat,
              colConfig,
              thisRef: this,
            })
          }
        },
        onBlur: () => {
          if (typeof onBlur === 'function') {
            onBlur({
              field: field,
              colConfig,
              thisRef: this,
            })
          }
        }
      }
      return <><MonthPicker {...monthPickerProps} /></>
    }
    else if (controlType === 19) { // 月份区间
      const temps = value ? value.split(',') : null;
      return (
        <>
          <RangePicker
            mode={['month', 'month']}
            format="YYYY-MM"
            title={promptInfo}
            allowClear={!isRequire}
            disabled={disabled}
            style={style}
            value={temps && temps.length ? [moment(temps[0]), moment(temps[1])] : null}
            onChange={(e, dateStrings) => {
              if (typeof onChange === 'function') {
                onChange({
                  field: field,
                  value: dateStrings.filter(ds => !!ds).join(',') || null,
                  colConfig,
                  thisRef: this,
                })
              }
            }}
            onPanelChange={value => {
              if (typeof onChange === 'function') {
                const dateStrings = value.map(val => moment(moment(val).format('YYYY-MM')).format('YYYY-MM-DD'))
                onChange({
                  field: field,
                  value: dateStrings.join(',') || null,
                  colConfig,
                  thisRef: this,
                })
              }
            }}
            onBlur={() => {
              if (typeof onBlur === 'function') {
                onBlur({
                  field: field,
                  colConfig,
                  thisRef: this,
                })
              }
            }}
          />
        </>
      )
    }
    else if (controlType === 20) { // 年份选择
      const yearPickerProps = {
        title: promptInfo,
        disabled,
        style,
        allowClear: !isRequire,
        value: value ? moment(value) : null,
        mode: "year",
        format: "YYYY",
        placeholder: "请选择年份",
        onChange: (e, year) => {
          if (typeof onChange === 'function') {
            onChange({
              field: field,
              value: year || null,
              colConfig,
              thisRef: this,
            })
          }
        },
        onPanelChange: (date) => {
          const monthFormat = date ? moment(moment(date).format('YYYY')).format('YYYY-MM-DD') : null
          if (typeof onChange === 'function') {
            onChange({
              field: field,
              value: monthFormat,
              colConfig,
              thisRef: this,
            })
          }
        }
      }
      return <><DatePicker {...yearPickerProps} /></>
    }
    else if (controlType === 21) { // 年份区间
      const temps = value ? value.split(',') : null
      const handleChangeEvent = (e, value) => {
        if (typeof onChange === 'function') {
          const dateStrings = value.map(val => val ? moment(moment(val).format('YYYY')).format('YYYY-MM-DD') : null)
          if (dateStrings[0] && dateStrings[1]) {
            if (moment(dateStrings[0]).isAfter(dateStrings[1])) {
              dateStrings.reverse()
            }
          }
          onChange({
            field: field,
            value: dateStrings.filter(ds => !!ds).join(',') || null,
            colConfig,
            thisRef: this,
          })
        }
      }
      return (
        <>
          <RangePicker
            mode={['year', 'year']}
            format="YYYY"
            title={promptInfo}
            allowClear={!isRequire}
            disabled={disabled}
            style={style}
            value={temps && temps.length ? [moment(temps[0]), moment(temps[1])] : null}
            onChange={handleChangeEvent}
            onPanelChange={value => handleChangeEvent(null, value)}
            onCalendarChange={value => handleChangeEvent(null, value)}
          />
        </>
      )
    }
    else if (controlType === 22) { // 年月日时分秒区间
      const temps = value ? value.split(',') : null;
      return (
        <>
          <RangePicker
            showTime
            title={promptInfo}
            allowClear={!isRequire}
            disabled={disabled}
            style={style}
            value={temps && temps.length ? [moment(temps[0]), moment(temps[1])] : null}
            onChange={(e, dateStrings) => {
              if (typeof onChange === 'function') {
                onChange({
                  field: field,
                  value: dateStrings.filter(ds => !!ds).join(',') || null,
                  colConfig,
                  thisRef: this,
                })
              }
            }}
            onBlur={() => {
              if (typeof onBlur === 'function') {
                onBlur({
                  field: field,
                  colConfig,
                  thisRef: this,
                })
              }
            }}
          />
        </>
      )
    }
    else if (controlType === 23) { // 年月日时分区间
      const temps = value ? value.split(',') : null;
      return (
        <>
          <RangePicker
            showTime={{ format: 'HH:mm' }}
            format="YYYY-MM-DD HH:mm"
            title={promptInfo}
            allowClear={!isRequire}
            disabled={disabled}
            style={style}
            value={temps && temps.length ? [moment(temps[0]), moment(temps[1])] : null}
            onChange={(e, dateStrings) => {
              if (typeof onChange === 'function') {
                onChange({
                  field: field,
                  value: dateStrings.filter(ds => !!ds).join(',') || null,
                  colConfig,
                  thisRef: this,
                })
              }
            }}
            onBlur={() => {
              if (typeof onBlur === 'function') {
                onBlur({
                  field: field,
                  colConfig,
                  thisRef: this,
                })
              }
            }}
          />
        </>
      )
    }
    else if (controlType === 24) {//分页下拉多选
      const { api, onSelect } = data ? data : {};
      return <>
        <MultiSelectPagination api={api} value={value}
          //disabled={disabled}
          disabled={disabled}
          style={style} record={record} colConfig={colConfig} showFormCode={showFormCode} thisRef={this}
          showFormId={showFormId} placeholder={promptInfo} onSelect={onSelect} data={data} onChange={(value) => {
            if (typeof onChange === 'function') {
              onChange({
                field: field,
                value: value,
                colConfig,
                thisRef: this,
              })
            }
          }} onBlur={() => {
            if (typeof onBlur === 'function') {
              onBlur({
                field: field,
                colConfig,
                thisRef: this,
              })
            }
          }} />
      </>
    } else if (controlType === 25) {//附件
      return <Attachment
        style={style}
        record={record}
        colConfig={colConfig}
        showFormCode={showFormCode}
        thisRef={this}
        showFormId={showFormId}
        placeholder={promptInfo}
        data={data}
        onChange={({ value }) => {
          // const navShowFieldArray = colConfig.field.split('.');
          // const saveField = navShowFieldArray[0];
          // record[saveField]=value;
          // this.setState(record);
          if (typeof onChange === 'function') {
            onChange({
              field: field,
              value: value,
              colConfig,
              thisRef: this,
            })
          }
        }}
      />

    } else if (controlType === 108) { // 仿照 15 时间控件自定义格式：年月日时分秒 ==> DatePicker 
      var isShowTime = false
      let format = "YYYY-MM-DD HH:mm:ss"
      if (promptInfo != null && promptInfo.length > 0 && format.indexOf(promptInfo) > -1) {
        //promptInfo 要么 名称 要么 填写的信息
        format = promptInfo
        promptInfo = label
      } else if (promptInfo != null && promptInfo.length > 0 && promptInfo.indexOf("00") > -1) {
        format = promptInfo
        promptInfo = label
      }
      if (format.indexOf("HH") > -1 || format.indexOf("mm") > -1 || format.indexOf("ss") > -1) {
        isShowTime = true
      }
      return (
        <>
          <DatePicker
            placeholder={promptInfo}
            format={format}
            showTime={isShowTime}
            allowClear={!isRequire}
            disabled={disabled}
            style={style}
            value={value ? moment(value) : null}
            onChange={(e, datestring) => {
              if (typeof onChange === 'function') {
                onChange({
                  field: field,
                  value: datestring,
                  colConfig,
                  thisRef: this,
                })
              }
            }}
            onBlur={() => {
              if (typeof onBlur === 'function') {
                onBlur({
                  field: field,
                  colConfig,
                  thisRef: this,
                })
              }
            }}
          />
        </>
      )

    }
    // controlType === 100 ~ 107 默认是 Input 组件，用于处理不同类型文本
    return <>
      <Input placeholder={promptInfo} disabled={disabled} style={style} value={value} onChange={(e) => {
        if (e !== null && e !== undefined) {
          let tmpValue = (e.target && e.target.value ? e.target.value : (typeof e === 'object' ? null : e));
          if (tmpValue && caseType && caseType === 1) {
            tmpValue = tmpValue.toString().toLowerCase();
          }
          else if (tmpValue && caseType && caseType === 2) {
            tmpValue = tmpValue.toString().toUpperCase();
          }
          if (typeof onChange === 'function') {
            onChange({
              field: field,
              value: tmpValue,
              colConfig,
              thisRef: this,
            })
          }
        }
      }} onBlur={() => {
        if (!disabled) {
          let tmpValue = value;
          if (tmpValue) {
            tmpValue = tmpValue.toString().replace(/(^\s*)|(\s*$)/g, "");
          }
          if (typeof onChange === 'function') {
            onChange({
              field: field,
              value: tmpValue,
              colConfig,
              thisRef: this,
            })
          }
        }
        if (typeof onBlur === 'function') {
          onBlur({
            field: field,
            colConfig,
            thisRef: this,
          })
        }
      }} />
    </>
  }

  /*
    获取表中单元格显示文本
    {
      format,controlType,enumName,isBool,isDate,isPercent,isTwoPoint,isLimitText,isTime,showFormCode,showIdField,showFormId,
      data:{
         enumName
      }
    }
   */
  getTableCellText({ col, record, text, isReturnString }) {
    if (col.field && (col.field.indexOf('+') > -1 ||
      col.field.indexOf('-') > -1 ||
      col.field.indexOf('*') > -1 ||
      col.field.indexOf('/') > -1)) {
      text = getDataFieldValueByCol(record, col.field);
    }
    const isSysParam = col.field && (col.field.indexOf('Nav_SysParams') > -1)
    if (isSysParam) {
      text = getDataFieldValue(record, col.field);
    }
    if (typeof col.format === 'function') {
      return col.format({ col, record, text });
    }
    let enumName = col.data ? col.data.enumName : null;
    if (col.enumName) {
      enumName = col.enumName;
    }
    let options = col.data ? col.data.options : null;
    if (col.options) {
      options = col.options;
    }
    if (enumName || options) {
      const enums = this.props.app ? this.props.app.enums : null;
      let optionEnums = enumName && enums[enumName] ? enums[enumName].enums : null;
      if (optionEnums === null && options) {
        optionEnums = {};
        let tempOptions = options.split(',');
        tempOptions.forEach(item => {
          let paris = item.split(":");
          optionEnums[+paris[1]] = paris[0];
        });
      }
      if (text && text.toString().indexOf('_') > -1 && optionEnums) {
        let s = '';
        const tmp = text.toString().split('_');
        const arr = [];
        tmp.forEach((n, i) => {
          if (n !== '')
            arr.push(n);
        });
        if (arr) {
          arr.forEach((n1, i1) => {
            s += optionEnums[parseInt(n1, 10)] + ' ';
          });
        }
        return isReturnString ? s : <span>{s}</span>
      }
      if (typeof text === 'string') {
        text = +text;
      }
      return isReturnString ? optionEnums[text] : <span>{optionEnums && optionEnums[text] ? optionEnums[text] : '--'}</span>;
    }
    //系统格式化
    if (col.isBool || col.controlType === 101) {//布尔类型
      if (isSysParam) {
        text = this.getControlValue({ controlType: 4, value: text });
      }
      text = text ? '是' : '否';
    }
    else if (col.isDate || col.controlType === 102) {//日期
      if (isSysParam) {
        text = this.getControlValue({ controlType: 2, value: text });
      }
      if (text) {
        text = text.toString().substring(0, 10);
      }
    }
    else if (col.isPercent || col.controlType === 107) {//百分比
      const num = parseFloat(text);
      if (!isNaN(num)) {
        text = (num * 100).toFixed(2) + "%";
      }
    }
    else if (col.isTwoPoint || col.controlType === 104) {//格式化为两位小数
      const num = parseFloat(text);
      if (!isNaN(num)) {
        text = num.toFixed(2);
      }
    }
    else if (col.isThreePoint || col.controlType === 105) {//格式化为三位小数
      const num = parseFloat(text);
      if (!isNaN(num)) {
        text = num.toFixed(3);
      }
    }
    else if (col.isLimitText || col.controlType === 106) {//限制文本长度
      if (text) {
        if (text.length > 10) {
          text = <span title={text}>{text.substring(0, 10) + '...'}</span>;
        }
      }
    }
    else if (col.isTime || col.controlType === 103) {//时间
      if (text) {
        text = text.toString().substring(11, 19);
      }
    } else if (col.controlType === 108 && col.customParams && text) {//wyw 列表日期格式转换  配合 修改了 Format
      text = (new Date(text)).Format(col.customParams)
    }
    // 显示日期根据控件类型格式化
    if (col.controlType === 2) {
      moment(text).isValid() && (text = moment(text).format('YYYY-MM-DD'))
    }
    else if (col.controlType === 8) {
      moment(text).isValid() && (text = moment(text).format('HH:mm:ss'))
    }
    else if (col.controlType === 10) {
      const dates = text.split(',')
      if (moment(dates[0]).isValid() && moment(dates[1]).isValid()) {
        text = [moment(dates[0]).format('YYYY-MM-DD'), moment(dates[1]).format('YYYY-MM-DD')].join(',')
      }
    }
    else if (col.controlType === 18) {
      moment(text).isValid() && (text = moment(text).format('YYYY-MM'))
    }
    else if (col.controlType === 19) {
      const months = text.split(',')
      if (moment(months[0]).isValid() && moment(months[1]).isValid()) {
        text = [moment(months[0]).format('YYYY-MM'), moment(months[1]).format('YYYY-MM')].join(',')
      }
    }

    if (col.showIdField) {
      col.showFormId = getDataFieldValue(record, col.showIdField);
    }
    const isShow = col.showFormCode && col.showFormId;
    if (isShow && !isReturnString) {
      const reloadKey = col.showFormCode + '_' + col.showFormId + '_' + col.id + '_' +
        record.ID + '_reload';
      let rule = [];
      if (col.showFormParms) {
        rule = [
          {
            field: col.showFormParms,
            operator: 1,
            value: record.ID
          }
        ];
      }
      return col.showFormId ? <><span style={{ width: '80%' }}>{text}</span>
        <FromModal formCode={col.showFormCode} data={{ id: col.showFormId, reloadKey, isShow: true, showFormParms: col.showFormParms, rules: [...rule] }}>
          <Icon type="info-circle" style={{ marginLeft: 8, fontSize: 20 }} />
        </FromModal></> : <span>{text}</span>;
    }
    return text;
  }

  /*
  添加新增日志
   */
  addAddLog({ formCode, formId, ids, codes, extData, thisRef }) {
    if (!thisRef) {
      thisRef = this;
    }
    const { login, dispatch, formId: tempFormId, formCode: tempFormCode } = thisRef.props;
    if (dispatch && login) {
      const logJson = initFilter(login.OrgId, login.userId, '', 0, 1, (formCode ? formCode : tempFormCode), (formId ? formId : tempFormId), ids, codes, extData);
      dispatch({
        type: 'app/addAddLog',
        payload: logJson,
      });
    }
  }

  /*
  添加编辑日志
   */
  addEditLog({ formCode, formId, ids, codes, extData, thisRef }) {
    if (!thisRef) {
      thisRef = this;
    }
    const { login, dispatch, formId: tempFormId, formCode: tempFormCode } = thisRef.props;
    if (dispatch && login) {
      const logJson = initFilter(login.OrgId, login.userId, '', 0, 1, (formCode ? formCode : tempFormCode), (formId ? formId : tempFormId), ids, codes, extData);
      dispatch({
        type: 'app/addEditLog',
        payload: logJson,
      });
    }
  }

  /*
    添加删除日志
     */
  addDeleteLog({ formCode, formId, ids, tableName, extData, thisRef }) {
    if (!thisRef) {
      thisRef = this;
    }
    const { login, dispatch, formId: tempFormId, formCode: tempFormCode } = thisRef.props;
    if (dispatch && login) {
      const logJson = initFilter(login.OrgId, login.userId, '', 0, 1, (formCode ? formCode : tempFormCode), (formId ? formId : tempFormId), ids, tableName, extData);
      dispatch({
        type: 'app/addDeleteLog',
        payload: logJson,
      });
    }
  }

  /*
    添加其他日志
     */
  addOtherLog({ formCode, formId, title, data, extData, thisRef }) {
    if (!thisRef) {
      thisRef = this;
    }
    const { login, dispatch, formId: tempFormId, formCode: tempFormCode } = thisRef.props;
    if (dispatch && login) {
      const logJson = initFilter(login.OrgId, login.userId, '', 0, 1, (formCode ? formCode : tempFormCode), (formId ? formId : tempFormId), title, data, extData);
      dispatch({
        type: 'app/addOtherLog',
        payload: logJson,
      });
    }
  }

  /*
    根据父ID添加树节点
   */
  addTreeDataByParentId = (treeData, parentId, data) => {
    if (treeData) {
      if (parentId) {
        treeData.forEach(n => {
          if (n.ID === parentId) {
            if (!n.Children) {
              n.Children = [];
            }
            n.IS_LEAF = false;
            n.Children.push(data);
          }
          else if (n.Children && n.Children.length) {
            this.addTreeDataByParentId(n.Children, parentId, data);
          }
        });
      }
      else {
        treeData.push(data);
      }
    }
  };

  /*
  根据ID删除树节点
   */
  deleteTreeDataById = (treeData, id, parent, getNodeData) => {
    if (treeData && treeData.length) {
      let index = -1;
      treeData.forEach((n, i) => {
        if (n.ID === id) {
          index = i;
        }
        else if (n.Children && n.Children.length) {
          this.deleteTreeDataById(n.Children, id, n);
        }
      });
      if (index !== -1) {
        if (getNodeData) {
          getNodeData(treeData[index]);
        }
        treeData.splice(index, 1);
        if (parent) {
          if (!parent.Children || parent.Children.length === 0) {
            parent.IS_LEAF = true;
          }
        }
      }
    }
  };

  /*
  根据ID更新树数据
   */
  updateTreeDataById = (treeData, id, data) => {
    if (treeData && treeData.length) {
      let index = -1;
      treeData.forEach((n, i) => {
        if (n.ID === id) {
          index = i;
        }
        else if (n.Children && n.Children.length) {
          this.updateTreeDataById(n.Children, id, data);
        }
      });
      if (index !== -1) {
        const d = treeData[index];
        treeData.splice(index, 1, { ...d, ...data, });
      }
    }
  };

  /*
  根据ID获取树数据
   */
  getTreeDataById = (treeData, id, complete) => {
    if (treeData && treeData.length) {
      treeData.forEach((n, i) => {
        if (n.ID === id) {
          if (typeof complete === 'function') {
            complete(n);
          }
        }
        else if (n.Children && n.Children.length) {
          this.getTreeDataById(n.Children, id, complete);
        }
      });
    }
  };

  /*
  根据ID获取父节点
  complete(parent)://parent父数据
   */
  getTreeParentById = (treeData, id, complete) => {
    this.doGetTreeParentById(treeData, id, null, complete);
  };

  /*
  实际获取父节点
   */
  doGetTreeParentById = (treeData, id, parent, complete) => {
    if (treeData && treeData.length) {
      treeData.forEach((n, i) => {
        if (n.ID === id) {
          if (typeof complete === 'function') {
            complete(parent);
          }
        }
        else if (n.Children && n.Children.length) {
          this.doGetTreeParentById(n.Children, id, n, complete);
        }
      });
    }
  };

  /*
   获取树数据  即将列表转为树状数据
   {
   data:数据
   }
   */
  getTreeDataByList(params) {
    const { data } = params ? params : {};
    if (data && data.length) {
      const list = [];
      this.doGetTreeDataByList(data, null, null, list);
      return list;
    }
    return [];
  }

  /*
  实际获取树数据
   */
  doGetTreeDataByList = (data, parent, parentId, list) => {
    if (data && data.length) {
      const tmps = [];
      data.forEach(t => {
        if (t.PARENT_ID === parentId) {
          tmps.push(t);
        }
      });
      if (tmps && tmps.length) {
        tmps.forEach(t => {
          this.doGetTreeDataByList(data, t, t.ID, list);
        });
        if (parent) {
          parent.Children = tmps;
        } else {
          tmps.forEach(t => {
            list.push(t);
          });
        }
      }
    }
  };

  /*
  渲染树
  {
  data,  //数据
  treeCode,//树编号
  onLoadData,//加载数据事件
  onSelect,//选中节点事件
  expandedKeys,//已展开直接列表
  selectedId,//当前选中节点ID
  onExpand,//展开事件
  sort,排序字段
  order,排序类型
  onContextMenu,//获取节点右击菜单列表事件
  getNodeMenuKey,//获取节点右击菜单键值函数
  setNodeMenuVisible,//设置节点菜单可见性函数
  getTreeNodeTitle,//获取节点标题函数
  draggable,//是否拖拽
  onDrop,//拖拽事件
  }
   */
  getRenderTree(params) {
    const { data, onLoadData, onSelect, expandedKeys, selectedId, onExpand, draggable, onDrop } = params ? params : {};
    if (data && data.length) {
      return <Tree
        loadData={(treeNode) => {
          if (typeof onLoadData === 'function') {
            return onLoadData({ ...params, treeNode });
          }
          return new Promise((resolve, reject) => {
            if (treeNode.props.dataRef.IS_LEAF) {
              reject();
            } else {
              resolve();
            }
          });
        }}
        // onRightClick={({event, node}) => this.setState({ contextMenuId: node.props.eventKey})}
        onSelect={(selectedKeys, e) => {
          if (typeof onSelect === 'function') {
            onSelect({
              ...params,
              id: e.node.props.dataRef.ID,
              isAdd: e.node.props.dataRef.isAdd,
              data: e.node.props.dataRef
            });
          }
        }}
        expandedKeys={expandedKeys}
        onExpand={(expandedKeys, expandNodeInfo) => {
          if (typeof onExpand === 'function') {
            onExpand({
              ...params,
              expandedKeys,
              expandNodeInfo
            });
          }
        }}
        selectedKeys={selectedId ? [selectedId] : null}
        draggable={draggable}
        onDrop={(info) => {
          const dropKey = info.node.props.eventKey;//目标节点键值
          const dragKey = info.dragNode.props.eventKey;//拖拽节点键值
          const dropPos = info.node.props.pos.split('-');
          const dropPosition = info.dropPosition - Number(dropPos[dropPos.length - 1]);

          const loop = (data, key, callback, parent) => {
            data.forEach((item, index, arr) => {
              if (item.ID === key) {
                return callback(item, index, arr, parent);
              }
              if (item.Children) {
                return loop(item.Children, key, callback, item);
              }
            });
          };
          let dragObj;
          let oldDragParentId = null;
          loop(data, dragKey, (item, index, arr, parent) => {
            if (arr.length === 1) {
              this.getTreeParentById(data, dragKey, (d) => {
                d.IS_LEAF = true;
              })
            }
            arr.splice(index, 1);
            dragObj = item;
            if (parent) {
              oldDragParentId = parent.ID;
            }
          });
          if (!info.dropToGap) {
            loop(data, dropKey, (item) => {
              item.Children = item.Children || [];
              item.IS_LEAF = false;
              dragObj.PARENT_ID = item.ID;
              item.Children.push(dragObj);
            });
          }
          else if (
            (info.node.props.Children || []).length > 0 // Has children
            && info.node.props.expanded // Is expanded
            && dropPosition === 1 // On the bottom gap
          ) {
            loop(data, dropKey, (item) => {
              item.Children = item.Children || [];
              item.IS_LEAF = false;
              dragObj.PARENT_ID = item.ID;
              item.Children.unshift(dragObj);
            });
          } else {
            let ar;
            let i;
            let p;
            loop(data, dropKey, (item, index, arr, parent) => {
              ar = arr;
              i = index;
              p = parent;
            });
            if (p) {
              dragObj.PARENT_ID = p.ID;
              p.IS_LEAF = false;
            }
            else {
              dragObj.PARENT_ID = null;
            }
            if (dropPosition === -1) {
              ar.splice(i, 0, dragObj);
            } else {
              ar.splice(i + 1, 0, dragObj);
            }
          }
          onDrop(data, dragObj.ID, dragObj.PARENT_ID, dropKey, oldDragParentId);
        }}
      >
        {this.getRenderTreeNode(params, data)}
      </Tree>
    }
  }

  /*
  渲染树节点
   */
  getRenderTreeNode = (params, nodeData) => {
    if (!nodeData || !nodeData.length) return null;
    let { onContextMenu, treeCode, getNodeMenuKey, setNodeMenuVisible, getTreeNodeTitle, sort, order } = params ? params : {};
    if (!sort) {
      sort = 'ID';
    }
    const tempOrder = order ? order : 0;
    nodeData.sort((x, y) => {
      const xValue = getDataFieldValue(x, sort);
      const yValue = getDataFieldValue(y, sort);
      if (xValue != null && yValue != null) {
        if (xValue == yValue) return 0
        return tempOrder === 0 ? (xValue > yValue ? 1 : -1) : (xValue > yValue ? -1 : 1);
      }
      else if (xValue != null) {
        return tempOrder === 0 ? -1 : 1;
      }
      else if (yValue != null) {
        return tempOrder === 0 ? 1 : -1;
      }
      else {
        if (x.toString() === y.toString()) return 0
        return tempOrder === 0 ? (x.toString() > y.toString() ? 1 : -1) : (x.toString() > y.toString() ? -1 : 1);
      }
    });

    return nodeData.map((item) => {
      if (item) {
        const menuKey = typeof getNodeMenuKey === 'function' ? getNodeMenuKey({ treeCode, id: item.ID }) : 'treeNodeMenuKey_' + treeCode + '_' + item.ID;
        let title = typeof getTreeNodeTitle === 'function' ? getTreeNodeTitle({ data: item }) : item.NAME;
        const tempContextMenu = () => {
          let ret = null;
          if (typeof onContextMenu === 'function') {
            ret = onContextMenu({
              ...params,
              data: item,
            });
          }
          if (!ret) {
            ret = <div>空</div>;
          }
          return ret;
        };
        return <TreeNode
          title={<Popover
            content={tempContextMenu()}
            trigger="contextMenu"
            overlayClassName={styles.contextMenuPop}
            arrowPointAtCenter={true}
            visible={this.state[menuKey]}
            onVisibleChange={(visible) => {
              if (typeof setNodeMenuVisible === 'function') {
                setNodeMenuVisible({ treeCode, id: item.ID, visible });
              }
              else {
                this.setState({
                  [menuKey]: visible
                });
              }
            }}
            placement="right">{title}</Popover>}
          key={item["ID"]}
          dataRef={item}
          isLeaf={item["IS_LEAF"]}
        >
          {this.getRenderTreeNode(params, item.Children)}
        </TreeNode>
      } else {
        return null;
      }
    });
  };

  /*
  渲染选择树节点
  params={
  sort,order,
  }
   */
  getRenderSelectTreeNode = (params, nodeData) => {
    if (nodeData && nodeData.length) {
      let { sort, order } = params ? params : {};
      if (sort) {
        const tempOrder = order ? order : 0;
        nodeData.sort((x, y) => {
          const xValue = getDataFieldValue(x, sort);
          const yValue = getDataFieldValue(y, sort);
          if (xValue != null && yValue != null) {
            return tempOrder === 0 ? (xValue > yValue ? 1 : -1) : (xValue > yValue ? -1 : 1);
          }
          else if (xValue != null) {
            return tempOrder === 0 ? -1 : 1;
          }
          else if (yValue != null) {
            return tempOrder === 0 ? 1 : -1;
          }
          else {
            return tempOrder === 0 ? (x.toString() > y.toString() ? 1 : -1) : (x.toString() > y.toString() ? -1 : 1);
          }
        });
      }
      return nodeData.map((item) => {
        if (item.Children) {
          return (
            <TreeSelectNode title={item.label} key={item.key} value={item.value} data={item}
              isLeaf={item.isLeaf}>
              {this.getFieldTreeNode(item.Children)}
            </TreeSelectNode>
          );
        }
        return <TreeSelectNode title={item.label} key={item.key} value={item.value} data={item}
          isLeaf={item.isLeaf} />;
      });
    }
  };

  getBtnsOnCustomPage(formId) {
    if (!formId) {
      formId = this.props.formId;
    }
    const json = initFilter(this.props.login.OrgId);
    extendRule(json, 'PAGE_CUSTOM_FORM_ID', 1, formId);
    this.props.dispatch({
      type: 'app/getBtnList',
      payload: json,
      onComplete: (ret) => {
        if (ret) {
          this.setState({
            btns: ret,
          });
        }
      }
    });
  }
}

export default ComponentBase;
