let subdom = "tkdh" + (new Date().getDay() + 1).toString() + new Date().getHours().toString();
var navi = [
  {
    title: "彩色彩票",
    alias: "col",
    url: "list.html",
    icon: "./assets/images/navico1.png",
  },
  {
    title: "黑白彩票",
    alias: "black",
    url: "list.html",
    icon: "./assets/images/navico2.png",
  },
  {
    title: "澳门开奖",
    alias: "193844",
    url: `https://${subdom}.2hhk7oi7p.cc`,
    icon: "./assets/images/navico3.png",
  },
  {
    title: "港彩开奖",
    alias: "1313",
    url: `https://${subdom}.2233kj.com`,
    icon: "./assets/images/navico4.png",
  },
  {
    title: "高手资料",
    alias: "tkdh",
    url: `https://${subdom}.dbrpgfiu7.cc/#/pages/forum/find`,
    icon: "./assets/images/navico5.png",
  },
];

var myData = {
  col: [],
  black: [],
};
var imgLoad = "col";
var iSearch = false;
var searchContent = null;
var page = 1;
var pageLoadContent = "home";
var currentNoInfo = {}

var pageData = function (data, limit, page = 1) {
  const offset = (page - 1) * limit;
  return data.slice(offset, offset + limit);
};

const getMeta = (url, cb) => {
  const img = new Image();
  img.onload = () => cb(null, img);
  img.onerror = (err) => cb(err);
  img.src = url;
};

var MyImage = function (options) {
  this.init(options);
};

