// index.js
// 获取应用实例
import { VueLikePage } from "../../utils/page";
import { randomWord } from "../../utils/utils";
import { isPhoneX } from "./../../utils/tools";

import { CDN_URL, API_BASE_URL, VIDEO_BASE_URL, app } from "../../config/index";

let socket_io = require("../../utils/socket.io-mp.js");

let timer = null;

let projectid = null;

let isLoading = false;

import Router from "../../utils/routes";

VueLikePage([], {
  data: {
    cdn_url: "",
    isIphoneX: false,
    canTap: true,
    rndWord: randomWord(false, 8),
    info: {
      banner: {},
      sceneTitleImg: {},
      recordTitleImg: {},
      rescan: {},
      activeSceneBdImg: {},
    },
    scenes: [],
    records: [],
    autoplay: true,
    interval: 3000,
    duration: 500,
    current: 0,
    currentScene: 1,
    daojishi: 0,
    isShot: false,
    isRecord: false,
    isVideo: false,
    popupVisible: false,
    recordjishi: 10,
    type: "",
    authorCode: "",
    isOtherZhanYong: true,
  },
  methods: {
    scanCode: function (e) {
      wx.scanCode({
        onlyFromCamera: true,
        success(res) {
          wx.reLaunch({
            url: `/${res.path}`,
          });
        },
      });
    },

    swiperChange: function (e) {
      this.setData({
        current: e.detail.current,
      });
    },

    onShow() {
      this.setData({
        rndWord: randomWord(false, 8),
      });
    },

    gotoRecord(e) {
      let { id } = e.currentTarget.dataset;

      let item = this.data.records.find((i) => i.id == id);

      Router.push({
        url: "work",
        query: item.codeData,
      });

      console.log(item);
    },

    gotoWork() {
      //日期 new Date().Format("yyyy.MM.dd hh.mm.ss");
      //编号 new Date().Format("yyyyMMddhhmmss");
      timer && clearTimeout(timer);
      timer = null;

      let record = {
        projectid,
        type: this.data.type,
        id: this.data.currentScene,
        rdw: encodeURIComponent(this.data.authorCode),
      };

      Router.push({
        url: "work",
        query: record,
      });

      this.setData({
        records: [
          {
            id: new Date().Format("yyyyMMddhhmmss"),
            date: new Date().Format("yyyy.MM.dd hh.mm.ss"),
            type: this.data.type,
            codeData: record,
          },
        ]
          .concat(this.data.records)
          .slice(0, 15),
      });

      wx.setStorageSync("records", JSON.stringify(this.data.records));

      this.reset();
    },

    reset(noswitch = false) {
      this.setData({
        daojishi: 0,
        isShot: false,
        isRecord: false,
        currentScene: this.data.scenes[0] ? this.data.scenes[0].id : 1,
        recordjishi: 10,
      });
      if (!noswitch) {
        app.websocket &&
          app.websocket.send({
            data: "switch 1",
          });
      }

      setTimeout(() => {
        app.hideLoading();
      });
    },

    handleWebSocket: function () {
      if (app.websocket) {
        return;
      }

      app.websocket = socket_io(API_BASE_URL, {
        transports: ["websocket"],
      });

      app.websocket.on("connect", () => {
        console.log("SOCKET连接成功");
        app.emitEvent.request((data) => {
          console.log(data, 1111111);
        });
      });

      app.websocket.on("ForceOffline", () => {
        app.showAlert("服务器连接失败，请稍后再试", () => {
          wx.reLaunch({
            url: "/pages/start/index",
          });
        });

        console.log("ForceOffline成功");
      });
    },

    onHide: function () {
      this.disconnect();
    },

    onLoad: function (options) {
      console.log("options: ", options);

      wx.showLoading({
        title: "资源加载中",
      });

      if (options && options.scene) {
        const [machineid, authorCode] = options.scene.split("_");

        app.id = machineid;
        // 1、获取二维码传参
        if (authorCode) {
          this.setData({
            authorCode: decodeURIComponent(authorCode),
          });
          this.start(this.data.authorCode);
        }

        if (wx.getStorageSync("records")) {
          this.setData({
            records: JSON.parse(wx.getStorageSync("records")),
          });
        }
      } else {
        this.getData();
      }

      // wx.setStorageSync('records', JSON.stringify(this.data.records))

      isPhoneX().then((res) => {
        this.setData({
          isIphoneX: res,
        });
      });
      // let tmp = g_app.globalData.scenes.map(item=>{
      //   return {id:item}
      // })

      // this.setData({
      //   scenes: tmp,
      //   currentScene:tmp[0].id
      // })
    },
    // 横琴是ZHS2409020-1，替换 ZHS2305758-1
    getData(prjId = "ZHS2305758-1", scenes) {
      this.setData({
        cdn_url: CDN_URL + "/" + prjId,
      });

      wx.request({
        url:
          `${VIDEO_BASE_URL}project/4dage-sxb/${prjId}/config.json?t=` +
          new Date().getTime(),
        success: ({ data: { scenes: sourceScenes, title, ...rest } }) => {
          let scenesData = sourceScenes;
          if (scenes) {
            // 只展示 scenes 中存在的id
            scenesData = scenes.map((id) =>
              sourceScenes.find((scene) => id === scene.id)
            );
          }
          this.setData(
            {
              currentScene: scenesData[0].id,
              scenes: scenesData,
              info: rest,
            },
            () => {
              wx.hideLoading();
            }
          );
          wx.setNavigationBarTitle({
            title: title,
          });
        },
      });

      projectid = prjId;
    },

    daojishiFn(key, time, fn = () => {}) {
      intel && clearInterval(intel);
      let intel = null;

      let titop = time;

      intel = setInterval(() => {
        titop -= 1;
        let kv = {};

        kv[key] = titop;

        this.setData(kv);
        if (titop <= 0) {
          fn();
          intel && clearInterval(intel);
          return;
        }
      }, 1000);
    },

    shot: function (e) {
      if (isLoading) return;

      isLoading = true;

      app.checkOperationTimeout(true);
      let { id } = e.currentTarget.dataset;

      this.setData({
        type: id,
        popupVisible: true,
      });

      // if (!app.sendCheck()) {
      //   return;
      // }

      //录像
      if (id == "0") {
        let intel = null;
        intel && clearInterval(intel);

        this.setData({
          isShot: true,
          isVideo: true,
        });
        setTimeout(() => {
          this.setData({
            daojishi: 3,
          });

          app.emitEvent.switchMachine(this.data.currentScene);

          setTimeout(() => {
            app.emitEvent.Video(this.data.authorCode);

            // 为了同步机器的倒计时
            setTimeout(() => {
              this.daojishiFn("daojishi", this.data.daojishi, () => {
                this.setData({
                  isRecord: true,
                });

                this.daojishiFn("recordjishi", this.data.recordjishi, () => {
                  isLoading = false;
                  wx.showLoading({
                    title: "生成视频中...",
                  });
                  this.setData({
                    popupVisible: false,
                  });
                  setTimeout(() => {
                    // 不发送switch
                    this.gotoWork();
                    this.disconnect(true);
                    wx.hideLoading();
                    // 上传倒计时
                  }, 30 * 1000);
                });
              });
            }, 500);
          }, 1000);
        }, 500);
      }

      //拍照
      else {
        let intel = null;
        intel && clearInterval(intel);

        this.setData({
          isShot: true,
          isVideo: false,
        });

        setTimeout(() => {
          this.setData({
            daojishi: 3,
          });

          app.emitEvent.switchMachine(this.data.currentScene);

          setTimeout(() => {
            app.emitEvent.Photo(this.data.authorCode);

            // 为了同步机器的倒计时
            setTimeout(() => {
              this.daojishiFn("daojishi", this.data.daojishi, () => {
                isLoading = false;
                wx.showLoading({
                  title: "生成图片中...",
                  // mask: true,
                });
                this.setData({
                  popupVisible: false,
                });
                setTimeout(() => {
                  // 不发送switch
                  this.gotoWork();
                  this.disconnect(true);
                  wx.hideLoading();
                }, 4 * 1000);
              });
            }, 500);
          }, 1000);
        }, 500);
      }
    },

    tapSelect: function (e) {
      app.checkOperationTimeout(false, () => {
        app.showAlert("抱歉，因您长时间使用，让下一位小伙伴体验吧", () => {
          this.disconnect();
        });
      });

      if (!this.data.canTap) {
        return;
      }

      let { id } = e.currentTarget.dataset;
      if (id == this.data.currentScene) {
        return;
      }

      this.setData({
        canTap: false,
      });

      setTimeout(() => {
        this.setData({
          canTap: true,
        });
        app.hideLoading();
      }, 3 * 1000);

      wx.showLoading({
        title: "切换中...",
        mask: true,
      });
      this.setData({
        currentScene: id,
      });
      app.emitEvent.switchMachine(id);
    },

    disconnect(noswitch = false) {
      this.reset(noswitch);
      if (app.websocket) {
        app.emitEvent.close();
        app.websocket.disconnect();
        app.websocket = null;
        this.setData({
          isOtherZhanYong: true,
        });
      }
    },

    start: function (authorCode) {
      if (app.websocket) {
        return;
      }

      app.websocket = socket_io(API_BASE_URL, {
        transports: ["websocket"],
      });

      app.websocket.on("connect", () => {
        console.log("SOCKET连接成功");
        wx.showLoading({
          mask: true,
          title: "正在连接机器",
        });

        let linktimer = setTimeout(() => {
          clearTimeout(linktimer);
          wx.showToast({
            title: "网络异常，请稍后再试",
            icon: "none",
          });
          wx.hideLoading();
        }, 5000);
        app.emitEvent.request((data) => {
          // 校验成功后解除被他人占用情况
          clearTimeout(linktimer);
          wx.hideLoading();
          this.setData({
            isOtherZhanYong: false,
          });
          app.checkOperationTimeout(false, () => {
            app.showAlert("抱歉，因您长时间使用，让下一位小伙伴体验吧", () => {
              this.disconnect();
            });
          });
          app.websocket.on("ForceOffline", () => {
            console.log("ForceOffline成功");
            app.checkOperationTimeout(true);
            this.disconnect();
          });

          app.websocket.on("error", () => {
            this.disconnect();
            app.showAlert("服务器异常，请稍后再试");
          });

          if (data == 808) {
            // return app.showAlert("机器被占用，请稍后再试");
            app.checkOperationTimeout(true);
            this.disconnect();
          }

          if (data == 404 || data == 505) {
            app.checkOperationTimeout(true);
            this.disconnect();
            // app.showAlert("网络异常，请稍后再试");
          }

          try {
            const res = JSON.parse(data);
            this.getData(res.projectID, res.scenes);
          } catch (err) {
            console.log(err);
          }
          console.log(data, "data");
        }, authorCode);
      });
    },
  },
});
