import { nextTick, type Ref, unref, watch } from "vue"
import { useRequest } from "@/hooks/useFetchData"
import { usePaging } from "@/hooks/usePaging"
import { addArea, apiMapLocation, delArea, getAreaListByLocation, getLonAndLatByArea } from "@/api/service/area"
import type { Pager, Location } from '@/config/symbol'
import { VITE_MAP_KEY } from "@/config/env"
import { toast } from "@/utils/util"

/**用户操作 */
export function useAreaOperation(inited = true) {
    const areaSearch = ref()
    const tcMap = ref()
    const zone = ref('') //地区
    const regionCode = ref() //地区编码
    const base = ref<Pager<any>>() //区域列表信息
    const address = ref() //当前地址信息
    const isInited = ref(true) //初始化

    // 查询
    const handleSearch = (form: any) => {
        const params = {
            address: encodeURIComponent(form.area.join('')),
            key: VITE_MAP_KEY
        }
        const { runFn } = useRequest({
            apiFn: getLonAndLatByArea,
            onSuccess(response) {
                const { result: { location, address_components, ad_info } } = response
                searchCommon({ location, address_components, ad_info })
            },
        })
        runFn(params)
    }
    // 查询后操作
    const searchCommon = (payload: any) => {
        const { location, address_components, ad_info } = payload
        if (isInited.value) {
            tcMap.value?.setMapCenter(location)
            areaSearch.value?.setCascaderValue(address_components)
        }
        address.value = payload
        zone.value = address_components.district
        regionCode.value = ad_info.adcode
        fetchAreaList()
    }
    // 添加区域
    const increment = async (payload: any) => {
        const { runFn } = useRequest({
            apiFn: addArea,
            onSuccess(response) {
                tcMap.value.removePolygon()
                toast('添加成功', 'success')
                fetchAreaList()
            },
        })
        runFn(payload)
    }
    /**获取区域列表 */
    const fetchAreaList = async () => {
        const params = {
            regionId: regionCode.value
        }
        const { pager, getLists } = usePaging({
            fetchFun: getAreaListByLocation,
            params
        })
        await getLists()
        base.value = Object.assign(pager, {
            getLists
        })
    }
    /**初始化当前位置 */
    const initPosition = async () => {
        const params = { key: VITE_MAP_KEY }
        const { runFn } = useRequest({
            apiFn: apiMapLocation,
            onSuccess(response) {
                const { result: { location, ad_info } } = response
                searchCommon({ location, address_components: ad_info, ad_info })
            }
        })
        runFn(params)
        isInited.value = inited
    }

    onMounted(initPosition)

    return {
        tcMap,
        areaSearch,
        zone,
        regionCode,
        increment,
        searchCommon,
        handleSearch,
        base,
        address,
        isInited
    }
}

/**表格操作 */
export function useAreaTableOperation({ tcMap, base, aTable }: { tcMap: any, base: Ref<Pager>, aTable: any }) {

    /**选中 */
    const toggleRowSelection = (selectData: any[]) => {
        const tableData = base.value.lists
        const selectedIds = selectData?.map(item => item.id) as number[]
        const selectedList = tableData.filter(data => selectedIds.includes(data.id))

        tableData.forEach(data => {
            aTable.value.tableRef.toggleRowSelection(data, false)
        })
        selectedList.forEach(row => {
            aTable.value.tableRef.toggleRowSelection(row, true)
        })
    }
    /**定位 */
    const handleLocation = (row: any) => {
        const convertPolygons = row.polygongeo.replace("POLYGON((", '').replace("))", '').split(',')
        const polygonPaths = convertPolygons.map((path: string) => {
            const [lng, lat] = path.split(' ')
            return {
                lat: parseFloat(lat),
                lng: parseFloat(lng)
            }
        })

        tcMap.value.initPolygon({
            polygonId: row.id,
            polygonPaths
        })
    }
    /**删除 */
    const handleDelete = async (id: number) => {
        const { runFn } = useRequest({
            apiFn: delArea,
            onSuccess(response) {
                toast('删除成功', 'success')
                base.value.getLists()
            }
        })
        runFn({ id })
    }

    return {
        handleLocation,
        handleDelete,
        toggleRowSelection,
    }
}

/**地图 */
export function useAreaMapOperation(parentApi: any) {

    let map, polygon, editor;
    const TMap = (window as any).TMap

    const mapRef = ref()
    const drawId = ref([])

    /**初始化地图 */
    function initMap() {
        map = new TMap.Map(mapRef.value, {
            zoom: 12,
            viewMode: '2D'
        })
    }
    /**设置地图中心 */
    function setMapCenter(location: Location) {
        const { lat, lng } = location
        map!.setCenter(new TMap.LatLng(lat, lng))
    }
    /**绘制多边形 */
    const drawPolygon = () => {
        polygon = new TMap.MultiPolygon({
            map: map
        })
        editor = new TMap.tools.GeometryEditor({
            map: map,
            overlayList: [
                {
                    overlay: polygon,
                    id: 'polygon',
                }
            ],
            actionMode: TMap.tools.constants.EDITOR_ACTION.DRAW, // 编辑器的工作模式
            activeOverlayId: 'polygon', // 激活图层
            snappable: true,
        })
        editor.on('draw_complete', geometry => {
            drawId.value.push(geometry.id)
            geometry.paths.splice(geometry.paths.length, 0, geometry.paths[0])
            parentApi?.showDialog({
                polygonPaths: geometry.paths
            })
        })
    }
    /**表格定位=>初始化多边形 */
    function initPolygon({ polygonId, polygonPaths }: { polygonId: number, polygonPaths: Location[] }) {

        if (polygonId === polygon?.id) return

        polygon = new TMap.MultiPolygon({
            id: polygonId, // 图层id
            map: map, // 显示多边形图层的底图
            styles: {
                // 多边形的相关样式
                polygon: new TMap.PolygonStyle({
                    color: 'rgb(250, 250, 122)', // 面填充色
                    showBorder: false, // 是否显示拔起面的边线
                    borderColor: '#00FFFF', // 边线颜色
                }),
            },
            geometries: [
                {
                    id: 'polygon', // 多边形图形数据的标志信息
                    styleId: 'polygon', // 样式id
                    paths: polygonPaths, // 多边形的位置信息
                    properties: {
                        // 多边形的属性数据
                        title: 'polygon',
                    },
                },
            ],
        })
    }
    /**移除多边形 (先选中再删除)*/
    function removePolygon() {
        editor!.setActionMode(TMap.tools.constants.EDITOR_ACTION.INTERACT).select(drawId.value).setSelectable(true)
        editor!.delete()
    }

    onMounted(() => {
        nextTick(initMap)
    })

    return {
        mapRef,
        setMapCenter,
        drawPolygon,
        removePolygon,
        initPolygon
    }
}

/**弹框 */
export function useDialogOperation(regionCode: Ref<number>) {
    const infoDialogRef = ref()

    function showDialog(payload: any) {
        const params = {
            title: '绘制确认',
            rawData: { ...payload, regionCode: regionCode.value }
        }
        infoDialogRef.value.acceptParams(params)
    }

    return {
        infoDialogRef,
        showDialog
    }
}