import { View, Map, Text, Image } from "@tarojs/components";
import "./index.less";
import { useRef, useState } from "react";
import Taro, { useDidShow } from "@tarojs/taro";
import { getAuth } from "@/utils/comm";
import services from "@/services";
import useReportStore from "@/store/report";
import locationImg from "@/assets/images/event/localPoint.png";
import dragPoint from "@/assets/images/event/dragPoint.png";
import lacate from "@/assets/images/event/lacate.png";
import locationIcon from "@/assets/images/event/location.png";
import { Button } from "@taroify/core";
function ConfirmLocation() {
  const { discoverEntry, eventReportInfoExtend, standardEventContent } =
    useReportStore(); //上报事件
  const [marketPoint, setMarketPoint] = useState<any>({
    longitude: 104.067252,
    latitude: 30.548654,
  });
  //解析的地址信息
  const addressInfo = useRef<any>();
  let eventFileImgs = Taro.getStorageSync("beforeFilePath"); //事件图片地址
  useDidShow(async () => {
    const auth = await getAuth("scope.userLocation", "请打开位置权限", () => {
      Taro.navigateBack();
    });
    if (auth) {
      getRealLocation();
    }
  });

  // 获取位置信息
  const getRealLocation = () => {
    try {
      Taro.getLocation({
        type: "wgs84", // 返回的经纬度坐标为WGS84坐标系
        success: async (position) => {
          let { longitude, latitude } = position;
          await getAnalysisAddress(longitude, latitude);
          setMarketPoint({ longitude, latitude });
        },
        fail: (err) => {
          // 处理获取位置信息失败的情况
          console.error(err);
        },
      });
      //查询地址信息
    } catch (error) {
      // 处理异常
      console.error(error);
    }
  };

  //解析地址信息
  const getAnalysisAddress = async (longitude: number, latitude: number) => {
    return new Promise((resolve, reject) => {
      Taro.request({
        url: `https://apis.map.qq.com/ws/geocoder/v1`,
        method: "GET",
        data: {
          location: `${latitude},${longitude}`,
          key: "ZCMBZ-EMXKZ-GQEXH-TQNKQ-IHFAO-KQF3S",
        },
        success: function (res) {
          let { status, result } = res.data;
          if (status === 0) {
            addressInfo.current = {
              cityCode: "5101",
              cityName: result.address_component.city,
              districtCode: result.ad_info.adcode,
              districtName: result.ad_info.district,
              streetCode: result.address_reference?.town?.id,
              streetName: result.address_component.street,
              communityCode: "",
              communityName: "",
              lon: result.location.lng, //事件经度
              lat: result.location.lat, //事件纬度
              coordinateType: "GCJ-02", //坐标类型
              address: result.formatted_addresses.recommend,
            };
            resolve(addressInfo.current);
          }
        },
        fail: (err) => {},
      });
    });
  };

  //确认位置，上报事件
  const handleConfirm = () => {
    let req: API.ReportEventSourceInfoReq = {
      standardEventTitle: standardEventContent, //极简上报如果有描述就传入
      standardEventContent, //描述
      handlingMethod: "1", //办理方式  1:派遣处置
      collectionMode: "1",
      eventReportInfoExtend: {
        ...eventReportInfoExtend,
        ...addressInfo.current,
      },
      beforeFilePath: eventFileImgs,
    };
    if (discoverEntry === "liftFinger") {
      req.handlingMethod = "2"; //2自查自处(举手之劳传2)
      req.afterFilePath = Taro.getStorageSync("afterFilePath"); //处置后的图片
    }
    console.log("上报参数", req);
    services.event.postReportEventSourceInfo(req).then((res) => {
      if (res.code === 200) {
        //上报成功
        if (res.data === true) {
          Taro.redirectTo({
            url: "/pages/Success/index?sourceType=event",
          });
        } else {
          Taro.setStorageSync("dispatchInfo", res.data); //派遣信息
          //直达
          Taro.redirectTo({
            url: "/pages/Event/view/autoDispatch/index",
          });
        }
      }
    });
  };
  //视野发生变化时触发，
  const regionChange = async (e) => {
    if (e.causedBy === "drag") {
      if (e.detail.type === "end") {
        const { longitude, latitude } = e.detail.centerLocation;
        await getAnalysisAddress(longitude, latitude);
        setMarketPoint({ longitude, latitude });
      }
    }
  };
  return (
    <View className="location-wrap">
      <Map
        id="myMap"
        longitude={marketPoint.longitude}
        latitude={marketPoint.latitude}
        onRegionChange={regionChange}
        scale={16}
        setting={{}}
        onError={() => {}}
        className="map-wrap"
        markers={[
          {
            id: 1,
            latitude: Number(marketPoint?.latitude),
            longitude: Number(marketPoint?.longitude),
            iconPath: locationImg,
            width: "76rpx",
            height: "100rpx",
          },
        ]}
      />
      <View className="drag">
        <Image src={dragPoint} className="drag-img" />
      </View>
      <View className="top-info">
        <Image src={eventFileImgs[0]} className="picture" />
        <View className="text">
          请确认问题是否发生在当前位置
          <Text className="tip"> 如果不是,请拖动地图调整</Text>
        </View>
      </View>
      <View className="right-lacate" onClick={getRealLocation}>
        <Image src={lacate} className="lacate-icon" />
      </View>
      <View className="bottom-confrim">
        <View>
          <Image src={locationIcon} className="icon" />
          {addressInfo.current?.address}
        </View>
        <Button color="primary" block onClick={handleConfirm} shape="round">
          位置对了，上报此问题
        </Button>
      </View>
    </View>
  );
}

export default ConfirmLocation;
