import { useVModel } from "@vueuse/core";
import { ElOption, ElSelect } from "element-plus";
import { defineComponent, ref, unref } from "vue";
import { RemoteSelectProps } from "./types";
import { useResponseHandle } from "/@/hooks";

const RemoteSelect = defineComponent({
  name: "RemoteSelect",
  props: RemoteSelectProps,
  emits: ["listChange", "itemChange"],
  setup(props, { emit }) {
    const value = useVModel(props, "value");

    const responseHandle = useResponseHandle();

    const list = ref<Array<any>>([]);

    const loading = ref(false);

    async function remoteMethod(val: string) {
      if (!val) return;
      const { responseLabelProp, responseValProp, requestProp, api } = props;

      loading.value = true;
      const { code, data, message } = await api({
        [requestProp ? requestProp : responseLabelProp]: val
      });

      responseHandle({
        code,
        message,
        handler: () => {
          list.value = data.list.map(i => ({
            label: i[responseLabelProp],
            value: i[responseValProp]
          }));

          emit("listChange", unref(list));
        }
      });

      loading.value = false;
    }

    return () => (
      <ElSelect
        v-model={value.value}
        placeholder={props.placeholder}
        remoteMethod={remoteMethod}
        loading={loading.value}
        reserveKeyword
        filterable
        clearable
        remote
        onChange={() => emit("itemChange")}
      >
        {list.value.map((item, index) => (
          <ElOption label={item.label} key={index} value={item.value} />
        ))}
      </ElSelect>
    );
  }
});

export default RemoteSelect;
