<template>
  <span v-if="!editable" :title="dictLabel">{{ dictLabel }}</span>
  <span v-if="editable">
    <el-select-v2
      v-model="dictValue"
      :options="dictOptions"
      size="small"
      collapseTags
      :fitInputWidth="false"
      @change="onSelectChange"
      v-bind="$attrs"
    >
    </el-select-v2>
  </span>
</template>
<script setup lang="ts">
import { ref, onMounted, watchEffect } from 'vue';
import { CommonStore } from '@/stores/common';

const commonStore = CommonStore();
interface Props {
  modelValue?: string | number;
  dictName?: any;
  options?: any;
  editable?: boolean;
}

const props = withDefaults(defineProps<Props>(), {
  modelValue: '',
  dictName: '',
  options: () => [],
  editable: false,
});
const emits = defineEmits(['update:modelValue', 'ok']);

const dictValue: any = ref('');
const dictLabel = ref('');
const dictOptions: any = ref([]);
onMounted(() => {
  if (props.dictName) {
    const res: any = commonStore.getDictData(props.dictName);
    dictOptions.value = res.A;
  } else if (props.options) {
    dictOptions.value = props.options;
  }
  if (props.modelValue && typeof props.modelValue === 'string' && props.modelValue.includes(',')) {
    dictValue.value = props.modelValue.split(',');
  } else {
    dictValue.value = String(props.modelValue ?? '');
  }
  calcDictLabelFun();
});

const calcDictLabelFun = () => {
  const options = dictOptions.value || [];
  const value = dictValue.value;
  let label = '';
  if (value && typeof value === 'string') {
    if (value.includes(',')) {
      const valueArr = value.split(',');
      const dicts: any = [];
      valueArr.forEach((value: any) => {
        const dict = options.find((item: any) => item.value === value);
        dicts.push(dict);
      });
      label = dicts.map((dict: any) => dict.label).join(',');
    } else {
      const dict: any = options.find((item: any) => item.value === value);
      if (dict) {
        label = dict.label;
      }
    }
  } else if (Array.isArray(value)) {
    const valueArr = value;
    const dicts: any = [];
    valueArr.forEach((value: any) => {
      const dict = options.find((item: any) => item.value === value);
      dicts.push(dict);
    });
    label = dicts.map((dict: any) => dict?.label).join(',');
  }
  dictLabel.value = label;
};
const onSelectChange = (val: any) => {
  let newVal = val;
  if (Array.isArray(val)) {
    newVal = val.join(',');
  }
  emits('update:modelValue', newVal);
};
watchEffect(() => {
  if (props.options && props.options.length > 0) {
    dictOptions.value = props.options;
    calcDictLabelFun();
  }
});
watchEffect(() => {
  const val = props.modelValue;
  if (val && typeof val === 'string' && val.includes(',')) {
    dictValue.value = val.split(',');
  } else {
    dictValue.value = String(val ?? '');
  }
  calcDictLabelFun();
});
</script>
