<template>
	<div class="chinese-region-selector">
		<el-select v-model="selectedCountry" placeholder="选择国家" filterable class="!w-48" @change="onCountryChange">
			<el-option-group v-if="props.showAll !== false" label="全部">
				<el-option :label="'全部国家'" :value="ALL_COUNTRY" />
			</el-option-group>
			<el-option-group v-for="continent in continentOptions" :key="continent.label" :label="continent.label">
				<el-option v-for="country in continent.countries" :key="country.code" :label="country.name"
					:value="country.code" />
			</el-option-group>
		</el-select>

		<el-select v-if="selectedCountry && selectedCountry !== ALL_COUNTRY && states.length > 0"
			v-model="selectedState" placeholder="选择省份/州" filterable class="!w-48 ml-2" @change="onStateChange">
			<el-option-group v-if="props.showAll !== false" label="全部">
				<el-option :label="'全部省/州'" :value="ALL_STATE" />
			</el-option-group>
			<el-option v-for="state in states" :key="state.code" :label="state.name" :value="state.code" />
		</el-select>

		<el-select v-if="selectedState && selectedState !== ALL_STATE && cities.length > 0" v-model="selectedCity"
			placeholder="选择城市" filterable class="!w-48 ml-2">
			<el-option-group v-if="props.showAll !== false" label="全部">
				<el-option :label="'全部城市'" :value="ALL_CITY" />
			</el-option-group>
			<el-option v-for="city in cities" :key="city.code" :label="city.name" :value="city.name" />
		</el-select>

		<el-button v-if="(props.showAll !== false) || selectedCountry" type="primary" size="small" class="ml-2"
			@click="addRegion">
			添加地区
		</el-button>
	</div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { State, City } from 'country-state-city';
import regionData from './region-data.json';

interface RegionData {
	country: string;
	state?: string;
	city?: string;
	code: string;
}

const props = defineProps<{
	modelValue?: RegionData[];
	showAll?: boolean;
}>();

const emit = defineEmits<{
	'update:modelValue': [value: RegionData[]];
}>();

const continentOptions = ref<any[]>([]);
const selectedCountry = ref('');
const selectedState = ref('');
const selectedCity = ref('');
const states = ref<any[]>([]);
const cities = ref<any[]>([]);
const countryCode = ref('');
const ALL_COUNTRY = '__ALL_COUNTRY__';
const ALL_STATE = '__ALL_STATE__';
const ALL_CITY = '__ALL_CITY__';

// 预定义的中文国家数据
const countriesData = (regionData as any).countriesData;

// 中国省份数据
const chinaProvinces = (regionData as any).chinaProvinces;

// 中国主要城市数据
const chinaCities: { [key: string]: string[] } = (regionData as any).chinaCities;

// （已移除未使用的美国州静态数组）

// 其他国家的主要省份/州
const otherStates: { [key: string]: string[] } = (regionData as any).otherStates;

// 其他国家的主要城市数据
const otherCities: { [key: string]: { [key: string]: string[] } } = (regionData as any).otherCities;

// 美国州中文映射（ISO/英文名 -> 中文名）
const usStateZhMap: Record<string, string> = (regionData as any).usStateZhMap;

// 美国常见城市中文映射（按州代码 -> 英文名到中文名）
const usCityZhMap: Record<string, Record<string, string>> = (regionData as any).usCityZhMap;

// 初始化地区数据
const initRegionData = () => {
	// 按大洲分组
	const continentMap: { [key: string]: any[] } = {
		'亚洲': [],
		'欧洲': [],
		'北美洲': [],
		'南美洲': [],
		'大洋洲': [],
		'非洲': []
	};

	(regionData as any).countriesData.forEach((country: any) => {
		if (continentMap[country.continent]) {
			continentMap[country.continent].push(country);
		}
	});

	// 转换为数组格式
	continentOptions.value = Object.keys(continentMap).map(continent => ({
		label: continent,
		countries: continentMap[continent].sort((a, b) => a.name.localeCompare(b.name))
	}));
};

// 国家变化处理
const onCountryChange = (countryCodeValue: string) => {
	selectedState.value = '';
	selectedCity.value = '';
	cities.value = [];
	countryCode.value = countryCodeValue === ALL_COUNTRY ? '' : countryCodeValue;

	// 根据国家代码获取省份/州
	if (countryCodeValue === ALL_COUNTRY && props.showAll !== false) {
		states.value = [];
		cities.value = [];
		return;
	}

	if (countryCodeValue === 'CN') {
		states.value = ((regionData as any).chinaProvinces as string[]).map(name => ({ name, code: name }));
	} else if (countryCodeValue === 'US') {
		const usStates = State.getStatesOfCountry('US') || [];
		states.value = usStates.map((s: any) => ({ name: ((regionData as any).usStateZhMap || {})[s.name] || s.name, code: s.isoCode, enName: s.name }));
	} else if ((regionData as any).otherStates[countryCodeValue]) {
		states.value = (regionData as any).otherStates[countryCodeValue].map((name: string) => ({ name, code: name }));
	} else {
		states.value = [];
	}
};

