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", "itenDetail"],
  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: () => {
          const _data = props.isRoot ? data : data.list;

          list.value = _data.map(item => ({
            ...item,
            label: item[responseLabelProp],
            value: item[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
        style={{
          wdith: props.width ? props.width + "px" : ""
        }}
        onChange={val => {
          emit(
            "itemChange",
            list.value.find(i => i.value === val)
          );
        }}
      >
        {list.value.map((item, index) => (
          <ElOption label={item.label} key={index} value={item.value} />
        ))}
      </ElSelect>
    );
  }
});

export default RemoteSelect;
