"use strict";
const common_vendor = require("../../common/vendor.js");
const common_assets = require("../../common/assets.js");
const sheep_index = require("../../sheep/index.js");
require("../../sheep/request/index.js");
require("../../sheep/api/index.js");
require("../../sheep/api/distri/score.js");
require("../../sheep/api/distri/share.js");
require("../../sheep/api/distri/team.js");
require("../../sheep/api/infra/file.js");
require("../../sheep/config/index.js");
require("../../sheep/api/member/address.js");
require("../../sheep/api/member/auth.js");
require("../../sheep/api/member/point.js");
require("../../sheep/api/member/signin.js");
require("../../sheep/api/member/social.js");
require("../../sheep/api/member/user.js");
require("../../sheep/api/migration/app.js");
require("../../sheep/api/migration/chat.js");
require("../../sheep/api/migration/index.js");
require("../../sheep/api/migration/third.js");
require("../../sheep/api/pay/channel.js");
require("../../sheep/api/pay/order.js");
require("../../sheep/api/pay/wallet.js");
require("../../sheep/api/product/category.js");
require("../../sheep/api/product/comment.js");
require("../../sheep/api/product/favorite.js");
require("../../sheep/api/product/history.js");
require("../../sheep/api/product/spu.js");
require("../../sheep/api/promotion/activity.js");
require("../../sheep/api/promotion/article.js");
require("../../sheep/api/promotion/bargain.js");
require("../../sheep/api/promotion/combination.js");
require("../../sheep/api/promotion/coupon.js");
require("../../sheep/api/promotion/diy.js");
require("../../sheep/api/promotion/rewardActivity.js");
require("../../sheep/api/promotion/seckill.js");
require("../../sheep/api/system/area.js");
require("../../sheep/api/system/voice.js");
require("../../sheep/api/trade/afterSale.js");
require("../../sheep/api/trade/brokerage.js");
require("../../sheep/api/trade/cart.js");
require("../../sheep/api/trade/config.js");
require("../../sheep/api/trade/delivery.js");
require("../../sheep/api/trade/order.js");
require("../../sheep/url/index.js");
require("../../sheep/store/index.js");
require("../../sheep/store/app.js");
require("../../sheep/platform/index.js");
require("../../sheep/platform/provider/wechat/index.js");
require("../../sheep/platform/provider/wechat/miniProgram.js");
require("../../sheep/platform/provider/apple/index.js");
require("../../sheep/platform/share.js");
require("../../sheep/router/index.js");
require("../../sheep/hooks/useModal.js");
require("../../sheep/helper/index.js");
require("../../sheep/helper/test.js");
require("../../sheep/helper/digit.js");
require("../../sheep/helper/throttle.js");
require("../../sheep/platform/pay.js");
require("../../sheep/store/user.js");
require("../../sheep/store/cart.js");
require("../../sheep/store/sys.js");
require("../../sheep/store/modal.js");
require("../../sheep/config/zIndex.js");
if (!Array) {
  const _easycom_s_layout2 = common_vendor.resolveComponent("s-layout");
  _easycom_s_layout2();
}
const _easycom_s_layout = () => "../../sheep/components/s-layout/s-layout.js";
if (!Math) {
  _easycom_s_layout();
}
const minRecordingTime = 500;
const cancelOffset = 280;
const _sfc_main = {
  __name: "speechtotext",
  setup(__props) {
    const {
      safeAreaInsets,
      safeArea
    } = sheep_index.sheep.$platform.device;
    const sysNavBar = sheep_index.sheep.$platform.navbar;
    const messagesHeight = safeArea.height - sysNavBar - 20 - 60;
    const messages = common_vendor.ref([]);
    const isRecording = common_vendor.ref(false);
    let startTime = common_vendor.ref(null);
    const recordingDuration = common_vendor.ref("");
    let intervalId = null;
    const startTouchY = common_vendor.ref(0);
    let mediaRecorder = null;
    let audioChunks = [];
    let isCancelled = common_vendor.ref(false);
    common_vendor.onMounted(() => {
      navigator.mediaDevices.getUserMedia({
        audio: true
      }).then((stream) => {
        mediaRecorder = new MediaRecorder(stream);
        mediaRecorder.ondataavailable = (event) => {
          audioChunks.push(event.data);
        };
        mediaRecorder.onstop = () => {
          if (!isCancelled.value) {
            sendDuration();
          }
          audioChunks = [];
        };
      }).catch((error) => {
        console.error("Error accessing media devices.", error);
      });
    });
    async function sendAudioToServer(audioBlob, audioUrl, duration, messageIndex) {
      const formData = new FormData();
      formData.append("audio_file", audioBlob);
      try {
        const response = await fetch("https://zxgz.newfeifan.cn/voice2text/", {
          method: "POST",
          body: formData
        });
        const data = await response.json();
        if (data.success) {
          messages.value[messageIndex].transcription = data.transcription;
        }
        console.log("Server response:", data);
      } catch (error) {
        console.error("Error sending audio file:", error);
      }
    }
    const sendDuration = () => {
      const audioBlob = new Blob(audioChunks, {
        type: "audio/mpeg"
      });
      const audioUrl = URL.createObjectURL(audioBlob);
      const duration = Math.max(Math.floor((/* @__PURE__ */ new Date() - startTime.value) / 1e3), 1);
      const messageIndex = messages.value.push({
        duration,
        audioUrl,
        transcription: ""
        // 初始为空
      }) - 1;
      sendAudioToServer(audioBlob, audioUrl, duration, messageIndex);
      common_vendor.nextTick$1(() => {
        let messagesElement = document.getElementById("messages");
        messagesElement.scrollTop = messagesElement.scrollHeight;
      });
    };
    const updateDuration = () => {
      const currentDuration = Math.floor((/* @__PURE__ */ new Date() - startTime.value) / 1e3);
      recordingDuration.value = currentDuration + "s";
      if (currentDuration >= 60) {
        stopRecording(new Event("mouseup"));
      }
    };
    const startRecording = (event) => {
      if (!isRecording.value && (event.type === "mousedown" || event.type === "touchstart")) {
        startTime.value = /* @__PURE__ */ new Date();
        isRecording.value = true;
        intervalId = setInterval(updateDuration, 1e3);
        recordingDuration.value = "1s";
        event.preventDefault();
        startTouchY.value = event.touches ? event.touches[0].clientY : 0;
        audioChunks = [];
        isCancelled.value = false;
        mediaRecorder.start();
      }
    };
    const stopRecording = (event) => {
      if (isRecording.value && (event.type === "mouseup" || event.type === "touchend" || event.type === "mouseleave" || event.type === "touchcancel")) {
        clearInterval(intervalId);
        isRecording.value = false;
        recordingDuration.value = "";
        if (/* @__PURE__ */ new Date() - startTime.value >= minRecordingTime) {
          mediaRecorder.stop();
        } else {
          console.log("录音时间太短，不保存");
        }
      }
    };
    const cancelRecording = () => {
      if (isRecording.value) {
        clearInterval(intervalId);
        console.log("录音取消");
        isCancelled.value = true;
        mediaRecorder.stop();
        resetRecording();
      }
    };
    const resetRecording = () => {
      isRecording.value = false;
      recordingDuration.value = 0;
      startTime.value = null;
      audioChunks = [];
    };
    const handleTouchMove = (event) => {
      const currentTouchY = event.touches[0].clientY;
      if (startTouchY.value - currentTouchY > cancelOffset) {
        cancelRecording();
      }
    };
    const playRecording = (index) => {
      const message = messages.value[index];
      const audio = new Audio(message.audioUrl);
      audio.play();
    };
    return (_ctx, _cache) => {
      return common_vendor.e({
        a: common_vendor.f(messages.value, (message, index, i0) => {
          return common_vendor.e({
            a: common_vendor.t(message.duration),
            b: message.transcription != null && message.transcription != ""
          }, message.transcription != null && message.transcription != "" ? {
            c: common_vendor.t(message.transcription)
          } : {}, {
            d: index,
            e: common_vendor.o(($event) => playRecording(index), index)
          });
        }),
        b: common_assets._imports_0$3,
        c: messagesHeight + "px",
        d: common_vendor.o(startRecording),
        e: common_vendor.o(stopRecording),
        f: common_vendor.o(cancelRecording),
        g: common_vendor.o(startRecording),
        h: common_vendor.o(stopRecording),
        i: common_vendor.o(cancelRecording),
        j: common_vendor.o(handleTouchMove),
        k: isRecording.value
      }, isRecording.value ? {
        l: common_vendor.t(recordingDuration.value)
      } : {}, {
        m: common_vendor.p({
          title: "语音转文字"
        })
      });
    };
  }
};
const MiniProgramPage = /* @__PURE__ */ common_vendor._export_sfc(_sfc_main, [["__scopeId", "data-v-c5c3bce2"], ["__file", "D:/zx/mall-front-app/pages/chat/speechtotext.vue"]]);
wx.createPage(MiniProgramPage);
