/*
 * @Author: 吴永生#A02208 yongsheng.wu@wholion.com
 * @Date: 2021-12-04 15:46:25
 * @LastEditors: 吴永生#A02208 yongsheng.wu@wholion.com
 * @LastEditTime: 2022-06-11 18:22:50
 * @FilePath: /lionet-slb-pc/src/components/SearchView/components/Collapse.tsx
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import * as React from "react";
import Box from "@mui/material/Box";
import InputLabel from "@mui/material/InputLabel";
import MenuItem from "@mui/material/MenuItem";
import FormControl from "@mui/material/FormControl";
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?: IOption;
  options: IOption[];
  onChange?: (val: IOption) => void;
  /** 类型变种 */
  variant?: "standard" | "outlined" | "filled";
  /** title */
  title?: string;
  /** 是否显示title */
  isTitle?: boolean;
}
export default function MySelect(props: IProps) {
  const { value, options, onChange, title, isTitle = false, variant } = props;

  const handleChange = (event: any) => {
    const newValue = options?.filter((item) => {
      return item.value === event.target.value;
    });
    if (onChange) {
      onChange(newValue[0] || { label: "", value: "" });
    }
  };

  return (
    <Box sx={{ minWidth: 120 }}>
      <FormControl fullWidth variant={variant}>
        {isTitle ? (
          <InputLabel id="demo-simple-select-label">
            {title || "请选择"}
          </InputLabel>
        ) : null}
        <Select
          labelId="demo-simple-select-label"
          id="demo-simple-select"
          label={title || "请选择"}
          size="small"
          {...props}
          value={value?.value}
          onChange={handleChange}
        >
          {options.length
            ? options?.map((item: IOption) => {
                return (
                  <MenuItem value={item.value} disabled={item?.disabled}>
                    {item.label}
                  </MenuItem>
                );
              })
            : null}
        </Select>
      </FormControl>
    </Box>
  );
}
