<template>
  <div class="form-item-box">
    <el-select v-model="province" clearable placeholder="请选择省份">
      <el-option v-for="item in areas" :value="item.code" :label="item.name" :key="item.code">{{ item.name }}
      </el-option>
    </el-select>
    <el-select clearable :disabled="!province" style="margin: 0 10px" v-model="city" placeholder="请选择城市">
      <el-option v-for="item in selectCity" :value="item.code" :label="item.name" :key="item.code">{{ item.name }}
      </el-option>
    </el-select>
    <el-select clearable :disabled="!province || !city" v-model="area" placeholder="请选择区域">
      <el-option v-for="item in selectArea" :value="item.code" :label="item.name" :key="item.code">{{ item.name }}
      </el-option>
    </el-select>
  </div>
</template>

<script setup>
import allAreas from "@/constant/pca-code.json";
import {
  ref,
  defineProps,
  defineEmits,
  defineExpose,
  computed,
  watch
} from "vue";
const props = defineProps({
  //获取组件传值
  placeholder: {
    default: "请选择省市区",
    type: String
  },
  modelValue: {
    default: "",
    type: String
  }
});

let province = ref("");
let city = ref("");
let area = ref("");
let areas = ref(allAreas);

let selectCity = ref([]);
let selectArea = ref([]);
//分发事件给父组件
//分发事件给父组件
const emits = defineEmits(["update:modelValue"]);
//监听省份变化
watch(
  () => province.value,
  (val) => {
    if (val) {
      let cities = areas.value.find(
        (item) => item.code === province.value
      )?.children;
      selectCity.value = cities;
    }
    city.value = "";
    area.value = "";
  }
);

//监听城市变化
watch(
  () => city.value,
  (val) => {
    if (val) {
      let area = selectCity.value.find(
        (item) => item.code === city.value
      )?.children;
      selectArea.value = area;
    }
    area.value = "";
  }
);

//监听区域变化
watch(
  () => area.value,
  (val) => {
    let provinceData = {
      code: province.value,
      name:
        province.value &&
        allAreas.find((item) => item.code === province.value).name
    };
    let cityData = {
      code: city.value,
      name:
        city.value &&
        selectCity.value &&
        selectCity.value.find((item) => item.code === city.value).name
    };
    let areaData = {
      code: val,
      name:
        val &&
        selectArea.value &&
        selectArea.value.find((item) => item.code === val).name
    };
    emits("update:modelValue", `${provinceData},${cityData},${areaData}`);
  }
);
</script>

<style lang="scss" scoped>
</style>
