<template>
  <div class="PointNavigation" id="PointNavigation">
    <div class="Header">
      <img
        @click="handleBack"
        src="../../assets/img/PointNavigation/back.png"
        alt=""
      />
      <div class="mode">
        <img src="../../assets/img/PointNavigation/weizhi.png" alt="" />
        <span>{{ locationName }}</span>
        <img
          src="../../assets/img/PointNavigation/PointNavigation.png"
          alt=""
        />
        <span>多点导航模式</span>
      </div>
      <div class="data">
        <div class="name">
          饲料
          <span>{{ ShipStatus.feedWeight }} kg</span>
        </div>
        <div class="name">
          船速
          <span>{{ ShipStatus.speed }} m/s</span>
        </div>
        <div class="name">
          电量
          <span>{{ ShipStatus.power }}%</span>
        </div>
      </div>
    </div>

    <div class="Left">
      <img
        @click="handleToushi"
        v-if="Sayaoform.radio1 == ''"
        src="../../assets/img/PathPlan/toushi.png"
        alt=""
      />
      <img
        @click="handleToushi"
        v-if="Sayaoform.radio1 == '2'"
        src="../../assets/img/PathPlan/toushigao.png"
        alt=""
      />
      <img
        @click="handleToushi"
        v-if="Sayaoform.radio1 == '1'"
        src="../../assets/img/PathPlan/toushizhong.png"
        alt=""
      />
      <img
        @click="handleToushi"
        v-if="Sayaoform.radio1 == '0'"
        src="../../assets/img/PathPlan/toushidi.png"
        alt=""
      />
      <img
        @click="handleToushi"
        v-if="Sayaoform.radio1 == '3'"
        src="../../assets/img/PathPlan/toushizidong.png"
        alt=""
      />

      <!-- 撒药模式 -->
      <el-dialog
        title="撒药模式"
        :modal-append-to-body="false"
        :visible.sync="dialogFormVisible"
        style="margin-top: 25vh"
        width="30%"
      >
        <el-form ref="form" :model="Sayaoform" label-width="80px">
          <el-form-item label="投食速度">
            <el-radio-group v-model="Sayaoform.radio1">
              <el-radio-button label="0">低速</el-radio-button>
              <el-radio-button label="1">中速</el-radio-button>
              <el-radio-button label="2">高速</el-radio-button>
              <el-radio-button label="3"
                >自动投食(根据鱼群密度自动投食)</el-radio-button
              >
            </el-radio-group>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取 消</el-button>
          <el-button type="primary" @click="ToushiOnsubmit()">确 定</el-button>
        </div>
      </el-dialog>
      <img
        v-if="Sayao"
        @click="handleSayao()"
        src="../../assets/img/PointNavigation/sayao.png"
        alt=""
      />
      <img
        v-if="Sayao == false"
        @click="handleSayao()"
        src="../../assets/img/PointNavigation/sayaohover.png"
        alt=""
      />
      <!-- <img
        v-if="Shexiangtou"
        @click="handleShexiangtou()"
        src="../../assets/img/PointNavigation/shexiangtou.png"
        alt=""
      />
      <img
        v-if="Shexiangtou == false"
        @click="handleShexiangtou()"
        src="../../assets/img/PointNavigation/shexiangtouhover.png"
        alt=""
      /> -->
    </div>

    <!-- 摄像头 -->
    <!-- <div class="video" v-if="Shexiangtou == false">
      <iframe
        width="100%"
        height="100%"
        frameborder="0"
        id="ysOpenDevice"
        :src="iframeSrc"
        allowfullscreen
      >
      </iframe>
    </div> -->
    <div class="Left-Bottom">
      <img
        v-if="Xuandian"
        src="../../assets/img/PointNavigation/xuandian.png"
        alt=""
        @click="handleXuandian()"
      />
      <img
        v-if="Xuandian == false"
        src="../../assets/img/PointNavigation/queding.png"
        alt=""
        @click="handleQueding()"
      />
      <img
        v-if="Xuandian == false"
        src="../../assets/img/PointNavigation/qingchu.png"
        alt=""
        @click="handleQingchu()"
      />
    </div>

    <div class="button">
      <img
        v-if="Start == 1"
        src="../../assets/img/PointNavigation/kaishi.png"
        alt=""
        @click="handleStart()"
      />
      <img
        v-if="Start == 2"
        src="../../assets/img/PointNavigation/jieshu.png"
        alt=""
        @click="handleEnd()"
      />
    </div>
  </div>
