import { ElOption, ElSelect } from "element-plus";
import { defineComponent, ref, unref, computed, onMounted } from "vue";
import { RemoteSelectProps } from "./types";
import { useResponseHandle } from "/@/hooks/useAsync";

const RemoteSelect = defineComponent({
  name: "RemoteSelect",
  props: RemoteSelectProps,
  emits: ["listChange", "itemChange", "itenDetail", "update:value", "inital"],
  setup(props, { emit, expose }) {
    const value = computed({
      get() {
        return props.value;
      },
      set(newVal) {
        emit("update:value", newVal);
      }
    });

    const responseHandle = useResponseHandle();

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

    const loading = ref(false);

    async function initalData(params) {
      const { responseLabelProp, responseValProp, subLabelProp, api } = props;

      loading.value = true;

      const model = {
        page: 1,
        size: 100,
        ...params
      };
      const { code, data, message } = await api(model);
      loading.value = false;

      responseHandle({
        code,
        message,
        handler: () => {
          const _data = props.isRoot ? data : data[props.prop];

          list.value = _data.map(item => ({
            ...item,
            status: item.status + "",
            label: item[responseLabelProp] ? item[responseLabelProp] + "" : "",
            value: item[responseValProp] ? item[responseValProp] + "" : "",
            subLabel: item[subLabelProp] ? item[subLabelProp] + "" : ""
          }));
          if (!props.isRoot) {
            value.value = list.value[0][responseValProp]
              ? list.value[0][responseValProp] + ""
              : "";
            emit(
              "inital",
              list.value[0][responseValProp]
                ? list.value[0][responseValProp] + ""
                : ""
            );
          }
        }
      });
    }

    async function remoteMethod(val: string) {
      if (!val) return;
      const {
        responseLabelProp,
        responseValProp,
        requestProp,
        subLabelProp,
        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[props.prop];

          list.value = _data.map(item => ({
            ...item,
            label: item[responseLabelProp] ? item[responseLabelProp] + "" : "",
            value: item[responseValProp] ? item[responseValProp] + "" : "",
            subLabel: item[subLabelProp] ? item[subLabelProp] + "" : "",
            status: item.status + ""
          }));

          emit("listChange", unref(list));
        }
      });
      console.log(list.value);
      console.log(props);
      loading.value = false;
    }
    onMounted(() => remoteMethod(""));
    expose({
      initalData
    });

    return () => (
      <ElSelect
        class="w-full"
        v-model={value.value}
        placeholder={props.placeholder}
        remoteMethod={remoteMethod}
        loading={loading.value}
        disabled={props.disabled}
        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 => (
          <ElOption
            label={
              item.subLabel ? item.label + " - " + item.subLabel : item.label
            }
            key={item.value}
            value={item.value}
            disabled={props.showDisabled ? item.status + "" === "0" : false}
          >
            <span style="float: left">{item.label}</span>

            <span style="float: right;color: var(--el-text-color-secondary);font-size: 13px;">
              {item.subLabel}
            </span>
          </ElOption>
        ))}
      </ElSelect>
    );
  }
});

export default RemoteSelect;
