/**
 * amis-ui v6.11.0-beta.8
 * Copyright 2018-2025 fex
 */

import { __extends, __awaiter, __generator, __decorate, __metadata } from 'tslib';
import React__default from 'react';
import { uuid, loadScript, autobind, themeable } from 'amis-core';
import debounce from 'lodash/debounce';
import { Icon } from './icons.js';

var COORDINATES_GCJ02 = 3;
var COORDINATES_BD09 = 5;
var BaiduMapPicker = /** @class */ (function (_super) {
    __extends(BaiduMapPicker, _super);
    function BaiduMapPicker() {
        var _this = _super !== null && _super.apply(this, arguments) || this;
        _this.state = {
            inputValue: '',
            locs: [],
            locIndex: -1,
            sugs: []
        };
        _this.id = uuid();
        _this.mapRef = React__default.createRef();
        _this.search = debounce(function () {
            var _a;
            if (_this.state.inputValue) {
                (_a = _this.ac) === null || _a === void 0 ? void 0 : _a.search(_this.state.inputValue);
            }
            else {
                _this.setState({
                    sugs: []
                });
            }
        }, 250, {
            trailing: true,
            leading: false
        });
        return _this;
    }
    BaiduMapPicker.prototype.componentDidMount = function () {
        if (window.BMap) {
            this.initMap();
        }
        else {
            loadScript("//api.map.baidu.com/api?v=3.0&ak=".concat(this.props.ak, "&callback={{callback}}")).then(this.initMap);
        }
    };
    BaiduMapPicker.prototype.componentWillUnmount = function () {
        var _a, _b;
        (_b = (_a = this.ac) === null || _a === void 0 ? void 0 : _a.dispose) === null || _b === void 0 ? void 0 : _b.call(_a);
        this.placeholderInput && document.body.removeChild(this.placeholderInput);
        delete this.placeholderInput;
        delete this.map;
    };
    BaiduMapPicker.prototype.initMap = function () {
        var _a;
        return __awaiter(this, void 0, void 0, function () {
            var autoSelectCurrentLoc, map, value, point, zoom, geolocationControl, input;
            var _this = this;
            return __generator(this, function (_b) {
                switch (_b.label) {
                    case 0:
                        autoSelectCurrentLoc = (_a = this.props.autoSelectCurrentLoc) !== null && _a !== void 0 ? _a : false;
                        map = new BMap.Map(this.mapRef.current, {
                            enableMapClick: false
                        });
                        this.map = map;
                        this.convertor = new BMap.Convertor();
                        value = this.props.value;
                        point = value
                            ? new BMap.Point(value.lng, value.lat)
                            : new BMap.Point(116.404, 39.915);
                        zoom = (value === null || value === void 0 ? void 0 : value.zoom) || 15;
                        if (!(this.props.coordinatesType == 'gcj02')) return [3 /*break*/, 2];
                        return [4 /*yield*/, this.covertPoint(point, COORDINATES_GCJ02, COORDINATES_BD09)];
                    case 1:
                        point = _b.sent();
                        map.centerAndZoom(point, zoom);
                        return [3 /*break*/, 3];
                    case 2:
                        map.centerAndZoom(point, zoom);
                        _b.label = 3;
                    case 3:
                        map.addControl(
                        // @ts-ignore
                        new BMap.NavigationControl({ type: BMAP_NAVIGATION_CONTROL_SMALL }));
                        geolocationControl = new BMap.GeolocationControl();
                        geolocationControl.addEventListener('locationSuccess', function (e) {
                            _this.getLocations(e.point, autoSelectCurrentLoc);
                        });
                        if (this.props.showGeoLoc === true) {
                            map.addControl(geolocationControl);
                        }
                        map.addEventListener('click', function (e) {
                            if (_this.props.onlySelectCurrentLoc) {
                                return;
                            }
                            _this.getLocations(e.point, true);
                        });
                        input = document.createElement('input');
                        input.className = 'invisible';
                        this.placeholderInput = input;
                        document.body.appendChild(input);
                        this.ac = new BMap.Autocomplete({
                            input: input,
                            location: map,
                            onSearchComplete: function (result) {
                                // 说明已经销毁了。
                                if (!_this.map) {
                                    return;
                                }
                                var sugs = [];
                                var poiLength = result.getNumPois();
                                if (poiLength) {
                                    for (var i = 0; i < poiLength; i++) {
                                        var poi = result.getPoi(i);
                                        if (poi) {
                                            sugs.push([
                                                poi.province,
                                                poi.city,
                                                poi.district,
                                                poi.street,
                                                poi.business
                                            ].join(' '));
                                        }
                                    }
                                    _this.setState({
                                        sugs: sugs
                                    });
                                }
                            }
                        });
                        value ? this.getLocations(point) : geolocationControl.location();
                        return [2 /*return*/];
                }
            });
        });
    };
    BaiduMapPicker.prototype.getLocations = function (point, selectCurrentLoc) {
        var _this = this;
        var map = this.map;
        map.clearOverlays();
        var mk = new BMap.Marker(point);
        map.addOverlay(mk);
        map.panTo(point);
        var geoc = new BMap.Geocoder();
        geoc.getLocation(point, function (rs) {
            // 说明已经销毁了。
            if (!_this.map) {
                return;
            }
            var index = 0;
            var locs = [];
            locs.push({
                title: '当前位置',
                address: rs.address,
                city: rs.addressComponents.city,
                lat: rs.point.lat,
                lng: rs.point.lng
            });
            if (Array.isArray(rs.surroundingPois)) {
                rs.surroundingPois.forEach(function (item) {
                    locs.push({
                        title: item.title,
                        address: item.address,
                        city: item.city,
                        lat: item.point.lat,
                        lng: item.point.lng
                    });
                });
            }
            _this.setState({
                locIndex: index,
                locs: locs
            }, function () {
                if (!selectCurrentLoc) {
                    return;
                }
                _this.triggerOnChange(locs[0]);
            });
        });
    };
    BaiduMapPicker.prototype.handleChange = function (e) {
        this.setState({
            inputValue: e.currentTarget.value
        }, this.search);
    };
    BaiduMapPicker.prototype.handleSelect = function (e) {
        var _this = this;
        var index = parseInt(e.currentTarget.getAttribute('data-index'), 10);
        var loc = this.state.locs[index];
        this.setState({
            locIndex: index
        }, function () {
            var point = new BMap.Point(loc.lng, loc.lat);
            _this.map.clearOverlays();
            var mk = new BMap.Marker(point);
            _this.map.addOverlay(mk);
            _this.map.panTo(point);
            _this.triggerOnChange(loc);
        });
    };
    BaiduMapPicker.prototype.covertPoint = function (point, from, to) {
        var _this = this;
        return new Promise(function (resolve, reject) {
            _this.convertor.translate([point], from, to, function (res) {
                if (res.status === 0 && res.points.length) {
                    resolve(new BMap.Point(res.points[0].lng, res.points[0].lat));
                }
                else {
                    reject();
                }
            });
        });
    };
    BaiduMapPicker.prototype.triggerOnChange = function (loc) {
        var _this = this;
        var _a, _b;
        var point = new BMap.Point(loc.lng, loc.lat);
        if (this.props.coordinatesType == 'gcj02') {
            this.covertPoint(point, COORDINATES_BD09, COORDINATES_GCJ02).then(function (convertedPoint) {
                var _a;
                typeof ((_a = _this.props) === null || _a === void 0 ? void 0 : _a.onChange) === 'function' &&
                    _this.props.onChange({
                        address: loc.address.trim() || loc.title,
                        lat: convertedPoint.lat,
                        lng: convertedPoint.lng,
                        city: loc.city
                    });
            });
        }
        else {
            typeof ((_a = this.props) === null || _a === void 0 ? void 0 : _a.onChange) === 'function' &&
                ((_b = this.props) === null || _b === void 0 ? void 0 : _b.onChange({
                    address: loc.address.trim() || loc.title,
                    lat: loc.lat,
                    lng: loc.lng,
                    city: loc.city
                }));
        }
    };
    BaiduMapPicker.prototype.handleSugSelect = function (e) {
        var _this = this;
        var value = e.currentTarget.innerText;
        this.setState({
            inputValue: value
        });
        var local = new BMap.LocalSearch(this.map, {
            // 智能搜索
            onSearchComplete: function () {
                var results = local.getResults();
                var poi = results.getPoi(0);
                _this.setState({
                    inputValue: poi === null || poi === void 0 ? void 0 : poi.title,
                    sugs: []
                });
                _this.getLocations(poi === null || poi === void 0 ? void 0 : poi.point, true);
            }
        });
        local.search(value);
    };
    BaiduMapPicker.prototype.render = function () {
        var _this = this;
        var _a, _b;
        var _c = this.props, cx = _c.classnames, mapStyle = _c.mapStyle;
        var onlySelectCurrentLoc = (_a = this.props.onlySelectCurrentLoc) !== null && _a !== void 0 ? _a : false;
        var _d = this.state, locIndex = _d.locIndex, locs = _d.locs, inputValue = _d.inputValue, sugs = _d.sugs;
        var showSug = (_b = this.props.showSug) !== null && _b !== void 0 ? _b : true;
        var hasSug = Array.isArray(sugs) && sugs.length;
        return (React__default.createElement("div", { className: cx('MapPicker') },
            !onlySelectCurrentLoc && (React__default.createElement("div", { className: cx('MapPicker-search TextControl-control') },
                React__default.createElement("div", { className: cx('TextControl-input') },
                    React__default.createElement("input", { onChange: this.handleChange, value: inputValue, placeholder: "\u641C\u7D22\u5730\u70B9" })))),
            React__default.createElement("div", { ref: this.mapRef, className: cx('MapPicker-map', {
                    invisible: hasSug
                }), style: mapStyle }),
            !showSug ? null : (React__default.createElement("div", { className: cx('MapPicker-result', {
                    invisible: hasSug
                }) },
                !onlySelectCurrentLoc &&
                    locs.map(function (item, index) { return (React__default.createElement("div", { onClick: _this.handleSelect, key: index, "data-index": index, className: cx('MapPicker-item') },
                        React__default.createElement("div", { className: cx('MapPicker-itemTitle') }, item.title),
                        React__default.createElement("div", { className: cx('MapPicker-itemDesc') }, item.address),
                        locIndex === index ? (React__default.createElement(Icon, { icon: "success", className: "icon" })) : null)); }),
                onlySelectCurrentLoc && locs.length > 0 && (React__default.createElement("div", { onClick: this.handleSelect, key: "locs-current", "data-index": 0, className: cx('MapPicker-item') },
                    React__default.createElement("div", { className: cx('MapPicker-itemTitle') }, locs[0].title),
                    React__default.createElement("div", { className: cx('MapPicker-itemDesc') }, locs[0].address),
                    locIndex === 0 ? (React__default.createElement(Icon, { icon: "success", className: "icon" })) : null)))),
            showSug && hasSug && !onlySelectCurrentLoc ? (React__default.createElement("div", { className: cx('MapPicker-sug') }, sugs.map(function (item) { return (React__default.createElement("div", { onClick: _this.handleSugSelect, className: cx('MapPicker-sugItem'), key: item }, item)); }))) : null));
    };
    __decorate([
        autobind,
        __metadata("design:type", Function),
        __metadata("design:paramtypes", []),
        __metadata("design:returntype", Promise)
    ], BaiduMapPicker.prototype, "initMap", null);
    __decorate([
        autobind,
        __metadata("design:type", Function),
        __metadata("design:paramtypes", [Object, Boolean]),
        __metadata("design:returntype", void 0)
    ], BaiduMapPicker.prototype, "getLocations", null);
    __decorate([
        autobind,
        __metadata("design:type", Function),
        __metadata("design:paramtypes", [Object]),
        __metadata("design:returntype", void 0)
    ], BaiduMapPicker.prototype, "handleChange", null);
    __decorate([
        autobind,
        __metadata("design:type", Function),
        __metadata("design:paramtypes", [Object]),
        __metadata("design:returntype", void 0)
    ], BaiduMapPicker.prototype, "handleSelect", null);
    __decorate([
        autobind,
        __metadata("design:type", Function),
        __metadata("design:paramtypes", [Object]),
        __metadata("design:returntype", void 0)
    ], BaiduMapPicker.prototype, "handleSugSelect", null);
    return BaiduMapPicker;
}(React__default.Component));
var BaiduMapPicker$1 = themeable(BaiduMapPicker);

export { BaiduMapPicker, BaiduMapPicker$1 as default };
