<template>
  <el-input v-model="inputValue" @input="disshow">
    <template #suffix>
      <el-icon class="el-input__icon" v-if="loading">
        <Loading />
      </el-icon>
      <el-icon v-else-if="successState" class="vxecol-green"><CircleCheckFilled /></el-icon>
      <el-icon v-else-if="errorState" class="vxecol-danger"><CircleCloseFilled /></el-icon>
      <el-icon v-else class="vxecol-gray" @click="openModal"><Search /></el-icon>
    </template>
  </el-input>
</template>

<script lang="ts" setup name="SelectorMtrldefSelect">
import { ref, computed, nextTick } from "vue";
import { GetERPMtrldefList } from "@/api/modules/common";
import { ElInput, ElIcon } from "element-plus";
import { Search, Loading, CircleCheckFilled, CircleCloseFilled } from "@element-plus/icons-vue";

import { useUserStore } from "@/stores/modules/user";
import { throttle } from "lodash-es";

interface ProTableProps {
  value?: any;
  valueKey?: string;
  searchKey?: any;
  row?: any;
  setMtrlerp?: any;
}

// 默认值
const props = withDefaults(defineProps<ProTableProps>(), {
  // valueKey: "mtrlid"
});

const inputValue = computed({
  get: () => props.value,
  set: val => emit("update:value", val)
});

const { userInfo } = useUserStore();
const emit = defineEmits(["select", "update:value", "openModal"]);
const loading = ref(false);
const successState = ref(false);
const errorState = ref(false);

const disshow = throttle(async (queryString: any) => {
  console.log("disshow props :>> ", props, queryString);
  loading.value = true;
  errorState.value = false;
  successState.value = false;

  let newParams: any = {};
  newParams.pageindex = 1;
  newParams.pagesize = 5;
  // newParams.mtrlid = props.mtrlid;
  if (props.searchKey) {
    newParams[props.searchKey] = queryString;
  } else {
    newParams.keyword = queryString;
  }
  console.log("newParams :>> ", newParams);
  let result = await GetERPMtrldefList(newParams);

  console.log("result.datatable :>> ", result.mtrldefList);

  loading.value = false;

  if (result.mtrldefList.length == 1) {
    // emit("select", result.mtrldefList[0]);
    props.setMtrlerp(props.row, result.mtrldefList[0], props.valueKey);
    successState.value = true;
    setTimeout(() => {
      successState.value = false;
    }, 1200);
  } else {
    props.setMtrlerp(props.row, {}, props.valueKey);
    // emit("select", {});
    errorState.value = true;
  }
}, 1500);

const openModal = (e: any) => {
  emit("openModal", e);
};
</script>
