click.js 11.2 KB
/*
 * @Author: 前端 qianduan01@didihu.com.cn
 * @Date: 2024-04-08 11:28:48
 * @LastEditors: 前端 qianduan01@didihu.com.cn
 * @LastEditTime: 2024-04-26 10:04:31
 * @FilePath: \gl_tape\mixin\click.js
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
const recorderManager = uni.getRecorderManager();
const plug = uni.requireNativePlugin("html5app-recordaudio");
const UPLOAD_STATUS = {
  // 上传状态
  success: 1,
  fail: 2,
};
import upload from "@/utils/ossUploadFile/uploadFile.js";
import fileManager from "@/utils/file/FileManager.js";
import { mapMutations, mapState } from "vuex";
import utils from "@/utils/utils.js";
export default {
  data() {
    return {
      voicePath: "",
      timer: null,
      times: 0,
      timeout: 240,
      reaction: 1,
    };
  },
  mounted() {
    // this.checkRecord();
    // fileManager.writeFile("123.txt", 555);
    // fileManager.readFile("file://123.txt").then((res) => {
    //   // res 读取的文件内容
    //   console.log(res);
    // });

    // 获取当前页面栈数组
    const pages = getCurrentPages();
    const currentPage = pages[pages.length - 1];
    const route = currentPage.route;
    const url = ["pages/home/home", "pages/boutique/index"];
    if (url.includes(route)) return;
    this.initTime();
    // this.checkVoice();
  },
  computed: {
    ...mapState("audio", ["receptionStatus", "booksList", "audioInfo"]),
    ...mapState(["user.customerInfo"]),
  },
  created() {
    console.log("created");
  },
  onHide() {
    console.log("隐藏");
    // recorderManager.stop();
    // recorderManager.start({
    //   duration: 10000,
    // });
  },
  onShow() {
    const userInfo = uni.$storage.get("userInfo") || {};
    if (!userInfo.shopMerchantId || !userInfo.shopMerchantName) {
      uni.$storage.rm("userInfo");
      uni.$storage.rm("sessionId");
      uni.reLaunch({
        url: "/pages/common/login",
      });
      return;
    }
    // console.log(utils.requestAndroidPermission());
  },
  methods: {
    ...mapMutations("audio", [
      "setReceptionStatus",
      "setBooks",
      "setAudioInfo",
    ]),
    //关闭提示
    tipCancel() {
      this.stopAudio();
      this.setReceptionStatus(0);
      this.setAudioInfo({ endReasonType: 1 });
      if (this.$refs.tipBox) {
        this.$refs.tipBox.close();
        let { sceneType } = uni.$storage.get("userInfo");
        uni.reLaunch({
          url: sceneType == 0 ? "/pages/home/home" : "/pages/boutique/index",
        });
      }
    },
    //结束提示
    tipConfirm() {
      this.times = 0;
      this.$refs.tipBox?.close();
    },
    //检查缓存录音
    checkVoice() {
      const file = uni.$storage.get("storageFile");
      if (file) this.uploadVoice(file);
    },
    getParams() {
      const { shopMerchantId, phone, sceneType } = uni.$storage.get("userInfo"),
        { customerName, phoneNumber, salesUuid, carModel, staffName } =
          this.$store.state.user.customerInfo,
        receptionCustomerPaySourceList = this.booksList.map((item) => {
          return {
            id: item.id,
            sourceType: item.id,
            sourceUrl: item.imgUrl,
          };
        }),
        { receptionStartTime, receptionEndTime, endReasonType } =
          this.audioInfo,
        params = {
          carModel,
          endReasonType, //原因 1.异常 0.正常
          customerName,
          phoneNumber,
          loginPhone: phone,
          salesName: staffName,
          salesUuid,
          receptionStatus: this.receptionStatus, //接待结果 1.成交 0.战败
          receptionStartTime,
          receptionEndTime,
          receptionCustomerPaySourceList, //1.付款凭证文件路径 2.客户购车发票文件路径 3.客户延保合同文件路径
          merchantId: shopMerchantId,
          bussinessType: sceneType == 0 ? 1 : 2, // sceneType 0延保 1精品。 bussinessType 1.延保 2.轻改
        };
      return params;
    },
    //保存录音记录及其他信息
    async uploadVoice(tempFilePath) {
      try {
        const params = Object.assign(this.getParams(), {
          recordUrlList: tempFilePath,
        });
        if (params.customerName && params.phoneNumber && params.salesUuid) {
          uni.$api.commonApi.saveRecCustomer(params).then((res) => {
            console.log(res, params);
          });
        }
        this.setBooks([]);
        this.$store.dispatch("clearCustomerInfo");
        this.setReceptionStatus(1);
        this.setAudioInfo({ endReasonType: 0, audioStatus: "finish" });
        uni.$storage.set("storageFile", "");
      } catch (error) {
        this.$store.dispatch("clearCustomerInfo");
        console.log(error);
      }
    },
    //开始录音
    async startAudio() {
      if (this.audioInfo.audioStatus == "start") return;
      this.setAudioInfo({ audioList: [], audioStatus: "start" });
      this.initTime();
      recorderManager.start({
        duration: 600000,
        sampleRate: 16000,
        numberOfChannels: 1,
      });
      recorderManager.onStop(async (res) => {
        console.log("结束录音");
        if (this.audioInfo.audioStatus == "start") {
          uni.getRecorderManager().start({
            duration: 600000,
            sampleRate: 16000,
            numberOfChannels: 1,
          });
        }
        if (this.audioInfo.audioStatus == "no") {
          setTimeout(() => {
            uni.hideLoading();
          }, 2000);

          uni.removeSavedFile({
            filePath: res.tempFilePath,
            complete: function (res) {
              console.log(res);
            },
          });
          return;
        }
        const isContinue = this.hasErrorFile();
        if (isContinue) {
          this.handleErrorFile(res.tempFilePath, UPLOAD_STATUS.fail);
          return;
        }
        //模拟上传失败
        const x = Math.random() * 10 > 5 ? "" : "x";
        const result = await this.checkUploadFile(res.tempFilePath + x);
        if (result instanceof Error) {
          console.error("上传失败:", result);
          const { customerName, phoneNumber, salesUuid, carModel, staffName } =
            this.$store.state.user.customerInfo;
          const { name } = uni.$storage.get("userInfo");
          this.$sendSentry(
            `重试多次失败:手机号-${phoneNumber} 姓名-${customerName} 销售-${staffName} 车型-${carModel} 员工-${name},失败原因-${result}`
          );
          const saveResult = await uni.saveFile({
            tempFilePath: res.tempFilePath,
          }); // 保存文件到本地
          this.handleErrorFile(saveResult[1].savedFilePath, UPLOAD_STATUS.fail);
          return;
        } else {
          this.handleErrorFile(result, UPLOAD_STATUS.success);
        }
        const storageFile = [...this.audioInfo.audioList, result];
        uni.$storage.set("storageFile", storageFile);
        this.setAudioInfo({ audioList: storageFile });
        if (this.audioInfo.audioStatus == "start") {
          return;
        }
        this.uploadVoice(storageFile);
      });
    },
    /**保存记录*/
    saveRecord() {
      console.log("保存记录");
      const recordUrlList = JSON.parse(uni.$storage.get("errorFile") || "[]");
      let recordList = JSON.parse(uni.$storage.get("recordList") || "[]");
      recordList = [
        {
          ...this.getParams(),
          recordUrlList,
        },
        ...recordList,
      ];
      uni.$storage.set("recordList", JSON.stringify(recordList));
      uni.hideLoading();
      uni.$storage.set("errorFile", "");
      console.log(recordList, "recordList");
    },
    /**是否存在错误文件*/
    hasErrorFile() {
      const fileList = JSON.parse(uni.$storage.get("errorFile") || "[]");
      const errorFileList = fileList.filter(
        (item) => item.status == UPLOAD_STATUS.fail
      );
      return errorFileList.length > 0;
    },
    /**处理失败的文件*/
    handleErrorFile(file, status) {
      const errorFileList = JSON.parse(uni.$storage.get("errorFile") || "[]");
      const errorFile = [...errorFileList, { file, status }];
      uni.$storage.set("errorFile", JSON.stringify(errorFile));
      console.log(this.audioInfo.audioStatus, errorFile, "errorFile");
      if (
        this.audioInfo.audioStatus == "end" &&
        errorFile.find((i) => i.status == UPLOAD_STATUS.fail)
      ) {
        this.saveRecord();
      }
      if (
        this.audioInfo.audioStatus == "end" &&
        errorFile.every((i) => i.status == UPLOAD_STATUS.success)
      ) {
        uni.$storage.set("errorFile", "");
      }
    },
    async checkUploadFile(tempFilePath) {
      console.log(tempFilePath);
      let attempt = 0;
      let errorMsg = "";
      while (attempt < 2) {
        try {
          const result = await upload(tempFilePath);
          // 上传成功
          return result;
        } catch (error) {
          if (attempt == 0) {
            const { customerName, phoneNumber } =
              this.$store.state.user.customerInfo;
            this.$sendSentry(
              `第一次上传失败:姓名-${customerName},手机号-${phoneNumber},文件${tempFilePath}`
            );
          }
          errorMsg = error;
          attempt++;
          // 等待一段时间后重试
          await new Promise((resolve) => setTimeout(resolve, 3000)); // 3秒后重试
        }
      }
      // 达到最大尝试次数后,如果上传仍然失败,可以进行相应的处理
      console.error("上传失败,达到最大尝试次数");
      // 返回一个错误或者进行其他操作
      return new Error(errorMsg);
    },
    //结束接待
    stopAudio: utils.throttle(async function (status) {
      // const result = await this.$permision.requestAndroidPermission(
      //   "android.permission.RECORD_AUDIO"
      // );
      // if (result !== 1) {
      //   uni.showToast({
      //     title: "为了记录语音通话,请打开录音权限",
      //     icon: "none",
      //   });
      //   return;
      // }
      if (this.audioInfo.audioStatus != "start") {
        return;
      }

      let finish_timer = null;
      this.setAudioInfo({ audioStatus: "end" });
      //直接退出
      uni.showLoading({
        mask: true,
        title: status ? "" : "处理中请稍后...",
      });
      this.times = 0;
      clearInterval(this.timer);
      this.timer = null;
      if (status) {
        this.setAudioInfo({ audioStatus: "no" });
      }
      recorderManager.stop();
      if (!status)
        finish_timer = setInterval(() => {
          if (this.audioInfo.audioStatus == "finish") {
            uni.hideLoading();
            clearInterval(finish_timer);
          }
        }, 300);
    }, 500),
    //监听点击事件
    initTime() {
      if (this.audioInfo.audioStatus != "start") return;
      this.timer = setInterval(() => {
        console.log(this.times);
        this.times++;
        if (this.times >= this.timeout) {
          this.$refs.tipBox?.open();
        }
        if (this.times >= this.reaction + this.timeout) {
          //结束接待
          this.tipCancel();
          clearInterval(this.timer);
        }
      }, 1000 * 10);
    },
    handleTouchStart() {
      this.times = 0;
    },
  },
  beforeCreate() {
    clearInterval(this.timer);
    this.timer = null;
  },
};