<template>
  <div>
    <!-- 字典下拉 -->
    <dict-select
      :valueType="record.formItemSelect.dictValueType == 1 ? 'dictId' : 'dictCode'"
      v-model:value="dataValue"
      :dictTypeId="record.formItemSelect.dictTypeId"
      :disabled="readonly || disabled"
      :placeholder="props.record?.placeholderContent || props.placeholder"
      :multiple="props.record?.itemMultipleChoiceFlag"
      @change="dataValueChange"
      ref="selectRef"
      type="user"
    ></dict-select>
  </div>
</template>

<script setup name="FormSelect">
import { ref, onMounted, watch } from 'vue';
import { isNumber } from '@/utils/common/util';

const props = defineProps({
  value: {
    type: [String, Number],
    default: ''
  },
  //当前行数据
  record: {
    type: Object,
    default: {}
  },
  //是否禁用
  disabled: {
    type: Boolean,
    default: false
  },
  placeholder: {
    type: String,
    default: '请选择'
  },
  // 是否只读
  readonly: {
    type: Boolean,
    default: false
  }
});

const emits = defineEmits(['update:value', 'onChange']);

// 选中的值
const dataValue = ref('');
// ref
const selectRef = ref();

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

// 更改值
const dataValueChange = () => {
  let data = null;
  if (props.record?.itemMultipleChoiceFlag) {
    if (dataValue.value?.length == 0) {
      data = '';
    } else {
      data = JSON.stringify(dataValue.value);
    }
  } else {
    data = dataValue.value;
  }
  emits('update:value', data);
  emits('onChange', props.record);
};

const setValueData = () => {
  // 多选
  if (props.record?.itemMultipleChoiceFlag) {
    if (props.value) {
      let arr = JSON.parse(props.value) || [];
      dataValue.value = arr.map(item => isNumber(item) ? item.toString() : item);
    } else {
      dataValue.value = [];
    }
  } else {
    dataValue.value = isNumber(props.value) ? props.value.toString() : props.value;
  }
  dataValueChange();
};

watch(
  () => props.value,
  val => {
    setValueData();
  },
  { deep: true }
);

watch(
  () => selectRef.value?.dictList,
  val => {
    props.record.dictList = val;
  },
  { deep: true, immediate: true }
);

watch(
  () => props.record.dictList,
  val => {
    if (val) {
      selectRef.value.dictList = val;
    }
  },
  { deep: true }
);
</script>

<style></style>
