<template>
  <el-row>
    <el-form-item label="区域查询"
      prop="region">
      <el-radio-group v-model="queryParams.region"
        @change="changeRegion">
        <el-radio-button label="全国"
          value="全国" />
        <el-radio-button label="省"
          value="省" />
        <el-radio-button label="省-市"
          value="省-市" />
      </el-radio-group>
    </el-form-item>
    <el-form-item label="省份"
      prop="provinceId"
      v-show="queryParams.region !== '全国'">
      <el-select v-model="queryParams.provinceId"
        placeholder="请选择省"
        @change="selProvince"
        filterable
        clearable>
        <el-option v-for="item in provinceList"
          :key="item.value"
          :label="item.label"
          :value="item.value" />
      </el-select>
    </el-form-item>
    <el-form-item label="城市"
      prop="cityId"
      v-show="queryParams.region === '省-市'">
      <el-select v-model="queryParams.cityId"
        placeholder="请选择市"
        @change="selCity"
        filterable
        clearable>
        <el-option v-for="item in cityList"
          :key="item.value"
          :label="item.label"
          :value="item.value" />
      </el-select>
    </el-form-item>
  </el-row>
</template>

<script setup>
import { getProCityAPI } from '@/api'

const props = defineProps({
  queryParams: {
    type: Object,
    default: () => ({})
  }
})

const emits = defineEmits(["change"])

const provinceList = ref([])
const cityList = ref([])
const getProCityList = async () => {
  const { data } = await getProCityAPI(props.queryParams)
  const list = data.map(item => ({
    label: item.name,
    value: item.num
  }))
  props.queryParams.provinceId ? (cityList.value = list) : (provinceList.value = list)
}
getProCityList()
// 切换省市范围
const changeRegion = async () => {
  if (props.queryParams.region === '全国') {
    props.queryParams.provinceId = ''
    props.queryParams.provinceName = ''
    props.queryParams.cityId = ''
    props.queryParams.cityName = ''
  } else if (props.queryParams.region === '省') {
    props.queryParams.cityId = ''
    props.queryParams.cityName = ''
  }
  emits('change')
}
// 选择省
const selProvince = async () => {
  // 设置省名
  props.queryParams.provinceName = provinceList.value.find(item => item.value === props.queryParams.provinceId)?.label
  // 重置城市
  props.queryParams.cityId = ''
  props.queryParams.cityName = ''
  cityList.value = []
  // 重新获取城市列表以及查询列表
  getProCityList()
  emits('change')
}
// 选择市
const selCity = async () => {
  // 设置市名
  props.queryParams.cityName = cityList.value.find(item => item.value === props.queryParams.cityId)?.label
  // 重新获取查询列表
  emits('change')
}
</script>