"use strict";
const common_vendor = require("../../../common/vendor.js");
const common_js_net_shop = require("../../../common/js/net/shop.js");
const common_js_net_mainUrl = require("../../../common/js/net/mainUrl.js");
const common_js_conver = require("../../../common/js/conver.js");
const common_js_cache_storage = require("../../../common/js/cache/storage.js");
const DownProgress = () => "../../../components/download-progress.js";
const docFix = ["doc", "docx", "xls", "xlsx", "ppt", "pptx", "pdf"];
const imgFix = ["jpg", "jpeg", "png", "gif", "bmp", "webp", "svg", "ico", "tiff", "tif"];
const _sfc_main = {
  components: {
    DownProgress
  },
  data() {
    return {
      msgHint: "",
      msgType: "info",
      msgShow: false,
      files: [],
      maxCount: 4,
      replenishId: "",
      replenish: null,
      replenishFiles: [],
      downloading: false,
      downloadProgress: 0,
      showActionsheet: false,
      kind: "buy",
      restore: null,
      restoreFiles: []
    };
  },
  onLoad(options) {
    common_vendor.index.setNavigationBarTitle({
      title: "资料补充"
    });
    common_vendor.index.setNavigationBarColor({
      frontColor: "#000000",
      backgroundColor: "#FFFFFF",
      animation: {
        duration: 500,
        timingFunc: "easeIn"
      }
    });
    const {
      id,
      kind
    } = options;
    if (id) {
      this.replenishId = id;
      this.kind = kind;
      this.doGetReplenishDetail();
    } else {
      this.showMessage("数据有误,请稍后重试", "error");
      setTimeout(() => common_vendor.index.navigateBack(), 1500);
    }
  },
  methods: {
    isImg: common_js_conver.isImg,
    // 获取补充详情
    async doGetReplenishDetail() {
      try {
        common_vendor.index.showLoading({
          title: "加载中..."
        });
        const res = await common_js_net_shop.Shop.doGetReplenishDetail(this.replenishId);
        common_vendor.index.hideLoading();
        this.replenish = res;
        common_vendor.index.__f__("log", "at pages/shop/replenishStuffDetail/replenishStuffDetail.vue:169", "详情", res);
        if (res.correctionFiles) {
          await this.doGetFileInfo(1, res.correctionFiles);
        }
        await this.doGetReplenishRestoreDetail();
      } catch (err) {
        common_vendor.index.__f__("error", "at pages/shop/replenishStuffDetail/replenishStuffDetail.vue:179", err);
        common_vendor.index.hideLoading();
        this.showMessage(err.msg || "网络错误,请稍后重试", "error");
        setTimeout(() => common_vendor.index.navigateBack(), 1500);
      }
    },
    // 获取回复详情
    async doGetReplenishRestoreDetail() {
      try {
        common_vendor.index.showLoading({
          title: "加载中..."
        });
        const id = this.kind === "buy" ? this.replenish.buyId : this.replenish.sellId;
        const res = await common_js_net_shop.Shop.doGetReplenishDetail(id);
        common_vendor.index.hideLoading();
        common_vendor.index.__f__("log", "at pages/shop/replenishStuffDetail/replenishStuffDetail.vue:196", "回复详情", res);
        if (res) {
          this.restore = res;
          if (res.correctionFiles) {
            await this.doGetFileInfo(2, res.correctionFiles);
          }
        }
      } catch (err) {
        common_vendor.index.__f__("error", "at pages/shop/replenishStuffDetail/replenishStuffDetail.vue:204", err);
        common_vendor.index.hideLoading();
        this.showMessage(err.msg || "网络错误,请稍后重试", "error");
      }
    },
    // 获取文件信息
    async doGetFileInfo(type, ids) {
      try {
        common_vendor.index.showLoading({
          title: "加载中..."
        });
        const res = await common_js_net_shop.Shop.doGetFileInfos({
          ids
        });
        common_vendor.index.hideLoading();
        if (res) {
          const list = this.addPrefix(res);
          if (type === 1) {
            this.replenishFiles = list;
          } else {
            this.restoreFiles = list;
          }
        }
      } catch (err) {
        common_vendor.index.hideLoading();
        this.showMessage(err.msg || "获取附件失败,请稍后重试", "error");
      }
    },
    inputRemark(e) {
      this.remark = e.detail.value;
    },
    // 添加baseUrl
    addPrefix(list) {
      return list.map((item) => {
        item.netUrl = common_js_net_mainUrl.sImgPrefix + item.fileId;
        return item;
      });
    },
    doPreImg(url) {
      common_vendor.index.previewImage({
        urls: [url]
      });
    },
    // 下载文件
    doDownloadFile(item) {
      if (this.isImageFile(item.fileName)) {
        this.doPreImg(item.netUrl);
      } else if (this.isDocumentFile(item.fileName)) {
        this.goDownloadFile(item);
      } else {
        this.showMessage("该文件无法在小程序中打开,请前往电脑端查看", "info");
      }
    },
    async goDownloadFile(item) {
      try {
        this.downloadProgress = 0;
        this.downloading = true;
        const token = common_js_cache_storage.get("token");
        const header = token ? {
          "Auth": `Bearer ${token}`
        } : {};
        const url = item.netUrl + "." + item.fileType;
        const res = await this.doStartDownload(url, header);
        var path = "";
        if (res.tempFilePath.endsWith("." + item.fileType)) {
          path = res.tempFilePath;
        } else {
          path = res.tempFilePath + "." + item.fileType;
        }
        common_vendor.index.__f__("log", "at pages/shop/replenishStuffDetail/replenishStuffDetail.vue:281", "文件路径", path, "=========", res.tempFilePath);
        common_vendor.index.openDocument({
          filePath: path,
          showMenu: true,
          fileType: item.fileType,
          success(res2) {
            common_vendor.index.__f__("log", "at pages/shop/replenishStuffDetail/replenishStuffDetail.vue:287", "打开文件", res2);
          },
          fail(err) {
            common_vendor.index.__f__("log", "at pages/shop/replenishStuffDetail/replenishStuffDetail.vue:290", "打开文件失败", err);
          }
        });
      } catch (err) {
        common_vendor.index.__f__("error", "at pages/shop/replenishStuffDetail/replenishStuffDetail.vue:294", "下载失败", err);
        this.showMessage("很抱歉，文件下载出现问题。建议您稍作等待，之后再尝试下载。", "error");
      } finally {
        this.downloadProgress = 0;
        this.downloading = false;
      }
    },
    async doStartDownload(url, header) {
      const _self = this;
      return new Promise((resolve, reject) => {
        const downloadTask = common_vendor.index.downloadFile({
          url,
          header,
          success: resolve,
          fail: reject
        });
        downloadTask.onProgressUpdate((res) => {
          _self.downloadProgress = res.progress;
          common_vendor.index.__f__("log", "at pages/shop/replenishStuffDetail/replenishStuffDetail.vue:312", res);
        });
      });
    },
    backPageRefresh() {
      const pages = getCurrentPages();
      const beforePage = pages[pages.length - 2];
      if (beforePage) {
        beforePage.$vm.needRefresh = true;
      }
      common_vendor.index.navigateBack();
    },
    showMessage(msg, type = "info") {
      this.msgHint = msg;
      this.msgType = type;
      this.$refs.msg.open();
    },
    bindChooseWay(e) {
      this.showActionsheet = false;
      const value = e.detail.value;
      if (value === "img") {
        common_vendor.index.chooseMedia({
          count: 4,
          mediaType: ["image"],
          sourceType: ["album"],
          success: ({
            tempFiles
          }) => {
            if (tempFiles.length > 0) {
              this.doUploadFile(1, tempFiles);
            }
          },
          fail: (err) => {
            this.showMessage(err.errMsg || "选择文件失败,请稍后重试", "error");
          }
        });
      } else {
        common_vendor.index.chooseMessageFile({
          count: 1,
          type: "file",
          extension: docFix,
          success: ({
            tempFiles
          }) => {
            if (tempFiles.length > 0) {
              this.doUploadFile(2, tempFiles);
            }
          },
          fail: (err) => {
            this.showMessage(err.errMsg || "选择文件失败,请稍后重试", "error");
          }
        });
      }
    },
    bindChooseFile() {
      this.showActionsheet = true;
    },
    // 上传文件 type=1 图片  =2文件
    async doUploadFile(type, files) {
      try {
        common_vendor.index.showLoading({
          title: "上传中..."
        });
        const upUrl = type === 1 ? common_js_net_mainUrl.upShopImgUrl : common_js_net_mainUrl.upShopFileUrl;
        const upType = type === 1 ? "image" : "file";
        const token = common_js_cache_storage.get("token");
        const header = token ? {
          "Auth": `Bearer ${token}`
        } : {};
        const uploadPromises = files.map((file) => {
          const filePath = type === 1 ? file.tempFilePath : file.path;
          return new Promise((resolve, reject) => {
            common_vendor.index.uploadFile({
              url: upUrl,
              header,
              filePath,
              name: upType,
              success: (res) => {
                try {
                  const result = JSON.parse(res.data);
                  result.data.netUrl = common_js_net_mainUrl.sImgPrefix + result.data.fileId;
                  resolve(result.data);
                } catch (err) {
                  reject(new Error("解析上传结果失败"));
                }
              },
              fail: reject
            });
          });
        });
        const results = await Promise.all(uploadPromises);
        this.files = [...this.files, ...results];
        common_vendor.index.hideLoading();
      } catch (err) {
        common_vendor.index.__f__("error", "at pages/shop/replenishStuffDetail/replenishStuffDetail.vue:416", "上传失败", err);
        common_vendor.index.hideLoading();
        this.showMessage("上传文件失败，请稍后重试", "error");
      }
    },
    doDelFile(index) {
      if (index >= 0 && index < this.files.length) {
        this.files.splice(index, 1);
      }
    },
    // 校验参数
    checkParams() {
      const isRemarkValid = this.remark.trim() !== "";
      const isFileValid = this.files.length > 0;
      if (!isRemarkValid && !isFileValid) {
        this.showMessage("请输入补充内容或上传附件（至少完成一项）", "error");
        return false;
      }
      return true;
    },
    // 提交
    async doSubmit() {
      if (this.checkParams()) {
        try {
          common_vendor.index.showLoading({
            title: "提交中..."
          });
          const fileIds = this.files.map((item) => item.fileId).join(",");
          const data = {
            correctionFiles: fileIds,
            correctionParentId: this.replenish.correctionId,
            correctionRemark: this.remark,
            orderId: this.replenish.orderId
          };
          await common_js_net_shop.Shop.doSaveReplenish(data);
          this.showMessage("提交成功", "success");
          setTimeout(() => {
            this.backPageRefresh();
          }, 1500);
        } catch (err) {
          this.showMessage(err.msg || "网络错误,请稍后重试", "error");
        } finally {
          common_vendor.index.hideLoading();
        }
      }
    },
    // 工具函数：检查文件类型
    getFileExtension(filename) {
      if (!filename || typeof filename !== "string")
        return "";
      const lastDot = filename.lastIndexOf(".");
      return lastDot === -1 ? "" : filename.substring(lastDot + 1).toLowerCase();
    },
    isImageFile(filename) {
      return imgFix.includes(this.getFileExtension(filename));
    },
    isDocumentFile(filename) {
      return docFix.includes(this.getFileExtension(filename));
    }
  }
};
if (!Array) {
  const _component_DownProgress = common_vendor.resolveComponent("DownProgress");
  const _easycom_uni_popup_message2 = common_vendor.resolveComponent("uni-popup-message");
  const _easycom_uni_popup2 = common_vendor.resolveComponent("uni-popup");
  (_component_DownProgress + _easycom_uni_popup_message2 + _easycom_uni_popup2)();
}
const _easycom_uni_popup_message = () => "../../../uni_modules/uni-popup/components/uni-popup-message/uni-popup-message.js";
const _easycom_uni_popup = () => "../../../uni_modules/uni-popup/components/uni-popup/uni-popup.js";
if (!Math) {
  (_easycom_uni_popup_message + _easycom_uni_popup)();
}
function _sfc_render(_ctx, _cache, $props, $setup, $data, $options) {
  return common_vendor.e({
    a: $data.replenish != null
  }, $data.replenish != null ? common_vendor.e({
    b: common_vendor.t($data.replenish.correctionTitle),
    c: common_vendor.t($data.replenish.correctionRemark),
    d: $data.replenish.correctionFiles !== ""
  }, $data.replenish.correctionFiles !== "" ? {
    e: common_vendor.f($data.replenishFiles, (item, index, i0) => {
      return common_vendor.e({
        a: index,
        b: $options.isImg(item.fileType)
      }, $options.isImg(item.fileType) ? {
        c: item.netUrl,
        d: common_vendor.t(item.fileName)
      } : {
        e: common_vendor.t(item.fileName)
      }, {
        f: common_vendor.o(($event) => $options.doDownloadFile(item))
      });
    })
  } : {}) : {}, {
    f: $data.restore != null
  }, $data.restore != null ? common_vendor.e({
    g: common_vendor.t($data.restore.correctionRemark),
    h: $data.restore.correctionFiles !== ""
  }, $data.restore.correctionFiles !== "" ? {
    i: common_vendor.f($data.restoreFiles, (item, index, i0) => {
      return common_vendor.e({
        a: index,
        b: $options.isImg(item.fileType)
      }, $options.isImg(item.fileType) ? {
        c: item.netUrl,
        d: common_vendor.t(item.fileName)
      } : {
        e: common_vendor.t(item.fileName)
      }, {
        f: common_vendor.o(($event) => $options.doDownloadFile(item))
      });
    })
  } : {}) : {}, {
    j: common_vendor.p({
      isShow: $data.downloading,
      progress: $data.downloadProgress
    }),
    k: common_vendor.p({
      type: $data.msgType,
      duration: 2e3,
      message: $data.msgHint
    }),
    l: common_vendor.sr("msg", "82e4fb99-1"),
    m: common_vendor.p({
      type: "message"
    })
  });
}
const MiniProgramPage = /* @__PURE__ */ common_vendor._export_sfc(_sfc_main, [["render", _sfc_render], ["__scopeId", "data-v-82e4fb99"]]);
swan.createPage(MiniProgramPage);
//# sourceMappingURL=../../../../.sourcemap/mp-baidu/pages/shop/replenishStuffDetail/replenishStuffDetail.js.map
