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

function getParameterByName(name) {
  name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
  var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
    results = regex.exec(location.search);
  return results === null
    ? ""
    : decodeURIComponent(results[1].replace(/\+/g, " "));
}

function getWebPage(id) {
  console.log(id);
  $.ajax({
    url: BASE + "/pageInfo/getWebPage?id=" + (id ? id : ""),
    type: "GET",
    // data: JSON.stringify(param),
    // data: {  },
    // params: { id },
    async: true,
    dataType: "json",
    contentType: "application/json; charset=UTF-8",
    success: function (data) {
      if (data.c === 200) {
        console.log(data);
        currentId = data.d.id;

        $(".body").css("background", data.d.pageColor);
        $(".footer").css("background", data.d.pageColor);
        $("html").css("background", data.d.pageColor);
        
        $("#shadow").css(
          "background",
          `linear-gradient(
          180deg,
          rgba(255, 151, 45, 0) 0%,
          ${data.d.pageColor} 100%
        )`
        );
        $("#liveList").empty();
        $("#blockList").empty();
        if (data.d.videoInfo2 !== null) {
          data.d.videoInfo2.map((item) => {
            let str = `<div class="videoItem videoItem_${
              data.d.pageStyle === "" ? "theme2" : data.d.pageStyle
            }" onclick="jumpLiveDetail('${item.id}')">
                  <div class="dz">${item.numLike}人点赞</div>
                  <img class="poster poster_${
                    data.d.pageStyle === "" ? "theme2" : data.d.pageStyle
                  }" src="${item.imageUrl}" alt="" />
                  <div class="videoItemTitle">${item.name}</div>
                </div>`;
            $("#liveList").append(str);
          });
        }

        $("#numShare").text(data.d.numShare);
        $("#numLike").text(data.d.numLike);

        $("#bottomInfo1").text(data.d.bottomInfo1);
        $("#bottomInfo2").text(data.d.bottomInfo2);
        $("#bottomInfo3").text(data.d.bottomInfo3);

        if (id) {
          $(".header").css("background", `url(${data.d.mainImageUrl})`);

          if (data.d.videoInfo1) {
            $("#video").attr("src", data.d.videoInfo1.playUrl);
          } else {
            $("video").parent().remove();
          }

          if (data.d.pageInfoResponseInfos) {
            data.d.pageInfoResponseInfos.map((item) => {
              let strBlock = `<div class="videoItem" onclick="jumpBlock('${item.pageUrl}','${item.id}')">
                  <img src="${item.pageImageUrl}" alt="" />
                  <div>${item.name}</div>
                </div>`;

              $("#blockList").append(strBlock);
            });
          } else {
            $("#blockList").parent().remove();
          }
        } else {
          $(".header").css("background", `url(${data.d.mainImageUrl})`);
          data.d.pageInfoResponseInfos.map((item) => {
            let strBlock = `<div class="videoItem" onclick="jumpTheme('${item.pageUrl}','${item.pageStyle}','${item.id}')">
              <img src="${item.pageImageUrl}" alt="" />
              <div>${item.name}</div>
            </div>`;

            $("#blockList").append(strBlock);
          });
        }
      }
    },
  });
}
function getWebVideoInfo(id) {
  // /pageInfo/getWebVideoInfo
  currentId = id;
  $.ajax({
    url: BASE + "/pageInfo/getWebVideoInfo?id=" + (id ? id : ""),
    type: "GET",
    // data: JSON.stringify(param),
    // data: {  },
    // params: { id },
    async: true,
    dataType: "json",
    contentType: "application/json; charset=UTF-8",
    success: function (data) {
      if (data.c === 200) {
        console.log(data);
        player = TCPlayer("player-container-id", {
          sources: [
            {
              src: data.d.playUrl,
            },
          ],
          licenseUrl:
            "https://license.vod2.myqcloud.com/license/v2/1329781370_1/v_cube.license",
          licenseKey: "42d4b304d6b3ea8b3f80906fd6f48a2d",
        });
        $(".btn_shareBox .right").text(data.d.numShare);
        $(".btn_thumbBox .right").text(data.d.numLike);
        $(".video-title").text(data.d.name);
      }
    },
  });
}
function jumpLiveDetail(id) {
  location.href = "live.html?id=" + id;
}
function jumpTheme(pageUrl, theme, id) {
  if (pageUrl !== "null" && pageUrl !== "") {
    location.href = `frame.html?url=${pageUrl}&id=${id}`;
  } else {
    location.href = `${theme}.html?id=${id}`;
  }
  //   location.href = `${theme}`;
  //   '${item.pageStyle}.html?id=${item.id}'
}
function jumpBlock(pageUrl, id) {
  //   location.href = "qk.html?id=" + id;
  if (pageUrl !== "null" && pageUrl !== "") {
    location.href = `frame.html?url=${pageUrl}&id=${id}`;
  } else {
    location.href = `qk.html?id=${id}`;
  }
}
function likeShare(type, page) {
  // /pageInfo/likeShare
  let payload = {
    id: currentId,
    type: type,
    type2: page,
  };
  $.ajax({
    url: BASE + "/pageInfo/likeShare",
    type: "POST",
    // data: JSON.stringify(param),
    data: JSON.stringify(payload),
    // params: { id },
    async: true,
    dataType: "json",
    contentType: "application/json; charset=UTF-8",
    success: function (data) {
      if (data.c === 200) {
        $("#numLike").text();
        if (type === 2) {
          copyTextToClipboard(location.href);
          msg.info("链接已复制到剪贴板");
        }
        if (!getParameterByName("id")) {
          getWebPage();
        } else {
          if (page === 2) {
            $.ajax({
              url: BASE + "/pageInfo/getWebVideoInfo?id=" + currentId,
              type: "GET",
              async: true,
              dataType: "json",
              contentType: "application/json; charset=UTF-8",
              success: function (data) {
                if (data.c === 200) {
                  console.log(data);

                  $(".btn_shareBox .right").text(data.d.numShare);
                  $(".btn_thumbBox .right").text(data.d.numLike);
                }
              },
            });
          } else {
            getWebPage(currentId);
          }
        }
      }
    },
  });
}
async function copyTextToClipboard(text) {
  try {
    await navigator.clipboard.writeText(text);
    console.log("Text copied to clipboard");
  } catch (err) {
    console.error("Failed to copy: ", err);
  }
}
function handleSearch() {
  let keyword = $(".searchInput").val();
  $(".searchList").show();
  window.btnSearch.addEventListener("click", toggleSearchList);
  document.addEventListener("click", closeSearchList);
  //   console.log(temp);

  $.ajax({
    url: BASE + "/pageInfo/searchList?keyword=" + keyword,
    type: "GET",
    // data: JSON.stringify(param),
    // data: JSON.stringify(payload),
    // params: keyword ,
    async: true,
    dataType: "json",
    contentType: "application/json; charset=UTF-8",
    success: function (data) {
      if (data.c === 200) {
        console.log(data);
        $(".searchList").empty();
        data.d.map((item) => {
          let str = `<div class="searchItem" onclick=jumpSearch('${item.id}',${item.type},'${item.pageStyle}','${item.pageUrl}')>${item.name}</div>`;
          $(".searchList").append(str);
        });
      }
    },
  });
  //   $(".searchList").focus();

  //   var _searchList = $(".searchList");
  //   console.log(searchList, searchList.style.display, _searchList.is(":hidden"));
  //   if (_searchList.is(":hidden")) {
  //     $(".searchList").show();
  //     setTimeout(() => {
  //       document.addEventListener("click", function (e) {
  //         console.log(
  //           "addEventListener",
  //           "searchList:",
  //           searchList,
  //           "e.target:",
  //           e.target
  //         );
  //         if (!searchList.contains(e.target)) {
  //           searchList.style.display = "none";
  //           document.removeEventListener("click");
  //         }
  //       });
  //     }, 1000);
  //   } else {
  //     $(".searchList").hide();
  //   }

  // 当点击searchList外部时，关闭searchList
}

