<template>
  <t-select
    v-model="valueData"
    :options="options"
    :multiple="isMultiple"
    :disabled="!config.writable"
    filterable
    @change="emitChange"
  ></t-select>
</template>
<script setup name="SELECT">
import { ref, onMounted, computed, watch } from 'vue';
import { request } from '@/utils/request.js';

const props = defineProps({
  config: { type: Object },
  modelValue: { type: [String, Array] },
  sop: { type: Object, default: () => ({}) },
});
const emit = defineEmits(['update:modelValue', 'change']);

const valueData = ref(null);
const isMultiple = computed(() => {
  return props.config.code === 'MULTIPLE_SELECT';
});

const options = ref([]);
const getOptionsApi = () => {
  let dataGrid = props.config?.dataGrid;
  if (props.config?.formId === 'engineer_users_id_1') {
    dataGrid = dataGrid.replace('#{id}', props.sop?.crmDetailId);
  }
  return request({
    url: dataGrid,
    method: 'post',
  });
};
const getOptions = async () => {
  if (props.config.options) {
    let data = props.config.options;
    if (typeof data === 'string') {
      data = JSON.parse(data);
    }
    options.value = data;
    return;
  }

  if (!props.config.dataGrid) return;
  const data = await getOptionsApi();
  console.log('data', data);
  options.value = data || [];
  if (props.config?.formId === 'engineer_users_id_1') {
    options.value = options.value.map((item) => {
      return {
        label: `${item.name}(${item.archivesRoleName})_${item.supplierName}_${item.mobileNumber}`,
        value: item.userId,
      };
    });
  }
};

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

const emitChange = () => {
  emit('update:modelValue', valueData.value);
  emit('change', valueData.value);
};

watch(
  () => props.modelValue,
  (val, oldval) => {
    if (val === oldval) return;
    valueData.value = val || (isMultiple.value ? [] : '');
  },
  {
    immediate: true,
  }
);
</script>