MyImage.prototype = {
  init: function (options) {
    this.getJsonKj();
    this.data = {
      col: [],
      black: [],
    };
    pageLoadContent = options.pageLoad;
    this.search = false;
    this.searchContent = "";
    this.picData();
    this.methods();
  },
  mAjax: async function (url, callback, fnCallback) {
    var xhr = new XMLHttpRequest();
    xhr.onreadystatechange = () => {
      if (xhr.readyState == XMLHttpRequest.DONE) {
        callback(xhr.response, fnCallback);
      }
    };
    xhr.open("GET", url, true);
    xhr.setRequestHeader("Content-Type", "application/json");
    xhr.send("");
  },
  getJsonKj: function () {
    let url = "https://kj.tpxiaoshimei.com/hk_kj.json?"+new Date().getTime();
    this.mAjax(url, this.currentNoInfo);
  },
  currentNoInfo: function (data) {
    data = JSON.parse(data);
    let kj = data.k.split(",");
    currentNoInfo = {
      no: kj[8].slice(-3),
      year: kj[8].slice(0, 4)
    }
  },
  picData: async function () {
    let url = "";
    if (pageLoadContent == "home") {
      await this.mAjax(
        "https://336640.tpxiaoshimei.com/imgs.php",
        this.homeData,
        this.render
      );
    }
    if (pageLoadContent == "picList") {
      await this.mAjax(
        "https://336640.tpxiaoshimei.com/imgs.php",
        this.homeData,
        this.picListRender
      );
    }

    if (pageLoadContent == "pic") {
      let id = new URLSearchParams(window.location.search).get("id");
      await this.mAjax(
        `https://336640.tpxiaoshimei.com/imgs.php?act=detail&id=${id}`,
        this.picDetail,
        this.swiperPic
      );
    }
  },
  homeData: function (data, fnCallback) {
    data = data ? JSON.parse(data) : myData;
    myData = data.data;
    page = 1;
    fnCallback();
    if (pageLoadContent == "home") {
      document.addEventListener("scroll", (event) => {
        let picWrap = document.querySelector(".pic-wrap");
        if (window.scrollY > picWrap.offsetHeight - 900) {
          page++;
          fnCallback();
        }
      });
    }
  },
  picList: function (data, picListRender) {
    data = data ? JSON.parse(data) : myData;
    myData = data.data;
    picListRender();
  },
  render: function () {
    imgLoad = localStorage.getItem("imgLoad") || "col";

    if (myData[imgLoad]) {
      const limit = 18;
      let data = [];
      let d = myData[imgLoad];
      let picWrap = document.querySelector(".pic-wrap .wrap");
      if (searchContent && searchContent != "") {
        d = d.filter((item) => item.name.includes(searchContent));
      }
      const totalPage = Math.ceil(d.length / limit);
      if (page > totalPage) return;
      data = pageData(d, limit, this.page);
      if (data.length > 0) {
        data.map((item) => {
          let box = document.createElement("div");
          box.classList.add("box");
          let html = `<a class="info" item="${item.id}" href="pic.html?id=${item.id}">
                            <img src="${hostImg}/thumb/${imgLoad}/${item.imgAlias}?v=${ver}" alt="${item.name}">
                            <span>${item.name}[${item.no}期]</span>
                        </a>`;
          box.innerHTML = html;
          if (picWrap) {
            picWrap.appendChild(box);
          }
        });
      }
      //   let picInfo = document.querySelectorAll(".pic-wrap .wrap .info");
      //   if (picInfo.length > 0) {
      //     picInfo.forEach((ele) => {
      //       ele.addEventListener("click", (e) => {
      //         let id = ele.getAttribute("item");
      //         window.location.href = `pic.html?id=${id}`;
      //       });
      //     });
      //   }
    }
  },
  picListRender: function (imgType = null) {
    imgLoad = imgType ?? (localStorage.getItem("imgLoad") || "col");
    if (myData[imgLoad]) {
      let d = myData[imgLoad];
      if (searchContent && searchContent != "") {
        d = d.filter((item) => item.name.includes(searchContent));
      }
      let ul = document.querySelector("ul.indexed-list");

      if (d.length > 0) {
        let html = d
          .map((item) => {
            return `<li class="pic-item" item="${item.id}">
                    <img src="${hostImg}/thumb/${imgLoad}/${item.imgAlias}?v=${ver}" loading="lazy" alt="${item.name}">
                    <a><label>${item.name}<span>${item.no}</span></label></a>
                </li>`;
          })
          .join("");
        if (ul) {
          ul.innerHTML = html;
        }
        let itemLi = document.querySelectorAll("ul.indexed-list li");
        if (itemLi.length > 0) {
          itemLi.forEach((ele) => {
            ele.addEventListener("click", () => {
              let id = ele.getAttribute("item");
              window.location.href = `pic.html?id=${id}`;
            });
          });
        }
      } else {
        ul.innerHTML = `<li style="text-align:center;font-size:20px">未找到数据</li>`;
      }
    }
  },
  methods: function () {
    var self = this;
    /*let nav = document.getElementById("nav");
    if (nav) {
      let html = `<ul>`;
      html += navi
        .map((item) => {
          return `<li class="nav-item"><a href="${item.url}" tar="${item.alias}"><img src="${item.icon}" alt="${item.title}">${item.title}</a></li>`;
        })
        .join("");
      html += `</ul>`;
      nav.innerHTML = html;
      document.querySelectorAll(".nav-item a").forEach((ele) => {
        ele.addEventListener("click", (e) => {
          e.preventDefault();
          if (["col", "black"].includes(ele.getAttribute("tar"))) {
            imgLoad = ele.getAttribute("tar");
            localStorage.setItem("imgLoad", imgLoad);
            window.location.href = ele.getAttribute("href");
          } else {
            window.open(ele.getAttribute("href"), "_blank");
          }
        });
      });
    }*/

    let search = document.querySelector("form.search");
    let picWrap = document.querySelector(".pic-wrap .wrap");
    if (search) {
      search.querySelector("input").addEventListener("focus", (e) => {
        search.classList.add("isFocus");
      });
      search.querySelector("input").addEventListener("blur", (e) => {
        if (e.target.value == "") {
          search.classList.remove("isFocus");
          if (iSearch) {
            searchContent = null;
            picWrap.innerHTML = "";
            page = 1;
            iSearch = false;
            self.render();
            document.querySelector("header .search .x-icon").style.display =
              "none";
          }
          return;
        }
      });

      search.addEventListener("submit", (e) => {
        e.preventDefault();
        let txtEle = search.querySelector("input#search");
        iSearch = true;
        picWrap.innerHTML = "";
        page = 1;
        searchContent = txtEle.value;
        self.render();
        document.querySelector("header .search .x-icon").style.display =
          "unset";
      });
      let clearSearch = document.querySelector("header .search .x-icon");
      if (clearSearch) {
        clearSearch.addEventListener("click", (e) => {
          e.preventDefault();
          picWrap.innerHTML = "";
          page = 1;
          clearSearch.style.display = "none";
          searchContent = null;
          document.querySelector("form.search input").value = null;
          iSearch = false;
          self.render();
        });
      }
    }

    let panels = document.querySelectorAll("[caitu]");
    if (panels.length > 0) {
      panels.forEach((ele) => {
        ele.addEventListener("click", (e) => {
          panels.forEach((el) => el.classList.remove("active"));
          ele.classList.add("active");
          imgLoad = ele.getAttribute("caitu");
          localStorage.setItem("imgLoad", imgLoad);
          picWrap.innerHTML = "";
          page = 1;
          self.render();
        });
      });
      imgLoad = localStorage.getItem("imgLoad") || imgLoad;
      if (imgLoad) {
        panels.forEach((el) => el.classList.remove("active"));
        panels.forEach((ele) => {
          if (ele.getAttribute("caitu") == imgLoad) {
            ele.classList.add("active");
          }
        });
      }
    }

    let selectType = document.querySelector("#searchForm select#type");
    if (selectType) {
      let inpEle = document.getElementById("keyword");
      selectType.addEventListener("change", (e) => {
        imgLoad = e.target.value;
        let keyword = inpEle.value;
        searchContent = keyword ?? null;
        document.querySelector("header .tit").innerHTML =
          imgLoad == "col" ? "彩色彩票" : "黑白彩票";
        self.picListRender(imgLoad);
      });
      inpEle.addEventListener("keyup", (e) => {
        searchContent = e.target.value;
        imgLoad = selectType.value;
        self.picListRender(imgLoad);
      });
      imgLoad = localStorage.getItem("imgLoad") || "col";
      selectType.value = imgLoad;
      document.querySelector("header .tit").innerHTML =
        imgLoad == "col" ? "彩色彩票" : "黑白彩票";
    }
    let homeIcon = document.getElementById("go-home");
    if (homeIcon) {
      homeIcon.addEventListener("click", () => {
        window.location.href = "index.html";
      });
    }
    let backIcon = document.getElementById("go-back");
    if (backIcon) {
      backIcon.addEventListener("click", () => {
        window.location.href = './'
      });
    }
  },
  picDetail: function (data, swiperPic) {
    data = data ? JSON.parse(data) : { data: null };
    obj = data.data;
    if (obj) {
      document.querySelector("header .tit").innerHTML = obj.name;
      let picArr = obj.url.replace("https://352611.com/", "").split("/");
      let slideItem = "";
      let img =
        hostImg +
        "/images/hk/"+currentNoInfo.year+"/" +
        picArr[0] +
        "/" +
        obj.no +
        "/" +
        picArr[2];
      let noTxt = "";
      for (let no = parseInt(obj.no); no > 0; no--) {
        picArr[1] = no;
        let imgUrl = hostImg + "/images/hk/"+currentNoInfo.year+"/" + picArr.join("/");
        // imgUrl = obj.url.replace("[no]", no);
        if (no > parseInt(obj.no) - 3) {
          slideItem += `<div class="swiper-slide"><img data-src="${imgUrl}" src="${imgUrl}" alt="${obj.name}"/></div>`;
        } else {
          slideItem += `<div class="swiper-slide"><img data-src="${imgUrl}" alt="${obj.name}"/></div>`;
        }
        noTxt += `<li class="item-no ${no == obj.no ? "active" : ""
          }">${no}期</li>`;
      }

      let swiperEle = document.querySelector(".p-swiper .swiper-wrapper");
      if (swiperEle) {
        swiperEle.innerHTML = slideItem;
      }
      let peroid = document.querySelector(".period ul");
      if (peroid) {
        peroid.innerHTML = noTxt;
      }
      let qishurUl = document.querySelector(".qishur-box ul");
      if (qishurUl) {
        qishurUl.innerHTML = noTxt;
      }
      swiperPic();
      getMeta(img, (err, img) => {
        let switem = document.querySelectorAll(".p-swiper .swiper-slide");
        if (switem.length > 0) {
          let offsetHeight = switem[0].offsetHeight;
          switem.forEach((item) => {
            item.style.minHeight = `${offsetHeight}px`;
            item.style.backgroundColor = "#f3f3f3";
          });
        }
      });
      let quishuEle = document.querySelector(".qishur-down");
      if (quishuEle) {
        let qishurBox = document.querySelector(".qishur-box");
        quishuEle.addEventListener("click", () => {
          if (qishurBox) {
            if (qishurBox.classList.contains("hide")) {
              qishurBox.classList.remove("hide");
            } else {
              qishurBox.classList.add("hide");
            }
          }
        });
      }
    }
  },
  swiperPic: function () {
    let period = document.querySelectorAll(".period li");
    let qishur = document.querySelectorAll(".qishur-box li");
    let swiperImg = document.querySelectorAll(".p-swiper img");
    let swiper_setting = {
      spaceBetween: 5,
      dynamicHeight: true,
    };
    let swiper = new Swiper(".p-swiper", swiper_setting);
    swiper.on("slideChange", function () {
      if (period.length > 0) {
        period.forEach((item) => {
          item.classList.remove("active");
        });
        period[swiper.activeIndex].classList.add("active");
        period[swiper.activeIndex].scrollIntoView({
          behavior: "smooth",
          block: "center",
          inline: "center",
        });
        index = swiper.activeIndex;
        let imgSrc = swiperImg[index].getAttribute("data-src");
        swiperImg[index].setAttribute("src", imgSrc);
        if (index + 2 < swiperImg.length) {
          let imgSrc_2 = swiperImg[index + 2].getAttribute("data-src");
          swiperImg[index + 2].setAttribute("src", imgSrc_2);
        }
        if (index + 3 < swiperImg.length) {
          let imgSrc_3 = swiperImg[index + 3].getAttribute("data-src");
          swiperImg[index + 3].setAttribute("src", imgSrc_3);
        }
      }
      if (qishur.length > 0) {
        qishur.forEach((item) => {
          item.classList.remove("active");
        });
        qishur[swiper.activeIndex].classList.add("active");
      }
    });
    if (period.length > 0) {
      period.forEach((ele, index) => {
        ele.addEventListener("click", (e) => {
          swiper.slideTo(index);
          ele.classList.remove("active");
          period[index].classList.add("active");
        });
      });
    }
    if (qishur.length > 0) {
      let qishurBox = document.querySelector(".qishur-box");
      qishur.forEach((ele, index) => {
        ele.addEventListener("click", (e) => {
          swiper.slideTo(index);
          ele.classList.remove("active");
          qishur[index].classList.add("active");
          if (qishurBox) {
            qishurBox.classList.add("hide");
          }
        });
      });
    }
  },
};
document.addEventListener("DOMContentLoaded", function () {
  document.querySelectorAll(".nav-item a").forEach((ele) => {
    ele.addEventListener("click", (e) => {
      e.preventDefault();
      if (["col", "black"].includes(ele.getAttribute("tar"))) {
        imgLoad = ele.getAttribute("tar");
        localStorage.setItem("imgLoad", imgLoad);
        window.location.href = ele.getAttribute("href");
      } else {
        window.open(ele.getAttribute("href"), "_blank");
      }
    });
  });
});