function toggleSearchList() {
  //   var searchList = document.querySelector(".searchList");
  console.log(12);
  if ($(".searchList").is(":hidden")) {
    setTimeout(() => {
      document.addEventListener("click", function (e) {
        console.log(
          "addEventListener",
          "searchList:",
          searchList,
          "e.target:",
          e.target
        );
        if (!searchList.contains(e.target)) {
          searchList.style.display = "none";
          document.removeEventListener("click");
        }
      });
    }, 1000);
  } else {
    $(".searchList").hide();
    // 移除事件监听器
  }
}

function closeSearchList(e) {
  console.log(22);
  if (!window.searchList.contains(e.target) && e.target !== window.btnSearch) {
    window.searchList.style.display = "none";
    btnSearch.removeEventListener("click", toggleSearchList);
    document.removeEventListener("click", closeSearchList);
  }
}

function jumpSearch(id, type, theme, pageUrl) {
  if (pageUrl) {
    location.href = `frame.html?id=${id}&url=${pageUrl}`;
    return;
  }
  switch (type) {
    case 2:
      location.href = `${theme}.html?id=${id}`;
      break;
    case 3:
      location.href = "qk.html?id=" + id;
      break;
    case 4:
      location.href = "live.html?id=" + id;
      break;
    default:
      break;
  }
}
