import axios from "axios";
import { gcj02towgs84, wgs84togcj02 } from 'coordtransform';
import { Url } from "./urlFormat";

const urls = new Url();
const WALKING_URL = "https://restapi.amap.com/v5/direction/walking";
const DRIVING_URL = "https://restapi.amap.com/v5/direction/driving";
const INPUT_TIP_URL = "https://restapi.amap.com/v3/assistant/inputtips";
const RE_GEO_URL = "https://restapi.amap.com/v3/geocode/regeo";

const GD_KEY = "6af6a87038f44c8c793aa70331f2b7ca";

// 起点、沿途、不包含的沿途、终点，光点的颜色
export const wayColorList = {
  startColor: {
    color: '#00F535',
    borderColor: '#DCFFDA',
  },
  endColor: {
    color: '#F5A500',
    borderColor: '#FFF1DA',
  },
  wayColorChoose: {
    color: '#00ECF5',
    borderColor: '#FFFFFF',
  },
  wayColorNoChoose: {
    color: '#7A7A7A',
    borderColor: '#7A7A7A',
  },
};


//高德路线导航-步行
export const getWalkingRoute = (params) => {
    let { startlng, startlat, endlng, endlat } = params;
    //wgs84转火星坐标系
    var gcj02StartLngLat = wgs84togcj02(startlng, startlat);
    var gcj02EndLngLat = wgs84togcj02(endlng, endlat);
    let gd_params = {
        origin: `${gcj02StartLngLat[0]},${gcj02StartLngLat[1]}`,
        destination: `${gcj02EndLngLat[0]},${gcj02EndLngLat[1]}`,
        show_fields: 'polyline',
        key: GD_KEY,
        alternative_route: 3,
    }
    let new_url = urls.getUrl(WALKING_URL, gd_params);
    return new Promise((resolve, reject) => {
        axios({
            method: "get",
            url: new_url,
        }).then((res) => {
            if (res.status === 200) {
                let solution: any = [];
                if(res.data.status == '0') {
                    solution = res.data.info;
                }
                if(res.data.status == '1') {
                    //处理数据
                    res.data.route.paths.map((path, pathIndex) => {
                        let route_len = path.distance;
                        let route_time = path.cost.duration;
                        let path_polyline = path.steps.map(step => {
                            return step.polyline
                        })
                        let router_path_str = [];
                        path_polyline.forEach(polyline => {
                            let step = polyline.split(';')
                            router_path_str = router_path_str.concat(step)
                        });
                        // 去掉重复点
                        let unique_router_path_str = [...new Set(router_path_str)]
                        // 坐标转数组
                        let unique_router_path = unique_router_path_str.map(path_str => {
                            let lng_lat_list = path_str.split(',')
                            //高德坐标系转wgs84坐标系
                            var wgs84Coordinate = gcj02towgs84(...lng_lat_list);
                            return wgs84Coordinate
                        })
                        //高德导航的起点和终点
                        let startCoordinates = unique_router_path[0]
                        let endCoordinates = unique_router_path.at(-1)
                        // 高德地图返回的结果：方案一。长度，线
                        solution.push(
                            {
                                route_key: pathIndex,
                                route_len: route_len,
                                route_time: route_time,
                                path_polyline: unique_router_path,
                                startCoordinates: startCoordinates,
                                endCoordinates: endCoordinates,
                            }
                        )
                    })
                }
                resolve(solution);
            } else {
                reject(res)
            }
        }).catch(err => {
            reject(err)
        })
    })
}

