import { useState } from 'react';
import axios from 'axios';
import Request from '../utils/request';
import { MAP_WEB_SERVER_KEY } from '../contants';
type AreaProps = {
	adcode: string;
	name: string;
	level: 'province' | 'city' | 'district';
	districts: AreaProps[];
	value: string;
	label: string;
	children: AreaProps[];
};
function formatMapData(data: AreaProps[]) {
	return data.map((element) => {
		return {
			...element,
			value: element.adcode,
			label: element.name,
			children: formatMapData(element.districts),
		};
	});
}
export const useGetAreaTree = () => {
	const [state, setState] = useState<{
		loading: boolean;
		dataSource: AreaProps[];
	}>({
		loading: false,
		dataSource: [],
	});
	const request = () => {
		setState((preState) => ({ ...preState, loading: true }));
		return axios({
			url: 'https://restapi.amap.com/v3/config/district',
			params: { key: MAP_WEB_SERVER_KEY, subdistrict: 3 },
		})
			.then(({ data }) => {
				setState((preState) => ({
					...preState,
					loading: false,
					dataSource: formatMapData(data.districts[0].districts),
				}));
			})
			.catch((error) => {
				setState((preState) => ({ ...preState, loading: false }));
				return Promise.reject(error);
			});
	};
	return { state, request } as const;
};