const initLinks = [
  {
    name: "域名① 475044.com",
    url: "https://336640n125.xn--v1b5a2aq1hd.xn--h2brj9c/",
    color: "#FF00FF",
  },
  {
    name: "域名② 476044.com",
    url: "https://336640n125.xn--v1b5a2aq1hd.xn--h2brj9c/",
    color: "#FF00FF",
  },
  {
    name: "看最快开奖结果",
    url: "https://336640n125.xn--81bap8b4azfb0ib.xn--h2brj9c/#891344",
    color: "#FF00FF",
  },
  {
    name: "平特三连肖",
    url: "https://336640n125.xn--v1bm1e5bvb6e.xn--h2brj9c/#891344",
    color: "#FF00FF",
  },
  {
    name: "平码三中三",
    url: "https://336640n125.xn--81bka8j6a.xn--h2brj9c/#891344",
    color: "#FF0000",
  },
  {
    name: "玄机解①码",
    url: "https://336640n125.xn--o1b9b7a1fb.xn--h2brj9c/#891344",
    color: "#0000FF",
  },
  {
    name: "重点买５码",
    url: "https://336640n125.xn--v1bl3ejc7hm0g.xn--h2brj9c/#891344",
    color: "#FF0000",
  },
  {
    name: "一句爆特码",
    url: "https://336640n125.xn--i1b0a1b1dwg.xn--h2brj9c/#891344",
    color: "#0000FF",
  },
  {
    name: "一句解特肖",
    url: "https://336640n125.xn--e2bwjl5fxcb.xn--h2brj9c/#891344",
    color: "#FF00FF",
  },
  {
    name: "600图库",
    url: "https://tkdh365.xn--v1bar0a7grbxa4db6k.xn--i1b6b1a6a2e",
    color: "#FF00FF",
    maxWidthShow: 544
  },
]

const screenWidth = window.innerWidth
const linksElm = document.getElementById("link-ads");
const linksHtml = initLinks.map(item => {
  return `<a href="${item.url}" style="color:${item.color};display:${(screenWidth || 0) > item.maxWidthShow ? "none" : "flex"}"  target="_blank">${item.name}</a>`
}).join("");
if(linksElm) linksElm.innerHTML = linksHtml;