//高德路线导航-驾车
export const getDrivingRoute = (params) => {
    let { startlng, startlat, endlng, endlat, way } = params;
    //wgs84转火星坐标系
    var gcj02StartLngLat = wgs84togcj02(startlng, startlat);
    var gcj02EndLngLat = wgs84togcj02(endlng, endlat);
    // 途径点
    var wayLngLatList: String = '';
    way.forEach((w, windex) => {
        var gcj02WayLngLat = wgs84togcj02(w.wayLngLat[0], w.wayLngLat[1]);
        if (w.wayFlag && w.wayLngLat && w.wayName) {
            if(windex == '') {
                wayLngLatList += `${gcj02WayLngLat[0]},${gcj02WayLngLat[1]}`;
            } else {
                wayLngLatList += `;${gcj02WayLngLat[0]},${gcj02WayLngLat[1]}`;
            }
        }
    })
    let gd_params = {
        key: GD_KEY,
        origin: `${gcj02StartLngLat[0]},${gcj02StartLngLat[1]}`,
        destination: `${gcj02EndLngLat[0]},${gcj02EndLngLat[1]}`,
        strategy: 32,
        waypoints: wayLngLatList,
        show_fields: 'polyline,cost',
    }
    let new_url = urls.getUrl(DRIVING_URL, gd_params);
    return new Promise((resolve, reject) => {
        axios({
            method: "get",
            url: new_url,
        }).then((res) => {
            if (res.status === 200) {
                let solution: any = [];
                if(res.data.status == '0') {
                    solution = res.data.info;
                }
                if(res.data.status == '1') {
                    //处理数据
                    res.data.route.paths.map((path, pathIndex) => {
                        let route_len = path.distance;
                        let route_time = path.cost.duration;
                        let path_polyline = path.steps.map(step => {
                            return step.polyline
                        })
                        let router_path_str = [];
                        path_polyline.forEach(polyline => {
                            let step = polyline.split(';')
                            router_path_str = router_path_str.concat(step)
                        });
                        // 去掉重复点
                        let unique_router_path_str = [...new Set(router_path_str)]
                        // 坐标转数组
                        let unique_router_path = unique_router_path_str.map(path_str => {
                            let lng_lat_list = path_str.split(',')
                            //高德坐标系转wgs84坐标系
                            var wgs84Coordinate = gcj02towgs84(...lng_lat_list);
                            return wgs84Coordinate;
                        })
                        //高德导航的起点和终点
                        let startCoordinates = unique_router_path[0]
                        let endCoordinates = unique_router_path.at(-1)
                        // 高德地图返回的结果：方案一。长度，线
                        solution.push(
                            {
                                route_key: pathIndex,
                                route_len: route_len,
                                route_time: route_time,
                                path_polyline: unique_router_path,
                                startCoordinates: startCoordinates,
                                endCoordinates: endCoordinates
                            }
                        )
                    })
                }
                resolve(solution);
            } else {
                reject(res)
            }
        }).catch(err => {
            reject(err)
        })
    })
}

// 输入提示
export const getInputTips = (params) => {
    let gd_params = {
        key: GD_KEY,
        keywords: params.keywords,
        location: params.location,
        city: '临沂',
        citylimit: true,
        datatype: 'all',
    }
    let new_url = urls.getUrl(INPUT_TIP_URL, gd_params);
    return new Promise((resolve, reject) => {
        axios({
            method: "get",
            url: new_url,
        }).then((res) => {
            if (res.status === 200) {                
                //处理数据
                let solution:any = res.data.tips.map((item, index)=>{
                    return {
                        ...item,
                        districtAndName: item.name + '(' + item.district.substring(6) + ')',
                    }
                });
                resolve(solution);
            } else {
                reject(res)
            }
        }).catch(err => {
            reject(err)
        })
    })
}

// 逆地理编码-通过坐标获取建筑信息
export const getRegeoByLocation = (params) => {
    let gd_params = {
        key: GD_KEY,
        location: params.location,
        radius: 500,
        extensions: 'all',
    }
    let new_url = urls.getUrl(RE_GEO_URL, gd_params);
    return new Promise((resolve, reject) => {
        axios({
            method: "get",
            url: new_url,
        }).then((res) => {
            console.log();
            if (res.status === 200) {
                let solution: any = '';
                if(res.data.status == '0') {
                    solution = {
                        "error" : res.data.info,
                    };
                }
                if(res.data.status == '1') {
                    //处理数据
                    solution = res.data.regeocode.formatted_address.substring(6);
                }
                resolve(solution);
            } else {
                reject(res)
            }
        }).catch(err => {
            reject(err)
        })
    })

}


