import { defineComponent, onMounted, reactive, shallowRef } from 'vue';
import styles from './amap-gps.module.less';
import AMapLoader from '@amap/amap-jsapi-loader';
import MHeader from '@/components/m-header';
import MSticky from '@/components/m-sticky';
import iconMap from './images/icon-map.png';
import iconMapError from './images/icon-map-error.png';
import { useRoute } from 'vue-router';
import request from '@/helpers/request';
export default defineComponent({
  name: 'amap-gps',
  setup() {
    const route = useRoute();
    // 选中地图详情地址
    const selectMapAddress = reactive({
      attendance_range: 1000,
      lnglat: [] as any, // 教学点 A座
      address: '',
      signInLongitudeLatitude: [] as any, // 签到  B座
      signOutLongitudeLatitude: [] as any, // 签退
      signInMark: null,
      signOutMark: null,
      addressMark: null
    });

    const sLngLat = route.query.sLngLat as string;
    if (route.query.sLngLat) {
      selectMapAddress.lnglat = sLngLat.split(',');
    }
    // inLngLat
    const inLngLat = route.query.inLngLat as string;
    if (route.query.inLngLat) {
      selectMapAddress.signInLongitudeLatitude = inLngLat.split(',');
    }
    // outLngLat
    const outLngLat = route.query.outLngLat as string;
    if (route.query.outLngLat) {
      selectMapAddress.signOutLongitudeLatitude = outLngLat.split(',');
    }

    const map = shallowRef<any>(null);
    const ininMap = () => {
      // ac943ac1522de0d63eb8a99b71fe2601
      // 501e5bfaf7cfc5d3d53a9a4d9466d8b9  9d8382171e90c8a085688172d7a903b2

      AMapLoader.load({
        key: 'ac943ac1522de0d63eb8a99b71fe2601', //api服务key--另外需要在public中使用安全密钥！！！
        version: '2.0', // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
        plugins: [
          // 'AMap.AutoComplete', // 输入提示插件
          // 'AMap.PlaceSearch',
          'AMap.ToolBar', // 缩放工具条
          'AMap.Driving'
        ], // 需要使用的的插件列表
        AMapUI: {
          version: '1.1',
          plugins: []
        },
        Loca: {
          version: '2.0.0'
        }
      })
        .then(AMap => {
          let marker = null as any;
          map.value = new AMap.Map('gpsContainer', {
            resizeEnable: true,
            zoom: 16,
            zooms: [2, 22]
            // center: [114.34371, 30.55939]
          });
          AMap.plugin(
            [
              // 'AMap.AutoComplete',
              // 'AMap.PlaceSearch',
              'AMap.Geocoder',
              'AMap.GeometryUtil'
            ],
            function () {
              // 判断是否有数据 加载教学点
              if (
                selectMapAddress.lnglat &&
                selectMapAddress.lnglat.length > 0
              ) {
                map.value.setCenter(selectMapAddress.lnglat, true);
                clearMarker();
                addMarker(selectMapAddress.lnglat, '教学点', 'addressMark');

                const circle = new AMap.Circle({
                  center: new AMap.LngLat(...selectMapAddress.lnglat), // 圆心位置
                  radius: selectMapAddress.attendance_range, //半径
                  strokeColor: '#00B2A7', //线颜色
                  strokeOpacity: 1, //线透明度
                  strokeWeight: 2, //线粗细度
                  fillColor: '#A3FFF9', //填充颜色
                  fillOpacity: 0.14 //填充透明度
                });
                map.value.add(circle);
                map.value.setFitView();
              }

              // 加载签到点
              if (
                selectMapAddress.signInLongitudeLatitude &&
                selectMapAddress.signInLongitudeLatitude.length > 0
              ) {
                console.log(
                  'signInLongitudeLatitude',
                  selectMapAddress.signInLongitudeLatitude
                );
                addMarker(
                  selectMapAddress.signInLongitudeLatitude,
                  '签到点',
                  'signInMark'
                );
              }
              // 加载签退点
              if (
                selectMapAddress.signOutLongitudeLatitude &&
                selectMapAddress.signOutLongitudeLatitude.length > 0
              ) {
                console.log(
                  'signOutLongitudeLatitude',
                  selectMapAddress.signOutLongitudeLatitude
                );
                addMarker(
                  selectMapAddress.signOutLongitudeLatitude,
                  '签退点',
                  'signOutMark'
                );
              }
              console.log(selectMapAddress, 'selectMapAddress');
              if (selectMapAddress.signInMark && selectMapAddress.addressMark) {
                // 连线 设置签到点与教学点的距离
                computeDis(
                  selectMapAddress.addressMark,
                  selectMapAddress.signInMark,
                  'top'
                );
                console.log('连线 设置签到点与教学点的距离');
              }
              if (
                selectMapAddress.signOutMark &&
                selectMapAddress.addressMark
              ) {
                // 连线 设置签退点与教学点的距离
                computeDis(
                  selectMapAddress.addressMark,
                  selectMapAddress.signOutMark,
                  'bottom'
                );
                console.log('连线 设置签退点与教学点的距离');
              }
            }
          );

          // 添加标记点
          function addMarker(
            lnglat: any,
            title: string,
            type: 'signInMark' | 'signOutMark' | 'addressMark'
          ) {
            const Icon = new AMap.Icon({
              size: [27, 28],
              image: iconMap,
              imageSize: [27, 28]
            });
            marker = new AMap.Marker({
              icon: Icon,
              // offset: new AMap.Pixel(-14, -28),
              anchor: 'bottom-center',
              position: new AMap.LngLat(...lnglat),
              title
            });

            marker.setLabel({
              content: `${title}`, //设置文本标注内容
              direction: 'top',
              offset: [0, -2]
            });

            selectMapAddress[type] = marker;
            marker.setMap(map);
            map.value.add(marker);
          }
          // 清除标记点
          function clearMarker() {
            if (marker) {
              marker.setMap(null);
              marker = null;
            }
          }
          // 连线 写标记
          function computeDis(m1: any, m2: any, type: string) {
            const p1 = m1.getPosition();
            const p2 = m2.getPosition();
            const textPos = p1.divideBy(2).add(p2.divideBy(2));
            const distance = Math.round(p1.distance(p2));
            const path = [p1, p2];
            const mainColor =
              distance > selectMapAddress.attendance_range
                ? '#FF5A56'
                : '#01C1B5';
            // 判断距离是否已经在圈外了
            if (distance > selectMapAddress.attendance_range) {
              m2.dom.classList.add('myClassM2');
              m2.setIcon(iconMapError);
            }

            const line = new AMap.Polyline({
              strokeColor: mainColor,
              strokeWeight: 2,
              isOutline: true,
              outlineColor: mainColor
            });
            line.setMap(map.value);
            line.setPath(path);

            // const a = calcAngle([p1.lng, p2.lng], [p2.lng, p1.lng]);
            // console.log(a, 'aaaaaaa');
            const text = new AMap.Text({
              text: distance + 'M',
              style: {
                'font-size': '12px',
                color: '#fff',
                border: 'none',
                backgroundColor: mainColor
              }
              //设置文本标注方位
            });
            text.setPosition(textPos);
            text.setMap(map.value);
            if (type == 'top') {
              text.setOffset(new AMap.Pixel(-40, -10));
            } else {
              // text.setOffset(new AMap.Pixel(-40, -50));
              //   text.setPosition(textPos);
            }
          }

          // 计算两点间的角度
          // function calcAngle(start: any, end: any) {
          //   const p_start = map.value.lngLatToContainer(start),
          //     p_end = map.value.lngLatToContainer(end);

          //   const diff_x = p_end.x - p_start.x,
          //     diff_y = p_end.y - p_start.y;
          //   console.log((360 * Math.atan2(diff_y, diff_x)) / (2 * Math.PI));
          //   return (360 * Math.atan2(diff_y, diff_x)) / (2 * Math.PI) - 45;
          // }
        })
        .catch(() => {
          //
        });
    };

    onMounted(async () => {
      try {
        const { data } = await request.get(
          '/api-web/open/school/queryByParamName',
          {
            params: {
              paramName: 'attendance_range'
            }
          }
        );
        selectMapAddress.attendance_range = data.attendance_range || 1000;
      } catch {
        //
      }
      ininMap();
    });

    return () => (
      <div class={styles['amap-gps']}>
        <MSticky position="top">
          <MHeader />
        </MSticky>

        <div
          id="gpsContainer"
          style={{
            width: '100%',
            height: 'calc(100vh - var(--header-height))',
            position: 'relative'
          }}></div>
      </div>
    );
  }
});
