/**
 * amis-ui v6.12.0-beta.0
 * Copyright 2018-2025 fex
 */

'use strict';

Object.defineProperty(exports, '__esModule', { value: true });

var tslib = require('tslib');
var React = require('react');
var amisCore = require('amis-core');
var debounce = require('lodash/debounce');
var icons = require('./icons.js');

function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }

var React__default = /*#__PURE__*/_interopDefaultLegacy(React);
var debounce__default = /*#__PURE__*/_interopDefaultLegacy(debounce);

var __react_jsx__ = require('react');
var _J$X_ = (__react_jsx__["default"] || __react_jsx__).createElement;
(__react_jsx__["default"] || __react_jsx__).Fragment;
var COORDINATES_GCJ02 = 3;
var COORDINATES_BD09 = 5;
var BaiduMapPicker = /** @class */ (function (_super) {
    tslib.__extends(BaiduMapPicker, _super);
    function BaiduMapPicker() {
        var _this = _super !== null && _super.apply(this, arguments) || this;
        _this.state = {
            inputValue: '',
            locs: [],
            locIndex: -1,
            sugs: [],
            innerValue: _this.props.value // 内部定位的值，用于内部更新地图定位点
        };
        _this.id = amisCore.uuid();
        _this.mapRef = React__default["default"].createRef();
        _this.search = debounce__default["default"](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 {
            amisCore.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.componentDidUpdate = function (prevProps, prevState) {
        var _this = this;
        // 值更新后需要重绘地图
        if (prevProps.value !== this.props.value) {
            this.setState({
                innerValue: this.props.value
            });
        }
        else if (this.state.innerValue !== prevState.innerValue &&
            this.state.innerValue) {
            this.map.clearOverlays();
            var value = this.state.innerValue;
            var point = value
                ? new BMap.Point(value.lng, value.lat)
                : new BMap.Point(116.404, 39.915);
            var zoom_1 = (value === null || value === void 0 ? void 0 : value.zoom) || 15;
            if (this.props.coordinatesType == 'gcj02') {
                this.covertPoint(point, COORDINATES_GCJ02, COORDINATES_BD09).then(function (point) { return _this.map.centerAndZoom(point, zoom_1); });
            }
            else {
                this.map.centerAndZoom(point, zoom_1);
            }
            var mk = new BMap.Marker(point);
            // 增加定位点
            this.map.addOverlay(mk);
            // 移动到中心
            this.map.panTo(point);
        }
    };
    BaiduMapPicker.prototype.initMap = function () {
        var _a;
        return tslib.__awaiter(this, void 0, void 0, function () {
            var autoSelectCurrentLoc, map, value, point, zoom, geolocationControl, input;
            var _this = this;
            return tslib.__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:
                        if (!this.props.hideViewControl) {
                            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,
            innerValue: loc
        }, function () {
            _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 (_J$X_("div", { className: cx('MapPicker') },
            !onlySelectCurrentLoc && (_J$X_("div", { className: cx('MapPicker-search TextControl-control') },
                _J$X_("div", { className: cx('TextControl-input') },
                    _J$X_("input", { onChange: this.handleChange, value: inputValue, placeholder: "\u641C\u7D22\u5730\u70B9" })))),
            _J$X_("div", { ref: this.mapRef, className: cx('MapPicker-map', {
                    invisible: hasSug
                }), style: mapStyle }),
            !showSug ? null : (_J$X_("div", { className: cx('MapPicker-result', {
                    invisible: hasSug
                }) },
                !onlySelectCurrentLoc &&
                    locs.map(function (item, index) { return (_J$X_("div", { onClick: _this.handleSelect, key: index, "data-index": index, className: cx('MapPicker-item') },
                        _J$X_("div", { className: cx('MapPicker-itemTitle') }, item.title),
                        _J$X_("div", { className: cx('MapPicker-itemDesc') }, item.address),
                        locIndex === index ? (_J$X_(icons.Icon, { icon: "success", className: "icon" })) : null)); }),
                onlySelectCurrentLoc && locs.length > 0 && (_J$X_("div", { onClick: this.handleSelect, key: "locs-current", "data-index": 0, className: cx('MapPicker-item') },
                    _J$X_("div", { className: cx('MapPicker-itemTitle') }, locs[0].title),
                    _J$X_("div", { className: cx('MapPicker-itemDesc') }, locs[0].address),
                    locIndex === 0 ? (_J$X_(icons.Icon, { icon: "success", className: "icon" })) : null)))),
            showSug && hasSug && !onlySelectCurrentLoc ? (_J$X_("div", { className: cx('MapPicker-sug') }, sugs.map(function (item) { return (_J$X_("div", { onClick: _this.handleSugSelect, className: cx('MapPicker-sugItem'), key: item }, item)); }))) : null));
    };
    tslib.__decorate([
        amisCore.autobind,
        tslib.__metadata("design:type", Function),
        tslib.__metadata("design:paramtypes", []),
        tslib.__metadata("design:returntype", Promise)
    ], BaiduMapPicker.prototype, "initMap", null);
    tslib.__decorate([
        amisCore.autobind,
        tslib.__metadata("design:type", Function),
        tslib.__metadata("design:paramtypes", [Object, Boolean]),
        tslib.__metadata("design:returntype", void 0)
    ], BaiduMapPicker.prototype, "getLocations", null);
    tslib.__decorate([
        amisCore.autobind,
        tslib.__metadata("design:type", Function),
        tslib.__metadata("design:paramtypes", [Object]),
        tslib.__metadata("design:returntype", void 0)
    ], BaiduMapPicker.prototype, "handleChange", null);
    tslib.__decorate([
        amisCore.autobind,
        tslib.__metadata("design:type", Function),
        tslib.__metadata("design:paramtypes", [Object]),
        tslib.__metadata("design:returntype", void 0)
    ], BaiduMapPicker.prototype, "handleSelect", null);
    tslib.__decorate([
        amisCore.autobind,
        tslib.__metadata("design:type", Function),
        tslib.__metadata("design:paramtypes", [Object]),
        tslib.__metadata("design:returntype", void 0)
    ], BaiduMapPicker.prototype, "handleSugSelect", null);
    return BaiduMapPicker;
}(React__default["default"].Component));
var BaiduMapPicker$1 = amisCore.themeable(BaiduMapPicker);

exports.BaiduMapPicker = BaiduMapPicker;
exports["default"] = BaiduMapPicker$1;
