import * as React from "react";
import InputLabel from "@mui/material/InputLabel";
import MenuItem from "@mui/material/MenuItem";
import FormControl from "@mui/material/FormControl";
import FormHelperText from "@mui/material/FormHelperText";
import Select, { SelectProps } from "@mui/material/Select";

export interface IOption {
  label: string;
  value: string;
  disabled?: boolean;
}

export const optionsTransform = (
  arr: Array<any>,
  labelKey: string = "label",
  valueKey: string = "value",
  disabledKey: string = "disabled"
): Array<IOption> => {
  return arr.map((item: any) => {
    return {
      label: item[labelKey],
      value: item[valueKey],
      disabled: item[disabledKey],
    };
  });
};

interface IProps
  extends Omit<SelectProps, "value" | "options" | "onChange" | "title"> {
  value?: any;
  options: IOption[];
  onChange?: any;
  /** 类型变种 */
  variant?: "standard" | "outlined" | "filled";
  /** title */
  title?: string;
  /** 是否显示title */
  isTitle?: boolean;
  size?: "small" | "medium";
  multiple?: boolean; // 多选
  error?: boolean;
  helpertext?: string;
}
export default function MySelect(props: IProps) {
  const {
    value,
    options,
    onChange,
    title,
    isTitle = false,
    variant,
    size = "small",
    multiple = false,
    error = false,
    helpertext,
  } = props;

  return (
    <FormControl fullWidth variant={variant} error={error}>
      {isTitle ? (
        <InputLabel id="demo-simple-select-label">
          {title || "请选择"}
        </InputLabel>
      ) : null}
      <Select
        labelId="demo-simple-select-label"
        id="demo-simple-select"
        label={title || ""}
        size={size}
        {...props}
        value={value}
        onChange={onChange}
        multiple={multiple}
      >
        {options.length
          ? options?.map((item: IOption) => {
              return (
                <MenuItem
                  key={item.value}
                  value={item.value}
                  disabled={item?.disabled}
                >
                  {item.label}
                </MenuItem>
              );
            })
          : null}
      </Select>
      {helpertext && error && <FormHelperText>{helpertext}</FormHelperText>}
    </FormControl>
  );
}
