<template>
  <div id="app">
    <router-view />
    <!-- 语音播报 -->
    <iframe id="iframeDom" allow="autoplay" style="display:none" :src="src" sandbox="allow-scripts"></iframe>
    <audio class="audio" ref="audio" :src="url" controlsList="nodownload" controls autoplay hidden>
    </audio>
    <!-- usb自动打印 -->
    <usb-auto-print @printOver="printOver" :orderType='orderType' :printNum="printNum" :printData="printData"></usb-auto-print>
    <!-- 自动更新提示 -->
    <el-dialog title="更新提示" :visible.sync="modal" width="600px">
      <div class="tips-modal" v-if="tipsModal">
        <span slot="footer" class="dialog-footer">
          <el-button size="mini" @click="modal = false">取 消</el-button>
          <el-button size="mini" type="primary" @click="modal = false">确 定</el-button>
        </span>
      </div>
      <el-progress v-if="progressModal" :percentage="downloadPercent" status="success"></el-progress>
    </el-dialog>
  </div>
</template>

<script>
import { getSoundMsg } from "./api/setting.js";
import { getPrintOrderInfos } from "./api/order.js";
import bus from "./common/bus.js";
import UsbAutoPrint from "./common/UsbAutoPrint";
import { mapGetters } from "vuex";
export default {
  name: "App",
  data() {
    return {
      url: "https://pc.liebaoai.cn/audio/test.mp3",
      audioList: [
        "https://pc.liebaoai.cn/audio/new-order.mp3",
        "https://pc.liebaoai.cn/audio/lower-than.mp3",
        "https://pc.liebaoai.cn/audio/missed-orders.mp3",
        "https://pc.liebaoai.cn/audio/not-enough.mp3",
        "https://pc.liebaoai.cn/audio/order-received.mp3",
        "https://pc.liebaoai.cn/audio/rider-cancel.mp3",
        "https://pc.liebaoai.cn/audio/rider-go-cancel.mp3",
        "https://pc.liebaoai.cn/audio/user-go-cancel.mp3",
        "https://pc.liebaoai.cn/audio/over-time.mp3",
      ],
      src: "https://pc.liebaoai.cn/audio/alone.mp3",
      timer: null,
      openMsg: false,
      printNum: 0,
      printData: {},
      printList: [],
      orderType: 1,
      usbPrinterList: [],
      modal: false,
      tipsModal: true,
      progressModal: false,
      downloadPercent: 0,
    };
  },
  components: {
    UsbAutoPrint,
  },
  computed: {
    ...mapGetters(["usbPrinter"]),
  },
  watch: {
    usbPrinter: {
      handler(newVal) {
        this.usbPrinterList = newVal.filter((v) => {
          return v.status;
        });
      },
      deep: true,
      immediate: true,
    },
  },
  created() {},
  mounted() {
    window.addEventListener("contextmenu", this.rightClick, false);
    // 进来准备关闭新订单提醒声音了
    bus.$on("closeGetSoundMsg", () => {
      console.log("进来准备关闭新订单提醒声音了");
      clearInterval(this.timer);
      this.timer = null;
    });
    // 进来准备开启新订单提醒声音了
    bus.$on("openGetSoundMsg", () => {
      console.log("进来准备开启新订单提醒声音了");
      this.timer = setInterval(() => {
        this.getSoundMsg();
      }, 5000);
    });
    bus.$on("startUsbPrint", (e) => {
      console.log("进来准备开始USB打印");
      if (!this.usbPrinterList.length) return;
      this.usbPrint(e, "", 1);
    });
    // 诱导用户触发点击动作，否则页面刷新后不会自动播放音频
    let userInfo = localStorage.getItem("userInfo");
    if (userInfo) {
      let nickname = JSON.parse(userInfo).nickname;
      this.$confirm(`当前登录账号：${nickname}`, "提示", {
        confirmButtonText: "确定",
        showCancelButton: false,
        type: "warning",
      }).then(() => {});
    }
    // electron 自动更新
    // 页面刷新的时候，执行检查更新操作
    // ipcRenderer.send("checkForUpdate");
    // // 每隔10分钟再次检查
    // setInterval(() => {
    //   // 每 10 分钟检查一次是否需要更新
    //   ipcRenderer.send("checkForUpdate");
    // }, 600000);
    // // 注意：“downloadProgress”事件可能存在无法触发的问题，只需要限制一下下载网速就好了
    // ipcRenderer.on("downloadProgress", (event, progressObj) => {
    //   // 如果发现有新的版本需要更新，立即弹出更新对话框
    //   this.progressModal = true;
    //   this.downloadPercent = progressObj.percent.toFixed(2) || 0;
    // });

    // ipcRenderer.on("message", (event, text) => {
    //   // 检测到新版本
    //   if (text.version) {
    //     this.modal = true;
    //     this.version = text.version;
    //     this.versionDes = text.versionDes ? text.versionDes : "";
    //     this.tips = text;
    //   }
    // });
  },
  beforeDestroy() {
    window.removeEventListener("contextmenu", this.rightClick, false);
    clearInterval(this.timer);
    this.timer = null;
  },
  destroyed() {},
  methods: {
    rightClick() {
      console.log("----右击------");
      window.ipcRenderer && window.ipcRenderer.send("show-context-menu");
    },
    printOver(isRemove) {
      // 是否需要去除已打印的对象
      if (isRemove) {
        this.printList = this.printList.slice(1);
        if (!this.printList.length) {
          return;
        }
      }
      this.printData = this.printList[0];
      this.printNum += 1;
    },
    usbPrint(orderId, waimaiOrderId, orderType = 1) {
      // usb自动打印新订单、预约单
      getPrintOrderInfos({ orderId, waimaiOrderId }).then((res) => {
        // console.log("返回内容：", res);
        if (res.code === 200 && res.data) {
          let data = res.data;
          this.printData = data;
          this.orderType = orderType;
          this.printNum += 1;
        }
      });
    },
    getSoundMsg() {
      getSoundMsg().then((res) => {
        if (res.code === 200) {
          if (res.data) {
            console.log("提示音:", res.data.sound);
            let data = res.data;
            let name = data.sound.slice(0, data.sound.indexOf("."));
            // 打印新订单、取消单
            let orderType;
            if (name === "new-order") {
              orderType = 1;
              this.usbPrint(data.orderId, data.waimaiOrderId, orderType);
            }
            if (name.includes("cancel")) {
              orderType = 2;
              this.usbPrint(data.orderId, data.waimaiOrderId, orderType);
            }
            let url = this.audioList.filter((v) => {
              return v.includes(name);
            })[0];
            this.url = url + "?t=" + new Date().getTime();
          }
        } else {
          this.$message({
            type: "error",
            message: res.msg,
          });
        }
      });
    },
  },
};
</script>

<style>
body {
  margin: 0;
  padding: 0;
}
#app {
  font-family: "Avenir", Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  margin: 0;
  padding: 0;
}
</style>
