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

const {getLabel} = WeaLocaleProvider;

// 自定义SQL转换规则
export default class CommonSql extends Component {
  constructor(props) {
    super(props);
    props.getInstance && props.getInstance(this);
    this.state = {
      datashowOptions: [],
    }
  }

  componentDidMount() {
    this.getDataSourceOptions();
  }
  
  // 获取数据源的下拉选择项
  getDataSourceOptions = () => {
    WeaTools.callApi('/api/integration/workflowtrigger/getTriggerOperation', 'POST', {operate: "getDatasource"}).then(result => {
      this.setState({datashowOptions: result.data || []});
    })
  }

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

    return (
      <div className="inte_workflow_trigger_rulespot_6">
        <span className="label" title={getLabel('18076','数据源')}>{getLabel('18076','数据源')}: </span>
        <WeaSelect 
          ecId={`${this && this.props && this.props.ecId || ''}_WeaSelect@lq2cqh`} 
          style={{width: 150}}
          options={this.state.datashowOptions || []}
          value={record.datasourceid}
          onChange={(value) => this.handleChangeValue(value, 'datasourceid')}
        />
        <WeaTextarea
          ecId={`${this && this.props && this.props.ecId || ''}_WeaTextarea@j9666q`}
          style={{width: 200}}
          minRows={2}
          maxRows={2}
          value={record.customsql}
          onChange={(value) => this.handleChangeValue(value, 'customsql')}
        />
      </div>
    )
  }

  // 数据源变化时传值
  handleChangeValue = (value, key) => {
    const {
      record,
      datas=[],
      onChange,
    } = this.props;

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

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

  // 校验自定义sql以select开始
  onSave = () => {
    const {
      record,
    } = this.props;

    if(record.rulesopt == "6" && record.customsql) {
      if(record.customsql.trim() && (!(record.customsql.trim().toLowerCase()).startsWith('select'))) {
        message.error(getLabel('514410','自定义SQL需要以select开始'));
        return false;
      }
    }
    return true;
  }
}




