<template>
  <div class="select-city">
    <el-select clearable filterable allow-create :placeholder="placeholder" @change="getCityData" v-model="showModel" style="width: 100%">
      <el-option v-for="item in data" :label="item.name" :value="item.id"> </el-option>
    </el-select>
  </div>
</template>
<script setup>
import { reactive, ref } from "vue";
const { proxy } = getCurrentInstance();
const showModel = ref("");
const emit = defineEmits(["update:modelValue", "change"]);
const formData = computed(() => {
  return proxy.modelValue;
});
defineProps({
  placeholder: {
    type: String,
    default: false,
  },
  addressId: {
    type: String,
    default: false,
  },
  addressName: {
    type: String,
    default: false,
  },
  modelValue: {
    type: String,
    default: false,
  },
  data: {
    type: Array,
    default: false,
  },
});
//监听modelValue的变化
watch(
  formData.value,
  (val) => {
    // console.log(formData.value[proxy.addressId || 'provinceId'],formData.value[proxy.addressName || 'provinceName'])
    if (!formData.value[proxy.addressId || "provinceId"] && !formData.value[proxy.addressName || "provinceName"]) {
      showModel.value = "";
    } else {
      showModel.value = formData.value[proxy.addressId || "provinceId"] || formData.value[proxy.addressName || "provinceName"];
    }
  },
  {
    immediate: true,
  }
);

const getCityData = (val) => {
  let isAddCity = true;
  //判断val是否在data里面
  proxy.data.forEach((item) => {
    if (item.id == val) {
      isAddCity = false;
      formData.value[proxy.addressId || "provinceId"] = item.id;
      formData.value[proxy.addressName || "provinceName"] = item.name;
      console.log(formData.value);
      emit("update:modelValue", formData.value);
      showModel.value = item.id;
      emit("change", item.id);
    }
  });
  if (isAddCity) {
    formData.value[proxy.addressId || "provinceId"] = null;
    formData.value[proxy.addressName || "provinceName"] = val;
    showModel.value = val;
    emit("update:modelValue", formData.value);
    emit("change", val);
  }
};
</script>