// 省份变化处理
const onStateChange = (stateCodeOrName: string) => {
	selectedCity.value = '';

	// 根据国家和省份获取城市
	if (countryCode.value === 'CN') {
		const stateName = stateCodeOrName === ALL_STATE ? '' : stateCodeOrName;
		if (stateCodeOrName === ALL_STATE && props.showAll !== false) {
			cities.value = [];
			return;
		}
		if ((regionData as any).chinaCities[stateName]) {
			cities.value = (regionData as any).chinaCities[stateName].map((name: string) => ({ name, code: name }));
		} else {
			cities.value = [];
		}
		return;
	}

	if (countryCode.value === 'US') {
		// 加载美国州城市
		if (stateCodeOrName === ALL_STATE && props.showAll !== false) {
			cities.value = [];
			return;
		}
		// 优先使用内置中文城市表（按州中文名）
		const st = states.value.find((s: any) => s.code === stateCodeOrName);
		const zhStateName = st ? st.name : '';
		if ((regionData as any).otherCities['US'] && (regionData as any).otherCities['US'][zhStateName]) {
			cities.value = (regionData as any).otherCities['US'][zhStateName].map((name: string) => ({ name, code: name }));
			return;
		}

		let usCities = City.getCitiesOfState('US', stateCodeOrName) || [];
		if (!usCities.length) {
			// 兜底：按国家取所有城市再按州代码过滤
			const allUsCities = City.getCitiesOfCountry('US') || [];
			usCities = allUsCities.filter((c: any) => c.stateCode === stateCodeOrName);
		}
		const cityMap = ((regionData as any).usCityZhMap || {})[stateCodeOrName] || {};
		cities.value = usCities.map((c: any) => {
			const zhName = cityMap[c.name] || c.name;
			return { name: zhName, code: zhName };
		});
		return;
	}

	const stateName = stateCodeOrName;
	if ((regionData as any).otherCities[countryCode.value] && (regionData as any).otherCities[countryCode.value][stateName]) {
		cities.value = (regionData as any).otherCities[countryCode.value][stateName].map((name: string) => ({ name, code: name }));
	} else {
		cities.value = [];
	}
};

// （移除空的城市变更处理函数）

// 添加地区
const addRegion = () => {
	if (!selectedCountry.value && props.showAll === false) return;

	let countryName = '全部国家';
	let countryCodeFinal = '';
	if (selectedCountry.value && selectedCountry.value !== ALL_COUNTRY) {
		const country = ((regionData as any).countriesData as any[]).find((c: any) => c.code === countryCode.value);
		if (!country) return;
		countryName = country.name;
		countryCodeFinal = country.code;
	}

	const newRegion: RegionData = {
		country: countryName,
		code: countryCodeFinal
	};

	if (selectedState.value || (props.showAll !== false && selectedCountry.value && selectedState.value === ALL_STATE)) {
		if (countryCode.value === 'US') {
			const st = states.value.find((s: any) => s.code === selectedState.value);
			newRegion.state = selectedState.value === ALL_STATE ? '全部省/州' : (st ? st.name : selectedState.value);
		} else {
			newRegion.state = selectedState.value === ALL_STATE ? '全部省/州' : selectedState.value;
		}
	}

	if (selectedCity.value || (props.showAll !== false && selectedState.value && selectedCity.value === ALL_CITY)) {
		newRegion.city = selectedCity.value === ALL_CITY ? '全部城市' : selectedCity.value;
	}

	console.log('添加的地区数据:', newRegion);

	const currentRegions = props.modelValue || [];
	const newRegions = [...currentRegions, newRegion];
	
	emit('update:modelValue', newRegions);
	
	// 重置选择
	selectedCountry.value = '';
	selectedState.value = '';
	selectedCity.value = '';
	states.value = [];
	cities.value = [];
	countryCode.value = '';
};

// 组件挂载时初始化地区数据
onMounted(() => {
	initRegionData();
});
</script>

<style lang="scss" scoped>
.chinese-region-selector {
	display: flex;
	align-items: center;
	flex-wrap: wrap;
	gap: 8px;
}
</style>
