<template>
	<div class="d-inline-block d-flex">
		<v-select
			v-model="entity.area2"
			@update:model-value="nextArea(entity.area2, 1)"
			@click:clear="clear(1)"
			:placeholder="user.areacode?.length >= 2 ? entity.name2 : '---省级---'"
			:items="areaData.area2"
			item-title="areaName"
			item-value="areaCode"
			class="d-inline-block sel_box mr-3"
			hide-details
			density="compact"
			variant="outlined"
			clearable
			:disabled="user.areacode?.length >= 2"
			:menu-props="{ offsetY: true }"
			:style="areaStyle"></v-select>
		<v-select
			v-if="maxArea >= 4"
			v-model="entity.area4"
			@update:model-value="nextArea(entity.area4, 2)"
			@click:clear="clear(2)"
			:placeholder="user.areacode?.length >= 4 ? entity.name4 : '---市级---'"
			:items="areaData.area4"
			item-title="areaName"
			item-value="areaCode"
			class="d-inline-block sel_box"
			:class="maxArea > 4 && 'mr-3'"
			hide-details
			density="compact"
			variant="outlined"
			clearable
			:disabled="user.areacode?.length >= 4"
			:menu-props="{ offsetY: true }"
			:style="areaStyle"></v-select>
		<v-select
			v-if="maxArea >= 6"
			v-model="entity.area6"
			@update:model-value="nextArea(entity.area6, 3)"
			@click:clear="clear(3)"
			:placeholder="user.areacode?.length >= 6 ? entity.name6 : '---区/县---'"
			:items="areaData.area6"
			item-title="areaName"
			item-value="areaCode"
			class="d-inline-block sel_box"
			:class="maxArea > 6 && 'mr-3'"
			hide-details
			density="compact"
			variant="outlined"
			clearable
			:disabled="user.areacode?.length >= 6"
			:menu-props="{ offsetY: true }"
			:style="areaStyle"></v-select>
		<v-select
			v-if="maxArea >= 9"
			v-model="entity.area9"
			@update:model-value="nextArea(entity.area9, 4)"
			@click:clear="clear(4)"
			:placeholder="user.areacode?.length >= 9 ? entity.name9 : '---街/镇---'"
			:items="areaData.area9"
			item-title="areaName"
			item-value="areaCode"
			class="d-inline-block sel_box"
			:class="maxArea > 9 && 'mr-3'"
			hide-details
			density="compact"
			variant="outlined"
			clearable
			:disabled="user.areacode?.length >= 9"
			:menu-props="{ offsetY: true }"
			:style="areaStyle"></v-select>
		<v-select
			v-if="maxArea >= 12"
			v-model="entity.area12"
			@update:model-value="nextArea(entity.area12, 5)"
			@click:clear="clear(5)"
			:placeholder="user.areacode?.length >= 12 ? entity.name12 : '---村/社---'"
			:items="areaData.area12"
			item-title="areaName"
			item-value="areaCode"
			class="d-inline-block"
			style="width: 188px"
			hide-details
			density="compact"
			variant="outlined"
			clearable
			:disabled="user.areacode?.length >= 12"
			:menu-props="{ offsetY: true }"
			:style="areaStyle"></v-select>
	</div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import Request from "@/commons/request"

// 定义组件名称和选项
defineOptions({
	name: "VtkArea",
	inheritAttrs: false,
});

// 定义props
const props = defineProps({
	maxArea: {
		type: Number,
		default: 12,
	},
	minArea: {
		type: Number,
		default: null,
	},
	areaStyle: {
		type: String,
		default: "",
	},
});

// 定义emits
const emit = defineEmits(['update:modelValue']);

// 响应式数据
const entity = reactive({
	area2: null,
	area4: null,
	area6: null,
	area9: null,
	area12: null,
	name2: '',
	name4: '',
	name6: '',
	name9: '',
	name12: ''
});

const user = ref({ areacode: "" });
const areaData = reactive({
	area2: [],
	area4: [],
	area6: [],
	area9: [],
	area12: []
});

// 安全获取 vtk 对象
const getVtk = () => {
//   if (typeof window !== 'undefined' && window.$vtk) {
//     return window.$vtk;
//   }
//   return null;
};

// 安全获取用户信息
const getUserInfo = () => {
  try {
    // const vtk = getVtk();
    // if (vtk && typeof vtk.storage?.get === 'function') {
    //   return vtk.storage.get("user") || { areacode: "" };
    // }
    return { areacode: "" };
  } catch (error) {
    console.warn('获取用户信息失败:', error);
    return { areacode: "" };
  }
};

// 组件挂载时执行
onMounted(() => {
	user.value = getUserInfo();
	area();
});

// 所属地区
const area = () => {
//   const vtk = getVtk();
//   if (!vtk) {
//     console.warn('Vtk 对象未初始化');
//     return;
//   }
  
  try {
    // vtk.message.loading.show();
    Request.postForm(`/dict/area/show/${user.value.areacode}`).then((res) => {
    //   vtk.message.loading.hide();
      if (res.meta.success) {
        entity[`area${res.data.areaLeve}`] = res.data.areaCode;
        entity.name2 = res.data.province;
        entity.name4 = res.data.city;
        entity.name6 = res.data.district;
        entity.name9 = res.data?.town;
        entity.name12 = res.data?.village;
        nextArea(user.value.areacode);
      } else {
        // vtk.message.toast(res.meta.message);
      }
    }).catch(error => {
    //   vtk.message.loading.hide();
      console.error('加载区域数据失败:', error);
    //   vtk.message.toast('加载区域数据失败');
    });
  } catch (error) {
    console.error('初始化区域数据失败:', error);
    // if (vtk.message?.loading?.hide) {
    //   vtk.message.loading.hide();
    // }
  }
};

// 下一级地区列表
const nextArea = (areaCode, index) => {
	inputFn(areaCode);
//   const vtk = getVtk();
//   if (!vtk || !areaCode) return;
  
	if (areaCode?.length < 12) {
		Request.postForm(`/dict/area/next/${areaCode}`).then((res) => {
			vtk.message.loading.hide();
			if (res.meta.success) {
				if (index) {
					Object.keys(areaData)
						.slice(index, 5)
						.forEach((e) => {
							areaData[e] = [];
							entity[e] = null;
						});
				}
				areaData[`area${res.data[0].areaLeve}`] = res.data;
			} else {
				vtk.message.toast(res.meta.message);
			}
		}).catch(error => {
      console.error('加载下级区域数据失败:', error);
    //   vtk.message.toast('加载下级区域数据失败');
    });
	}
};

// 清除
const clear = (index) => {
	let arr = Object.keys(areaData);
	inputFn(entity[arr[index - 2]]);
	arr.slice(index, 5).forEach((e) => {
		areaData[e] = [];
		entity[e] = null;
	});
};

// 输入事件
const inputFn = (e) => {
	e && emit("update:modelValue", e);
};
</script>

<style lang="scss" scoped>
.sel_box {
	width: 164px;
}
</style>