<template>
  <div class="comp-content">
    <el-select-v2
      class="select"
      v-model="choseData"
      :options="listData"
      :placeholder="disabled ? '' : '请选择'"
      filterable
      clearable
      :multiple="multiple"
      :disabled="disabled"
      @change="changeFun"
      @clear="clearFun"
    />
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted, watch } from 'vue';
import { systemApproveQueryApproveFlowTempalteApi } from '@/api/system/systemApprove';
import { debounce } from 'lodash-es';

interface Props {
  modelValue: string;
  disabled?: boolean;
  multiple?: boolean;
  attrs?: any;
}

const props = withDefaults(defineProps<Props>(), {
  modelValue: '',
  disabled: false,
  multiple: false,
  attrs: {},
});
const listData = ref<any>([]);
const choseData = ref<any>([]);

const emit = defineEmits(['update:modelValue', 'change', 'clear']);

watch(
  () => props.modelValue,
  (val: any) => {
    if (props.multiple) {
      choseData.value = val ? String(val).split(',') : [];
    } else {
      choseData.value = val;
    }
  },
  { deep: true, immediate: true }
);

onMounted(() => {
  getlistDataFun();
});

const getlistDataFun = () => {
  const params = {
    moduleCode: props.attrs.moduleCode || '',
  };
  systemApproveQueryApproveFlowTempalteApi(params).then((res: any) => {
    if (res.code === 200) {
      const build = res.data.map((item: any) => {
        return {
          value: item.templateId,
          label: item.templateName,
        };
      });
      listData.value = build;
      if (build[0]) {
        if (!props.multiple) {
          choseData.value = build[0].value;
          changeFun();
        }
      }
    }
  });
};

const multiplyChangeFun = debounce(() => {
  const ids = choseData.value.join(',');
  emit('update:modelValue', ids);
  const changeData: any[] = [];
  listData.value.forEach((item: any) => {
    if (choseData.value.includes(item.value)) {
      changeData.push(item);
    }
  });
  emit('change', changeData);
}, 500);

const changeFun = () => {
  if (props.multiple) {
    multiplyChangeFun();
  } else {
    emit('update:modelValue', choseData.value);
    let changeData: any = {};
    listData.value.some((item: any) => {
      if (choseData.value === item.value) {
        changeData = item;
        return true;
      }
    });
    emit('change', changeData);
  }
};

const clearFun = () => {
  emit('clear');
};
</script>

<style lang="scss" scoped>
.comp-content {
  width: 100%;
  .select {
    width: 100%;
  }
}
</style>
