import React, { useEffect, useState, useRef } from 'react'
import SiteModal from '@/components/Modal/SiteModa';
import { Input, Cascader, Button } from 'antd'
import { gcj_decrypt, exetent2AmapPoint, lngLat2WebMercator } from '@/utils/transformUtil'
import { GetAllConfig, GetMetaData } from '@/services/platform/gis'
const { Search } = Input;
const MapScope = props => {


    const [options, setOptions] = useState([])

    //const [mouseTool,setMouseTool] = useState(null)
    const { confirmModal,  extent,mapId } = props
    const [currentExtent, setCurrentExtent] = useState()
    const [isDistrict, setIsDistrict] = useState(false)
    const [currentAreaName, setCurrentAreaName] = useState(null)
    const mapID = useRef();
    const mouseToolID = useRef();
    useEffect(() => {
        if (document.getElementById(mapId)) {
            if (!mapID.current) {
                //1.加载底图
                let m = new window.AMap.Map(mapId);
                mapID.current = m
                //2.加载管网配置
                GetAllConfig().then(
                    res => {
                        if (res.IsSuccess == true) {
                            let pipenetCofig;
                            res.Result.map((item) => {
                                if (item.type == "pipenet") {
                                    pipenetCofig = item
                                }
                            })
                            if (pipenetCofig) {
                                GetMetaData(pipenetCofig.servicename).then(
                                    res2 => {
                                        if (res2 && res2.units) {
                                            const layers = res2.layers || [];
                                            const workspace = res2.mapName.split('_')[0];
                                            const subLayers = layers.filter(layer => layer.subLayerIds && layer.subLayerIds.length === 0).map(layer => layer.name);
                                            const paramLayers = `${workspace}:${subLayers.join(',')}`;
                                            const params = {
                                                'LAYERS': paramLayers,
                                                'VERSION': '1.1.1',
                                                '_site':''
                                            };
                                            const wmsOption = {
                                                tileSize: 512,
                                                url: `${location.origin}/Cityinterface/rest/services/MapServer.svc/${pipenetCofig.servicename}/GeoServerProxy/wms`,
                                                blend: false,
                                                params: params,
                                                zooms: [2, 20],
                                            }
                                            let wms = new window.AMap.TileLayer.WMS(wmsOption)
                                            m.add(wms);

                                        }
                                    }
                                )
                            }

                        }
                    }
                )

                //3.组装高德支持的数据
            }
            if (!mouseToolID.current) {
                let tool = new AMap.MouseTool(mapID.current)
                mouseToolID.current = tool
            }
            extent && mapID.current.setCenter(exetent2AmapPoint(extent))
            //distinct&&onCascderChange([distinct])


            window.AMap.plugin('AMap.DistrictSearch', function () {
                let districtSearch = new AMap.DistrictSearch({
                    // 关键字对应的行政区级别,country表示国家
                    level: 'country',
                    //  显示下级行政区级数,1表示返回下一级行政区
                    subdistrict: 3
                })

                // 搜索所有省/直辖市信息
                districtSearch.search('中国', function (status, result) {
                    // 查询成功时,result即为对应的行政区信息
                    console.log(result, "行政区划信息")
                    setOptions(result.districtList[0].districtList)
                })
            })
        }

    }, [props])
    const resetmap = () => {

    }

    const getInitConfig = () => {

    }
    const onSubmit = () => {
        confirmModal && confirmModal(currentExtent, currentAreaName)
        let mouseTool = mouseToolID.current;
        mouseTool.close(true)
        let map = mapID.current
        map.clearMap()

    }
    const handleSearch = () => {

    }
    const onTangleClick = () => {

        // if(!mouseTool){
        //     let tool = new AMap.MouseTool(map)
        //     setMouseTool(tool)
        // }

        let mouseTool = mouseToolID.current
        mouseTool.close(true)

        mouseTool.rectangle({
            fillColor: '#00b0ff',
            strokeColor: '#80d8ff'
            //同Polygon的Option设置
        });
        mouseTool.on('draw', function (event) {
            mouseTool.close(false)
            //console.log(event.obj.getBounds(),"矩形对象")
            let bounds = event.obj.getBounds()
            let ne = bounds.northEast.pos
            let sw = bounds.southWest.pos

            let str = (sw.concat(ne)).toString()
            setCurrentExtent(str)
        })
    }
    const onCascderChange = (value) => {

        let map = mapID.current
        map.clearMap()
        console.log(value, "选中的行政区")
        let dic = {
            "1": "province",
            "2": "city",
            "3": "district"
        }
        let level = dic[value.length.toString]
        AMap.plugin('AMap.DistrictSearch', function () {
            // 创建行政区查询对象
            let district = new AMap.DistrictSearch({
                // 返回行政区边界坐标等具体信息
                extensions: 'all',
                // 设置查询行政区级别为 区 
                level: level
            })

            district.search(`${value[value.length - 1]}`, function (status, result) {
                // 获取朝阳区的边界信息

                let bounds = result.districtList[0].boundaries

                let polygons = []
                if (bounds) {
                    for (let i = 0, l = bounds.length; i < l; i++) {
                        //生成行政区划polygon
                        let polygon = new AMap.Polygon({
                            map: map,
                            strokeWeight: 1,
                            path: bounds[i],
                            fillOpacity: 0.7,
                            fillColor: '#CCF3FF',
                            strokeColor: '#CC66CC'
                        })
                        polygons.push(polygon)
                    }
                    // 地图自适应
                    map.setFitView()
                    setCurrentAreaName(value[value.length - 1])
                    setIsDistrict(true)
                }
            })
        })

    }
    const filter = (inputValue, path) => {
        return path.some(option => option.name.toLowerCase().indexOf(inputValue.toLowerCase()) > -1)
    }
    return (
        <SiteModal
            {...props}
            title={"范围选择"}
            bodyStyle={{ width: '100%', minHeight: '100px' }}
            style={{ top: 200, borderRadius: '20px' }}
            width="800px"
            cancelText="取消"
            okText="确认"
            onOk={() => onSubmit()}

        >
            <div style={{ width: "750px", height: "500px" }}>
                <div style={{ width: "750px", height: "500px", position: "absolute" }} >
                    <div id={mapId} style={{ width: "750px", height: "500px" }}></div>

                    <div style={{ top: "10px", left: "10px", position: "absolute" }}>
                        <Cascader
                            fieldNames={{ label: 'name', value: 'name', children: 'districtList' }}
                            options={options}
                            onChange={onCascderChange}
                            placeholder="请选择行政区"
                            showSearch={{ filter }}
                            changeOnSelect
                            style={{ width: "200px" }}
                        />
                    </div>
                    <div style={{ top: "10px", right: "10px", position: "absolute" }}>
                        <Button type="primary" onClick={onTangleClick}>框选范围</Button>
                    </div>
                    <div style={{ display: `${isDistrict ? "inline" : "none"}`, top: "10px", left: "220px", position: "absolute" }}>
                        <Button type="primary" onClick={onTangleClick}>样式调整</Button>
                    </div>
                </div>
            </div>

        </SiteModal>
    )
}

export default MapScope