import React, { Component } from 'react';
import {
  WeaInput,
  WeaTools,
  WeaLocaleProvider,
} from 'ecCom';
import {message} from 'antd';

const {getLabel} = WeaLocaleProvider;

// 自定义转换类
export default class CustomClass extends Component {
  constructor(props) {
    super(props);
    props.getInstance && props.getInstance(this);
    this.state = {
      errorMsg: '',
    }
  }

  componentDidMount() {
    this.setState({
      errorMsg: '',
    });

    // 对于历史数据进行兼容性处理
    const {
      record,
    } = this.props;

    if(record.customsql && record.customsql.trim()) {
      this.checkCustomClassVal(record.customsql.trim());
    }
  }
  
  // 检测自定义转换类是否有效
  checkCustomClassVal = (classpath, show) => {
    WeaTools.callApi('/api/integration/workflowtrigger/getTriggerOperation', 'POST', {operate: "checkCustomClass", classpath}).then(result => {
      let errorMsg = result.errorMsg ? result.errorMsg.trim() : "";

      this.setState({
        errorMsg,
      })

      if(show && errorMsg) {
        message.error(errorMsg);
      }
    })
  }

  render() {
    const {
      record,
    } = this.props;

    return (
      <WeaInput
        ecId={`${this && this.props && this.props.ecId || ''}_WeaInput@0nerjb`}
        viewAttr={3}
        value={record.customsql}
        style={{width: 200}}
        onChange={this.handleChangeValue}
        onBlur={this.handleBlur}
      />
    )
  }

  // 自定义转换类失去焦点的时候检测输入值是否合法
  handleBlur = () => {
    const {
      record,
    } = this.props;

    if(record.customsql && record.customsql.trim()) {
      this.checkCustomClassVal(record.customsql.trim(), true);
    }
  }

  // 自定义转换类变化时传值
  handleChangeValue = (value) => {
    const {
      record,
      datas=[],
      onChange,
    } = this.props;

    let changeAfterDatas = datas && datas.map(data => {
      if(data.fieldid === record.fieldid) {
        data.customsql = value;
      }
      return data;
    })

    // 调用父组件中的onchange方法改变值
    if(onChange && typeof(onChange) === "function") {
      onChange(changeAfterDatas);
    }
  }

  // 校验必填
  onSave = () => {
    const {
      record,
    } = this.props;

    if(!record.customsql) {
      message.error(getLabel('529955','自定义转换类必填'));
      return false;
    }

    if(this.state.errorMsg) {
      message.error(this.state.errorMsg);
      return false;
    }

    return true;
  }
}
