import React from "react";
import { Select } from "@alifd/next";
import { event } from "@alilc/lowcode-engine";

interface MappedSelectSetterProps {
  value: any;
  onChange: (val: string) => void;
  field: any;
}

export default class MappedSelectSetter extends React.PureComponent<
  MappedSelectSetterProps,
  any
> {
  state = {
    options: [],
    selectedOpt: "",
  };

  componentDidMount() {
    const { field, value } = this.props;
    const initData = field.parent.getPropValue("data");
    const initOptions: any[] = [];
    if (initData.length > 0) {
      Object.keys(initData[0]).forEach((e) => {
        initOptions.push({ label: e, value: e });
      });
    }
    this.setState({ options: initOptions, selectedOpt: value });
  }

  render() {
    const { field, onChange } = this.props;
    event.on("common:FieldsMapping", () => {
      this.setState({
        options: field.parent.getPropValue("fieldOptions"),
        selectedOpt: "",
      });
    });
    return (
      <Select.AutoComplete
        style={{ width: "100%" }}
        dataSource={this.state.options}
        value={this.state.selectedOpt}
        placeholder="请选择/输入"
        onChange={(e) => {
          this.setState({ selectedOpt: e });
          onChange(e);
        }}></Select.AutoComplete>
    );
  }
}
