import { Button, Col, Form, Input, Row } from "antd";
import { useState } from "react";
import MapSelector from "./MapSelector";

/**
 * 定位组件
 */
const Map = (props) => {
  const {
    longitudeProps = "longitude",
    latitudeProps = "latitude",
    onConfirm,
    required = true,
    area = "",
    showArea = false,
    disable = false,
    type = "baidu",
  } = props;

  const form = Form.useFormInstance();
  const [mapVisible, setMapVisible] = useState(false);
  const [currentLongitude, setCurrentLongitude] = useState("");
  const [currentLatitude, setCurrentLatitude] = useState("");

  const handleMapConfirm = (longitudeValue, latitudeValue, extra) => {
    setCurrentLongitude(longitudeValue);
    setCurrentLatitude(latitudeValue);
    form.setFieldsValue({
      [longitudeProps]: longitudeValue,
      [latitudeProps]: latitudeValue,
    });
    onConfirm?.(longitudeValue, latitudeValue, extra);
    setMapVisible(false);
  };

  return (
    <>
      <Row gutter={24}>
        <Col span={12}>
          <Form.Item label="经度" name={longitudeProps} rules={[{ required, message: "请选择经度" }]}>
            <Input disabled />
          </Form.Item>
        </Col>
        <Col span={12}>
          <Form.Item label="纬度" required={required}>
            <div style={{ display: "flex", gap: 10 }}>
              <Form.Item name={latitudeProps} noStyle rules={[{ required, message: "请选择纬度" }]}>
                <Input disabled />
              </Form.Item>
              <Button
                type="primary"
                onClick={() => {
                  setMapVisible(true);
                  setCurrentLongitude(form.getFieldValue(longitudeProps));
                  setCurrentLatitude(form.getFieldValue(latitudeProps));
                }}
              >
                地图定位
              </Button>
            </div>
          </Form.Item>
        </Col>
      </Row>
      <MapSelector
        visible={mapVisible}
        onClose={() => setMapVisible(false)}
        longitude={currentLongitude}
        latitude={currentLatitude}
        area={area}
        type={type}
        showArea={showArea}
        disable={disable}
        onConfirm={handleMapConfirm}
      />
    </>
  );
};

Map.displayName = "Map";

export default Map;
