var BASE = "https://ykdz.yundazhou.com/api";

var player;
var markers = [];
var groupType = undefined;
function getList(tag) {
  $.ajax({
    url: BASE + "/waterLoggingPoints/list",
    type: "GET",
    // data: JSON.stringify(param),
    data: { groupType },
    async: false,
    dataType: "json",
    contentType: "application/json; charset=UTF-8",
    success: function (data) {
      if (data.c === 200) {
        // console.log(data);
        $(".videoList").empty();
        $(`.videoList1`).empty();
        $(`.videoList2`).empty();
        if (tag === 1) {
          data.d.map((item) => {
            //创建一个 Marker 实例：
            const marker = new AMap.Marker({
              icon: "https://a.amap.com/jsapi_demos/static/demo-center/icons/poi-marker-default.png",
              position: new AMap.LngLat(item.longitude, item.latitude), //经纬度对象，也可以是经纬度构成的一维数组[116.39, 39.9]
              anchor: "bottom-center",
              title: item.name,
            });
            // 设置鼠标划过点标记显示的文字提示
            marker.setTitle(item.name);

            // 设置label标签
            // label默认蓝框白底左上角显示，样式className为：amap-marker-label
            marker.setLabel({
              direction: "top",
              offset: new AMap.Pixel(10, 0), //设置文本标注偏移量
              content: "<div class='info'>" + item.name + "</div>", //设置文本标注内容
            });
            marker.on("click", () => {
              location.href = `detail.html?id=${item.id}`;
            });
            map.add(marker);
            markers.push(marker);
          });
        } else {
          let data1 = data.d.filter((item) => item.groupType === 1);
          let data2 = data.d.filter((item) => item.groupType === 2);
          if (data1.length > 0) {
            appendListDom(data1);
          }
          if (data2.length > 0) {
            appendListDom(data2);
          }
        }
      }
    },
  });
}
function appendListDom(data) {
  // let title =
  //   '<div class"titleBg">' + data[0].groupType === 1
  //     ? "城市道路积水"
  //     : "河道水情观测" + "</div>";
  // $(".videoList").append(title);
  let type = data[0].groupType;
  let title =
    type === 1
      ? '<div class="videoListTitle">城市道路积水</div><div class="videoList"></div>'
      : '<div class="videoListTitle">河道水情观测</div><div class="videoList"></div>';
  $(`.videoList${type}`).prepend(title);
  console.log(1);
  data.map((item) => {
    let local =
      (localStorage.getItem("local") &&
        localStorage.getItem("local").split(",")) ||
      "0,0";

    let dis = AMap.GeometryUtil.distance(local, [
      item.longitude,
      item.latitude,
    ]);
    let bg = item.groupType === 1 ? "bg1" : "bg2";
    let status = item.num2 > item.num1 ? "异常" : "正常";
    let statusClass = status === "异常" ? "err" : "";
    let str =
      '<div class="videoItem ' +
      bg +
      '" onclick="handleDetail(\'' +
      item.id +
      "')\" id=" +
      item.id +
      ">" +
      '<div class="videoBox">' +
      '<span class="status ' +
      statusClass +
      '">' +
      status +
      "</span>" +
      '<img src="' +
      item.image +
      '" />' +
      "</div>" +
      "<div class='name'>" +
      item.name +
      "</div>" +
      '<div class="positionDiv"><i class="icon_position"></i>' +
      Math.round(dis / 1000) +
      "km</div>" +
      "</div>";
    $(`.videoList${type}> .videoList`).append(str);
    console.log(2);
  });
}

function handleDetail(id) {
  console.log(id);
  window.location.href = `detail.html?id=${id}`;
}