</template>
<script>
import apiServe from "@/utils/api";
import AMapLoader from "@amap/amap-jsapi-loader";
import axios from "axios";
export default {
  data() {
    return {
      Sayao: true,
      Start: 0,
      Xuandian: true,
      Shexiangtou: true,
      token: "",
      dialogFormVisible: false,
      Sayaoform: {
        radio1: "",
      },
      locationName: "", // 存储获取到的地点名称
      // 模拟后端传递的经纬度数据（实际从API获取）
      backendLocation: {
        longitude: 120.072896,
        latitude: 36.155971,
      },
      // 多点导航参数
      ArrayDate: {
        data: [], // 用于保存最终的经纬度数据
        routeId: "",
      },
      map: null, // 地图实例
      polylineNavigation: null, // 折线实例
      selectedPaths: [], // 存储用户点击的经纬度点路径
      markerList: [], // 存储所有的标记点
      ShipId: 123456789,
      // 定时器
      intervalI: null,
      // 船状态定时器
      timeInterval: null,
      intervalId: null,
      // 船状态信息每五秒刷新
      ShipStatus: {
        // gps错误
        gpsWarning: null,
        // 遥控器错误
        joyWarning: null,
        // 设备ID
        deviceId: null,
        // 投食重量
        feedWeight: null,
        // 经度
        longitude: null,
        // 纬度
        latitude: null,
        // 电量
        power: null,
        // 速度
        speed: null,
        // 船状态
        Status: null,
      },
    };
  },
  mounted() {
    this.initAMap();
    this.GetToken();
    this.handleReceiveQuery();
    this.GetShipStatus();
    this.GetTimer();
  },
  computed: {
    iframeSrc() {
      return `https://open.ys7.com/console/jssdk/pc.html?accessToken=${this.token}&url=ezopen://open.ys7.com/FC9834568/1.live&themeId=pcLive`;
    },
  },
  // 离开该页面时销毁定时器
  beforeDestroy() {
    this.map?.destroy();
    clearInterval(this.timeInterval);
    this.timeInterval = null; // 清除引用
    clearInterval(this.intervalId);
  },
  methods: {
    //获取船的状态数据
    GetShipStatus() {
      apiServe.GetShipStatus("get", { id: this.ShipId }).then((res) => {
        // console.log(res, "获取船的状态数据");
        if (res) {
          this.shipStatus = res.data;
          console.log(this.shipStatus);
          // 根据船的状态信息来弹出警告
          if (this.shipStatus.gpsWarning == 1) {
            this.$message({
              showClose: true,
              message: "GPS错误警告!!!",
              type: "warning",
            });
          }
          if (this.shipStatus.joyWarning == 1) {
            this.$message({
              showClose: true,
              message: "遥控器错误警告!!!",
              type: "warning",
            });
          }
        }
      });
    },
    // 定时器
    GetTimer() {
      this.timeInterval = setInterval(() => {
        this.GetShipStatus();
      }, 5000);
    },

    // 摄像头
    GetToken() {
      axios
        .post(
          "https://open.ys7.com/api/lapp/token/get",
          {
            appKey: "1e0fd35277444a3986f4984788a0ee82",
            appSecret: "4bc97fa347f130fa3f0180f53c71edfd",
          },
          {
            headers: {
              "Content-Type": "application/x-www-form-urlencoded",
              Accept: "application/json",
            },
          }
        )
        .then((res) => {
          this.token = res.data.data.accessToken;
        })
        .catch((error) => {
          console.error("Error:", error);
        });
    },
    initAMap() {
      window._AMapSecurityConfig = {
        securityJsCode: "93bceef67b80451f0817024a81dc6170",
      };
      AMapLoader.load({
        key: "f470b3bf9c52d2514824bc38ca6383b9", // 申请好的Web端开发者Key，首次调用 load 时必填
        version: "2.0", // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
        plugins: ["AMap.Scale"], //需要使用的的插件列表，如比例尺'AMap.Scale'，支持添加多个如：['...','...']
      })
        .then((AMap) => {
          this.map = new AMap.Map("PointNavigation", {
            // 设置地图容器id
            viewMode: "2D", //地图模式
            zoom: 16, //初始化地图层级
            center: [
              this.backendLocation.longitude,
              this.backendLocation.latitude,
            ],
            terrain: true, //开启地形图
            mapStyle: "amap://styles/normal", //设置地图的显示样式
          });
          // 4. 创建地理编码器实例
          const geocoder = new AMap.Geocoder({
            radius: 1000, // 搜索半径（米）
            extensions: "all", // 返回详细信息
          });

          // 5. 执行逆地理编码
          geocoder.getAddress(
            [this.backendLocation.longitude, this.backendLocation.latitude],
            (status, result) => {
              if (status === "complete" && result.info === "OK") {
                // 成功获取地址信息
                const address = result.regeocode;
                this.locationName = address.formattedAddress; // 完整地址

                // 如果需要更精确的名称（如POI名称）
                if (address.pois && address.pois.length > 0) {
                  this.locationName = address.pois[0].name; // 最近POI的名称
                }

                console.log("地点名称:", this.locationName);
              } else {
                console.error("逆地理编码失败:", result);
              }
            }
          );
          // 根据从上个页面传递过来的路线并且画出该路线
          // 转换坐标数据格式
          // 判断是否是从上一个页面跳转来的
          if (this.ArrayDate.data) {
            console.log(this.ArrayDate.data);
            if (Array.isArray(this.ArrayDate.data)) {
              console.log("这是一个数组");
            } else {
              console.log("这不是一个数组");
              this.ArrayDate.data = JSON.parse(this.ArrayDate.data);
            }
            // 将一个一维数组转换成二维数组
            const coordinates = this.ArrayDate.data.reduce(
              (acc, curr, index, arr) => {
                if (index % 2 === 0) {
                  acc.push([arr[index], arr[index + 1]]);
                }
                return acc;
              },
              []
            );

            // 创建折线实例
            const polylineHistory = new AMap.Polyline({
              path: coordinates, // 折线路径坐标数组
              strokeColor: "#3366FF", // 线颜色
              strokeWeight: 5, // 线宽
              strokeStyle: "solid", // 线样式
              lineJoin: "round", // 折线拐点样式
            });

            // 将折线添加到地图
            polylineHistory.setMap(this.map);

            // 自动调整视野范围
            this.map.setFitView([polylineHistory]);
          }
          // 添加鼠标点击事件
          this.map.on("click", (e) => {
            if (this.Xuandian == true) {
              return;
            }
            // 获取点击的经纬度
            const lnglat = e.lnglat;
            // 路径
            this.selectedPaths.push(lnglat);
            // 创建新的Marrker实例
            // 定义创建一个新的 NavigationIcon 实例
            const NavigationIcon = new AMap.Icon({
              size: new AMap.Size(40, 40),
              image: require("../../assets/img/PointNavigation/B.png"), // 修改为你的图标路径
              imageOffset: new AMap.Pixel(0, 0),
              imageSize: new AMap.Size(48, 56),
              anchor: "top-center",
            });
            // 使用这个定义的icon
            const NavigationMarker = new AMap.Marker({
              position: lnglat,
              icon: NavigationIcon,
              offset: new AMap.Pixel(-21, -43),
            });
            // 添加到地图
            NavigationMarker.setMap(this.map);
            //  保存标记点
            this.markerList.push(NavigationMarker);
            // 如果已有线,更新线的位置,否则创建新的线
            if (this.polylineNavigation) {
              this.polylineNavigation.setPath(this.selectedPaths);
            } else {
              this.polylineNavigation = new AMap.Polyline({
                path: this.selectedPaths,
                strokeColor: "#0F97FF",
                strokeOpacity: 1,
                strokeWeight: 6,
                strokeStyle: "solid",
                lineJoin: "round",
                lineCap: "round",
                zIndex: 50,
              });
            }
            this.polylineNavigation.setMap(this.map);
          });

          var PointPath = []; //存储开启导航的点
          var PointPolyline; //存储开启导航的线
          var markerPoint = null;
          const fetchData = () => {
            console.log("开始导航", this.Start, this.ArrayDate.routeId);
            if (this.Start !== 2 && this.ArrayDate.routeId == undefined) {
              console.log("未开始导航");
              return;
            }
            apiServe.GetShipStatus("get", { id: 123456789 }).then((res) => {
              const PointData = res.data;

              // console.log(PointData);
              if (PointData) {
                if (PointData.latitude === null) {
                  clearInterval(this.intervalId);
                  console.log("航线已完成");
                  return;
                }
                if (PointData.latitude && PointData.longitude) {
                  const PointLnglat = new AMap.LngLat(
                    PointData.longitude,
                    PointData.latitude
                  );
                  PointPath.push(PointLnglat); //将接口的经纬度添加到路径数组
                  // 如果已经有线了，更新线的位置
                  if (PointPolyline) {
                    PointPolyline.setPath(PointPath);
                  } else {
                    PointPolyline = new AMap.Polyline({
                      path: PointPath,
                      strokeColor: "#1DC007",
                      strokeOpacity: 1, //透明度
                      strokeWeight: 5, //线宽
                    });
                    PointPolyline.setMap(this.map);
                  }
                  // 如果marker存在则更新位置否则创建一个新的marker
                  if (markerPoint) {
                    markerPoint.setPosition(PointLnglat);
                  } else {
                    const PointIcon = new AMap.Icon({
                      size: new AMap.Size(40, 40),
                      image: require("../../assets/img/PointNavigation/A.png"), // 修改为你的图标路径
                      imageOffset: new AMap.Pixel(0, 0),
                      imageSize: new AMap.Size(48, 56),
                      anchor: "top-center",
                    });
                    markerPoint = new AMap.Marker({
                      icon: PointIcon,
                      position: PointLnglat,
                      offset: new AMap.Pixel(-23, -37),
                    });
                    this.map.add(markerPoint);
                  }
                  // 设置地图中心到新添加的点
                  this.map.setCenter(PointLnglat);
                }
              }
            });
          };
          this.intervalId = setInterval(fetchData, 10000); // 每隔1秒获取一次数据
        })
        .catch((e) => {
          console.log(e);
        });
    },
    handleToushi() {
      this.dialogFormVisible = true;
    },
    ToushiOnsubmit() {
      this.dialogFormVisible = false;
      // 如果是自动传递type为0,手动还需要传递速度
      let data = {
        // 当radio1为0、1、2时，type赋值为1；其他情况type赋值为0
        type: [0, 1, 2].includes(parseInt(this.Sayaoform.radio1)) ? 1 : 0,
        speed: this.Sayaoform.radio1,
        mode: 1,
        shipId: 1,
      };
      apiServe.FeedingMode("post", data).then((res) => {
        console.log(res);
      });
    },
    handleBack() {
      this.$router.push({
        name: "deviceDetails",
      });
    },
    handleXuandian() {
      this.Xuandian = false;
    },
    handleQueding() {
      if (this.selectedPaths.length == 0) {
        this.$message({
          type: "error",
          message: "请选择导航点位!",
        });
        return;
      }
      this.Xuandian = true;
      this.Start = 1;
    },
    // 清除点位
    handleQingchu() {
      this.$confirm("是否清除点位?", "清除点位", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          // 清除所有标记点
          this.markerList.forEach((marker) => {
            marker.setMap(null); // 从地图移除
          });
          this.markerList = []; // 清空数组

          // 清除路线
          if (this.polylineNavigation) {
            this.polylineNavigation.setMap(null);
            this.polylineNavigation = null; // 释放内存
          }

          // 清空路径数据
          this.selectedPaths = [];
          this.$message({
            type: "success",
            message: "已成功清除点位!",
          });
        })
        .catch(() => {});
    },
    handleSayao() {
      this.Sayao = !this.Sayao;
      apiServe
        .SetShipFeedingMode("post", {
          shipId: 123456789,
          mode: this.Sayao === true ? "1" : "0",
        })
        .then((res) => {
          console.log(res);
        });
    },
    handleShexiangtou() {
      this.Shexiangtou = !this.Shexiangtou;
    },
    //
    //
    // 开启导航路线规划
    handleFetch() {
      if (this.Start == true) {
        return;
      }
    },
    // 开始规划按钮
    handleStart() {
      this.Start = 2;
    },
    // 结束按钮
    handleEnd() {
      this.Start = 3;
      clearInterval(this.intervalId);
      this.$prompt("是否保存该路线", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
      })
        .then(({ value }) => {
          this.$message({
            type: "success",
            message: "路线名称: " + value,
          });
          // 将之前选中的点进行处理
          const flatCoordinates = this.selectedPaths.reduce((acc, cur) => {
            acc.push(cur.lng, cur.lat);
            return acc;
          }, []);

          apiServe.AddHistoryRoute("post", {
            routeName: value,
            routePoints: flatCoordinates,
            routeType: 1,
            shipId: 123456789,
          });
        })
        .catch(() => {
          // 清除所有标记点
          this.markerList.forEach((marker) => {
            marker.setMap(null); // 从地图移除
          });
          this.markerList = []; // 清空数组

          // 清除路线
          if (this.polylineNavigation) {
            this.polylineNavigation.setMap(null);
            this.polylineNavigation = null; // 释放内存
          }

          // 清空路径数据
          this.selectedPaths = [];
          this.$message({
            type: "info",
            message: "取消保存",
          });
        });
    },

    // 接收从上个页面跳转来的query参数
    handleReceiveQuery() {
      //  console.log(this.ArrayDate);
      console.log(this.$route.query);
      this.ArrayDate = this.$route.query;
    },
  },
};
</script>
<style lang="scss" scoped>
#PointNavigation {
  width: 100%;
  height: 900px;
  z-index: 1;
  position: relative;
}
.PointNavigation::v-deep {
  .Header {
    z-index: 2;
    position: fixed;
    top: 137px;
    width: 1594px;
    height: 100px;
    background: #f8fbff;
    display: flex;
    border-radius: 12px;
    > img {
      cursor: pointer;
    }
    .mode {
      display: flex;
      align-items: center;
      margin-left: 5px;
      > img:first-child {
        margin-right: 10px;
      }
      > img:nth-child(3) {
        margin-left: 45px;
        margin-right: 10px;
      }
      > span:nth-child(2) {
        font-family: PingFang SC;
        font-weight: 500;
        font-size: 28px;
        color: #000000;
        line-height: 50px;
      }
      > span:nth-child(4) {
        font-family: PingFang SC;
        font-weight: bold;
        font-size: 36px;
        color: #000000;
        line-height: 50px;
      }
    }

    .data {
      display: flex;
      align-items: center;
      margin-left: 200px;

      .name {
        font-family: PingFang SC;
        font-weight: 500;
        font-size: 28px;
        color: #626262;
        line-height: 50px;
        margin-right: 50px;
        > span {
          margin-left: 25px;
          font-family: PingFang SC;
          font-weight: bold;
          font-size: 36px;
          color: #000000;
          line-height: 50px;
        }
      }
    }
  }
  .Left {
    z-index: 2;
    position: fixed;
    top: 247px;
    width: 250px;
    height: 325px;
    cursor: pointer;
  }
  .Left-Bottom {
    z-index: 1;
    position: fixed;
    bottom: 0px;
    width: 250px;
    height: 156px;
    cursor: pointer;
    display: flex;
    justify-content: center;
  }
  .button {
    z-index: 1;
    position: fixed;
    bottom: 0px;
    display: flex;
    right: 55px;
    width: 250px;
    height: 156px;
    cursor: pointer;
    flex-direction: row;
    align-items: center;
  }
  .video {
    z-index: 1;
    width: 640px;
    height: 360px;
    position: fixed;
    left: 485px;
    top: 259px;
  }
}
</style>
