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

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

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

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

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

watch(
  () => props.modelValue,
  (val: any) => {
    choseData.value = val;
  },
  { deep: true, immediate: true }
);

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

const getlistDataFun = () => {
  const params = {
    templatePrefix: props.attrs.templatePrefix || '',
  };
  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]) {
        choseData.value = build[0].value;
        emit('update:modelValue', choseData.value);
      }
    }
  });
};

const changeFun = () => {
  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>
