<template>
  <div style="width: 100%">
    <dict-checkbox
      :valueType="valueType"
      v-model:value="dataValue"
      @change="dataValueChange"
      :dictTypeId="props.record.formItemSelect.dictTypeId"
      :disabled="readonly || disabled"
      ref="selectRef"
      type="user"
    ></dict-checkbox>
  </div>
</template>

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

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

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

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

// 类型
const valueType = computed(() => {
  if (props.record?.formItemSelect?.dictValueType) {
    return props.record.formItemSelect.dictValueType == 1 ? 'dictId' : 'dictCode';
  }
  return 'dictId';
});

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

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

// 更改值
const dataValueChange = () => {
  emits('update:value', JSON.stringify(dataValue.value));
  emits('onChange', props.record);
};

watch(
  () => props.value,
  val => {
    setDataValue();
  },
  { 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>
