/*
 * @Note:
 * @Author: 2058827620@qq.com
 * @Date: 2022-04-03 10:53:25
 */
import React, { useState, useEffect } from 'react';
import { useModel } from 'umi';
import {
  Modal,
  Space,
  Button,
  Select,
  Input
} from 'antd';

import {
  ProFormText,
  ProFormTextArea
} from '@ant-design/pro-components';


import services from '@/services/admin';

const { wemapSuggestion, wemapGeocoder } = services.WemapController;
let geocoder, map, marker = null;

export const QQMap = ({ ...restProps }) => {

  const { onChange, value } = restProps;


  const [option, setOption] = useState([]);

  const [location, setLocation] = useState(value);

  const [modalOpenState, setModalOpenState] = useState(false);
  const [sign, setSign] = useState(false);


  const inputChange = (data) => {
    onChange(data);
  };

  useEffect(() => {

    //初始化地图
    if (sign && !map) {
      map = new TMap.Map('container', {
        center: new TMap.LatLng(34.789049, 113.684792), //设置地图中心点坐标
      });

      marker = new TMap.MultiMarker({
        map: map, //指定点标记图层所覆盖的地图容器
        // 设置点标记数据
        geometries: [{
          id: 'this',//指定点标记id
          position: new TMap.LatLng(34.789049, 113.684792)// 标记位置(经度，纬度，高度)
        }
        ],
      });

      map?.on("click", function (evt) {
        const lat = evt.latLng.getLat().toFixed(6);
        const lng = evt.latLng.getLng().toFixed(6);

        marker.remove('this');
        marker.add({
          id: 'this',//指定点标记id
          position: new TMap.LatLng(lat, lng)
        });

        getWemapGeocoder(`${lat},${lng}`);
      });
      wemapGeocoder({
        location: '34.789049,113.684792'
      }).then(({ data }) => {

        setLocation(data);
      });
    }
  }, [sign]);


  const search = (value) => {
    wemapSuggestion({
      keyword: value
    }).then(({ data }) => {
      const arr = [];
      data?.map((item) => {
        item.fullname = `${item.title}   ${item.address}`;
        arr.push(item);
      });
      setOption(arr);
    });

  }


  const getWemapGeocoder = async (location) => {
    const { success, data } = await wemapGeocoder({
      location: location
    });

    setLocation(data);
  };


  return (
    <>
      <ProFormText
        hidden={true}
        {...restProps.fieldProps}
      />
      <Space.Compact style={{ width: "100%" }}>
        <Input
          disabled
          style={{ width: "100%" }}
          hidden={false}
          value={location?.name}
          placeholder={restProps.placeholder}
        />
        <Button onClick={() => {
          setSign(true);
          setModalOpenState(true);
        }}>地图选点</Button>
      </Space.Compact>
      <Modal width="800px" title="地图选点" open={modalOpenState} onOk={() => {
        inputChange(location);
        setModalOpenState(false);
      }} onCancel={() => {
        setModalOpenState(false)
      }}>
        <>
          <div
            className={`text-red-500`}
            style={{
              position: "absolute",
              backgroundColor: "#ffffff",
              color: "#222222",
              top: "100px",
              left: "30px",
              zIndex: "10000",
              padding: "10px"
            }}
          >
            <div>坐标：{`${location?.value?.lat},${location?.value?.lng}`}</div>
            <div>地址：{`${location?.name}`}</div>
          </div>
          <div>
            <Space.Compact style={{ width: "100%" }}>
              <Select
                placeholder="请输入地点"
                showSearch
                style={{ width: "100%" }}
                filterOption={false}
                onSearch={
                  (e) => {
                    if (!e) {
                      return;
                    }
                    search(e);
                  }
                }
                fieldNames={{
                  label: "fullname",
                  value: "id"
                }}
                options={option}
                onSelect={(e, option) => {
                  map.setCenter(new TMap.LatLng(option?.location?.lat, option?.location?.lng));
                  marker.remove('this');
                  marker.add({
                    id: 'this',//指定点标记id
                    position: new TMap.LatLng(option?.location?.lat, option?.location?.lng)
                  });
                  getWemapGeocoder(`${option?.location?.lat},${option?.location?.lng}`);

                }}
              />

            </Space.Compact>
          </div>
          <div id="container">

          </div>
        </>
      </Modal >
    </>
  );
};

export default QQMap;
