<template>
  <el-cascader
    v-model="innerCodes"
    :options="regionOptions"
    :props="cascaderProps"
    :placeholder="placeholder"
    :disabled="disabled"
    clearable
    filterable
    style="width: 100%"
    @change="handleChange"
  />
</template>

<script>
import { regionData, resolveRegionLabels } from "@/utils/chinaRegion"

export default {
  name: "RegionCascader",
  props: {
    provinceCode: { type: String, default: "" },
    provinceName: { type: String, default: "" },
    cityCode: { type: String, default: "" },
    cityName: { type: String, default: "" },
    countyCode: { type: String, default: "" },
    countyName: { type: String, default: "" },
    placeholder: { type: String, default: "请选择省/市/县" },
    disabled: { type: Boolean, default: false }
  },
  data() {
    return {
      regionOptions: regionData,
      cascaderProps: { value: "value", label: "label", children: "children" },
      innerCodes: []
    }
  },
  watch: {
    provinceCode: { handler: "syncFromProps", immediate: true },
    cityCode: { handler: "syncFromProps" },
    countyCode: { handler: "syncFromProps" }
  },
  methods: {
    syncFromProps() {
      if (this.provinceCode && this.cityCode && this.countyCode) {
        const next = [this.provinceCode, this.cityCode, this.countyCode]
        if (JSON.stringify(next) !== JSON.stringify(this.innerCodes)) {
          this.innerCodes = next
        }
      } else if (!this.provinceCode && !this.cityCode && !this.countyCode) {
        this.innerCodes = []
      }
    },
    handleChange(codes) {
      if (!codes || codes.length < 3) {
        this.emitRegion({}, {})
        return
      }
      const labels = resolveRegionLabels(codes)
      this.emitRegion(
        { provinceCode: codes[0], cityCode: codes[1], countyCode: codes[2] },
        { provinceName: labels[0] || "", cityName: labels[1] || "", countyName: labels[2] || "" }
      )
    },
    emitRegion(codeMap, nameMap) {
      this.$emit("update:provinceCode", codeMap.provinceCode || "")
      this.$emit("update:provinceName", nameMap.provinceName || "")
      this.$emit("update:cityCode", codeMap.cityCode || "")
      this.$emit("update:cityName", nameMap.cityName || "")
      this.$emit("update:countyCode", codeMap.countyCode || "")
      this.$emit("update:countyName", nameMap.countyName || "")
      this.$emit("change", { ...codeMap, ...nameMap })
    }
  }
}
</script>
