<template>
  <div class="wh100">
    <a-cascader
      v-model:value="dataValue"
      :options="options"
      :show-search="{ filter }"
      @change="dataValueChange"
      @blur="dataValueBlur"
      @focus="dataValueFocus"
      @click="dataValueClick"
      :disabled="props.readonly || props.disabled"
      :placeholder="props.record?.placeholderContent || props.placeholder"
    />
  </div>
</template>

<script setup name="CityComponent">
import { ref, onMounted, watch } from 'vue';
import { regionData } from 'element-china-area-data';
const props = defineProps({
  value: {
    type: [String, Array],
    default: ''
  },
  //是否禁用
  disabled: {
    type: Boolean,
    default: false
  },
  // 当前行数据
  record: {
    type: Object,
    default: {}
  },
  placeholder: {
    type: String,
    default: '请选择'
  },
  // 是否只读
  readonly: {
    type: Boolean,
    default: false
  },
  // 是否正常保存，不是转json格式
  normal: {
    type: Boolean,
    default: false
  }
});

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

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

// 数据列表
const options = ref(regionData);

onMounted(() => {
  if (props.value) {
    dataValue.value = props.normal ? props.value : JSON.parse(props.value);
  } else {
    dataValue.value = [];
  }
});

// 过滤
const filter = (inputValue, path) => {
  return path.some(option => option.label.toLowerCase().indexOf(inputValue.toLowerCase()) > -1);
};

watch(
  () => props.value,
  val => {
    if (props.value) {
      dataValue.value = props.normal ? props.value : JSON.parse(props.value);
    } else {
      dataValue.value = [];
    }
  },
  { deep: true }
);

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

const dataValueClick = () => {
  emits('onClick', props.record);
}

const dataValueBlur = () => {
  emits('onBlur', props.record);
}

const dataValueFocus = () => {
  emits('onFocus', props.record);
}
</script>

<style></style>
