"use strict";
const common_vendor = require("../../common/vendor.js");
const api_user = require("../../api/user.js");
const _sfc_main = {
  data() {
    return {
      mediaSource: "",
      // 拍摄的照片或视频路径
      isCameraReady: false,
      cameraContext: null,
      isPageLoaded: false,
      // 添加页面加载状态标记
      mode: "photo",
      // 默认为拍照模式，可选值：photo, video
      isRecording: false,
      // 是否正在录制视频
      recordingTime: 0,
      // 录制时间（秒）
      recordingTimer: null,
      // 录制计时器
      photoUrl: ""
      // 存储上传后返回的图片URL
    };
  },
  onReady() {
    this.cameraContext = common_vendor.index.createCameraContext();
    setTimeout(() => {
      this.isPageLoaded = true;
    }, 100);
  },
  methods: {
    // 切换拍照/录制模式
    switchMode(newMode) {
      if (this.mediaSource) {
        this.retakeMedia();
      }
      this.mode = newMode;
    },
    // 处理相机错误
    handleCameraError(e) {
      console.error("相机错误:", e);
      common_vendor.index.showToast({
        title: "相机初始化失败，请检查权限设置",
        icon: "none"
      });
    },
    // 拍照方法
    takePhoto() {
      if (!this.cameraContext) {
        common_vendor.index.showToast({
          title: "相机未就绪",
          icon: "none"
        });
        return;
      }
      common_vendor.index.showLoading({
        title: "拍照中..."
      });
      this.cameraContext.takePhoto({
        quality: "high",
        success: (res) => {
          this.mediaSource = res.tempImagePath;
          common_vendor.index.hideLoading();
        },
        fail: (err) => {
          console.error("拍照失败:", err);
          common_vendor.index.hideLoading();
          common_vendor.index.showToast({
            title: "拍照失败，请重试",
            icon: "none"
          });
        }
      });
    },
    // 开始录制视频
    startRecording() {
      if (!this.cameraContext) {
        common_vendor.index.showToast({
          title: "相机未就绪",
          icon: "none"
        });
        return;
      }
      this.isRecording = true;
      this.recordingTime = 0;
      this.recordingTimer = setInterval(() => {
        this.recordingTime++;
        if (this.recordingTime >= 60) {
          this.stopRecording();
        }
      }, 1e3);
      this.cameraContext.startRecord({
        success: () => {
          console.log("开始录制视频");
        },
        fail: (err) => {
          console.error("开始录制失败:", err);
          this.isRecording = false;
          clearInterval(this.recordingTimer);
          common_vendor.index.showToast({
            title: "录制失败，请重试",
            icon: "none"
          });
        }
      });
    },
    // 停止录制视频
    stopRecording() {
      if (!this.isRecording)
        return;
      clearInterval(this.recordingTimer);
      this.isRecording = false;
      common_vendor.index.showLoading({
        title: "处理中..."
      });
      this.cameraContext.stopRecord({
        success: (res) => {
          this.mediaSource = res.tempVideoPath;
          console.log(res);
          common_vendor.index.hideLoading();
        },
        fail: (err) => {
          console.error("停止录制失败:", err);
          common_vendor.index.hideLoading();
          common_vendor.index.showToast({
            title: "视频保存失败，请重试",
            icon: "none"
          });
        }
      });
    },
    // 格式化时间显示 (秒 -> MM:SS)
    formatTime(seconds) {
      const minutes = Math.floor(seconds / 60);
      const remainingSeconds = seconds % 60;
      return `${minutes.toString().padStart(2, "0")}:${remainingSeconds.toString().padStart(2, "0")}`;
    },
    // 重新拍照或录制
    retakeMedia() {
      this.mediaSource = "";
      this.recordingTime = 0;
    },
    // 继续流程
    continueProcess() {
      if (!this.mediaSource) {
        common_vendor.index.showToast({
          title: "请先完成拍照",
          icon: "none"
        });
        return;
      }
      common_vendor.index.showLoading({
        title: "上传中..."
      });
      this.uploadMedia((url) => {
        this.photoUrl = url;
        this.submitPhotoUrl();
      });
    },
    // 上传媒体文件方法
    uploadMedia(callback) {
      const openid = JSON.parse(common_vendor.index.getStorageSync("userInfo")).openid || "";
      const tenant_id = 1;
      if (!openid || !tenant_id) {
        common_vendor.index.hideLoading();
        common_vendor.index.showToast({
          title: "用户信息不完整，请重新登录",
          icon: "none"
        });
        return;
      }
      common_vendor.index.uploadFile({
        url: "http://192.168.66.187:8083/api/system/upload/",
        filePath: this.mediaSource,
        name: "file",
        formData: {
          openid,
          tenant_id
        },
        success: (uploadRes) => {
          const res = JSON.parse(uploadRes.data);
          if (res.code === 2e3) {
            const photoUrl = res.data.url || res.data.photoUrl || "";
            if (callback && typeof callback === "function") {
              callback(photoUrl);
            }
          } else {
            common_vendor.index.hideLoading();
            common_vendor.index.showToast({
              title: res.msg || "照片上传失败",
              icon: "none"
            });
          }
        },
        fail: (err) => {
          common_vendor.index.hideLoading();
          console.error("上传失败:", err);
          common_vendor.index.showToast({
            title: "网络错误，请重试",
            icon: "none"
          });
        }
      });
    },
    // 提交照片URL到指定接口
    submitPhotoUrl() {
      const openid = JSON.parse(common_vendor.index.getStorageSync("userInfo")).openid || "";
      const tenant_id = 1;
      if (!this.photoUrl) {
        common_vendor.index.hideLoading();
        common_vendor.index.showToast({
          title: "照片信息不完整，请重试",
          icon: "none"
        });
        return;
      }
      api_user.fillUserInfo({
        application_id: JSON.parse(common_vendor.index.getStorageSync("selectedJob")).id,
        openid,
        tenant_id,
        avatar: this.photoUrl
      }).then((res) => {
        common_vendor.index.hideLoading();
        console.log(res);
        common_vendor.index.showToast({
          title: "照片上传成功",
          icon: "success"
        });
        setTimeout(() => {
          common_vendor.index.navigateTo({
            url: "/pages/identity-verify/identity-verify",
            fail: (err) => {
              console.error("页面跳转失败:", err);
              common_vendor.index.showToast({
                title: "页面跳转失败",
                icon: "none"
              });
            }
          });
        }, 1500);
      }).catch((err) => {
        common_vendor.index.hideLoading();
        console.error("提交失败:", err);
        common_vendor.index.showToast({
          title: "网络错误，请重试",
          icon: "none"
        });
      });
    },
    updateLocalUserInfo() {
      api_user.getUserInfo().then((res) => {
        if (res.code === 200 && res.data) {
          let userInfo = {};
          try {
            userInfo = JSON.parse(common_vendor.index.getStorageSync("userInfo") || "{}");
          } catch (e) {
            console.error("解析本地存储用户信息失败:", e);
            userInfo = {};
          }
          const updatedUserInfo = {
            ...userInfo,
            ...res.data
          };
          common_vendor.index.setStorageSync("userInfo", JSON.stringify(updatedUserInfo));
        }
      }).catch((err) => {
        console.error("更新本地用户信息失败:", err);
      });
    }
  }
};
function _sfc_render(_ctx, _cache, $props, $setup, $data, $options) {
  return common_vendor.e({
    a: $data.mode === "photo" ? 1 : "",
    b: common_vendor.o(($event) => $options.switchMode("photo")),
    c: $data.mode === "video" ? 1 : "",
    d: common_vendor.o(($event) => $options.switchMode("video")),
    e: !$data.mediaSource
  }, !$data.mediaSource ? {
    f: $data.mode,
    g: common_vendor.o((...args) => $options.handleCameraError && $options.handleCameraError(...args))
  } : $data.mode === "photo" ? {
    i: $data.mediaSource
  } : $data.mode === "video" ? {
    k: $data.mediaSource
  } : {}, {
    h: $data.mode === "photo",
    j: $data.mode === "video",
    l: $data.mode === "video" && $data.isRecording
  }, $data.mode === "video" && $data.isRecording ? {
    m: common_vendor.t($options.formatTime($data.recordingTime))
  } : {}, {
    n: !$data.mediaSource
  }, !$data.mediaSource ? common_vendor.e({
    o: $data.mode === "photo"
  }, $data.mode === "photo" ? {
    p: common_vendor.o((...args) => $options.takePhoto && $options.takePhoto(...args))
  } : $data.mode === "video" && !$data.isRecording ? {
    r: common_vendor.o((...args) => $options.startRecording && $options.startRecording(...args))
  } : $data.mode === "video" && $data.isRecording ? {
    t: common_vendor.o((...args) => $options.stopRecording && $options.stopRecording(...args))
  } : {}, {
    q: $data.mode === "video" && !$data.isRecording,
    s: $data.mode === "video" && $data.isRecording
  }) : {
    v: common_vendor.t($data.mode === "photo" ? "拍照" : "录制"),
    w: common_vendor.o((...args) => $options.retakeMedia && $options.retakeMedia(...args)),
    x: common_vendor.o((...args) => $options.continueProcess && $options.continueProcess(...args))
  }, {
    y: $data.isPageLoaded ? 1 : ""
  });
}
const MiniProgramPage = /* @__PURE__ */ common_vendor._export_sfc(_sfc_main, [["render", _sfc_render]]);
wx.createPage(MiniProgramPage);