function getInfo(id) {
  $.ajax({
    url: BASE + "/waterLoggingPoints/info",
    type: "GET",
    // data: JSON.stringify(param),
    async: false,
    dataType: "json",
    data: { id },
    contentType: "application/json; charset=UTF-8",
    success: function (data) {
      document.title = data.d.name;
      if (data.d.mark === 1) {
        $(".videoBox").append('<div class="zhedang"></div>');
      }

      $(".content").empty();
      // let str = `<div class="subTitle">点位信息<span class="tip">网络问题可能导致视频加载失败，请重新进入</span></div>
      // <div class="layer">
      // <div class="name">${data.d.name}</div>
      // <div class="status">正常</div>
      // </div>
      // <div class="subTitle">易涝点共查<span class="tip">共查数据每2小时更新一次</span></div>
      // <div class="layer_colume">
      // <div class="isNormal">该点位是否能正常通行?</div>
      // <div class="join"><i class="icon_user"></i><span>${data.d.numAll}</span>已参与</div>
      // <div class="chosen">
      //   <div class="choseItem">
      //     <img onclick="commit(1)" src="./img/success.png"/>
      //     <span>${data.d.numProportion1}</span>
      //   </div>
      //   <div class="choseItem">
      //     <img onclick="commit(0)" src="./img/error.png"/>
      //     <span>${data.d.numProportion2}</span>
      //   </div>
      // </div>
      // </div>`;
      let status = data.d.num2 > data.d.num1 ? "异常" : "正常";
      let statusClass = status === "异常" ? "err" : "";
      let str = `<div class="text_dwxx"></div>
      <div class="layer">
        <div class="name">
          <i class="icon_position1"></i> <span>${data.d.name}</span>
        </div>
        <span class="btn_status ${statusClass}">${status}</span>
        <div class="tip abs">如果监控长时间未成功播放，请刷新重试。<button onclick="refresh()" class="refresh">点击刷新</button></div>
      </div>

      <div class="text_yldgc"></div>
      <div class="layer_colume">
        <div style="margin-top: 22px">该点位是否正常通行?</div>
        <div class="tip"><span>${data.d.numAll}</span>人已参与</div>
        <div class="roll">
          <div class="rollItem" onclick="commit(1)">
            <div class="rollItemOption"><i class="success"></i> 是</div>
            <div class="rollItemPercent">${data.d.numProportion1}</div>
          </div>
          <div class="rollItem"  onclick="commit(0)">
            <div class="rollItemOption"><i class="error"></i> 否</div>
            <div class="rollItemPercent">${data.d.numProportion2}</div>
          </div>
        </div>
        <div class="tip abs">共查数据每2小时更新一次</div>
      </div>`;
      $(".content").append(str);
      if (data.c === 200) {
        console.log(data);
        player.src({
          src: data.d.playUrl,
          type: "application/x-mpegURL",
        });

        player.play();

        // var hls;
        // var video = document.getElementById("myVideo");
        // $(".status").text(Hls.isSupported(),document.getElementById("myVideo"));
        // var hls = new Hls();
        // hls.loadSource(data.d.playUrl);
        // hls.attachMedia(video);
        // hls.on(Hls.Events.MANIFEST_PARSED, function () {
        //   video.play();
        // });
        // $(video).attr('src',data.d.playUrl)

        // data.d.map((item, index) => {
        //   //   if (index !== 1) {
        //   $("#source_video" + index).attr("src", item);
        //   videojs("video" + index);
        //   //   }
        // });
      }
    },
  });
}
function refresh() {
  location.reload();
}

function commit(tag) {
  let payload = {
    id: parameterValue,
    isNormal: tag ? true : false,
  };
  $.ajax({
    url: BASE + "/waterLoggingPoints/dataCommit",
    type: "POST",
    // data: JSON.stringify(param),
    async: false,
    dataType: "json",
    data: JSON.stringify(payload),
    contentType: "application/json; charset=UTF-8",
    success: function (data) {
      // alert("提交成功!");
      msg.info("提交成功！");
      getInfo(parameterValue);
    },
  });
}

function handleGroupTypeChange() {
  console.log($("#groupType").val());
  groupType = $("#groupType").val();
  getList();
}
