"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_cache_storage = require("../../../common/js/cache/storage.js");
const DownProgress = () => "../../../components/download-progress.js";
const _sfc_main = {
  components: {
    DownProgress
  },
  setup() {
  },
  data() {
    return {
      msgHint: "",
      msgType: "info",
      msgShow: false,
      files: [],
      maxCount: 4,
      maxFixedCount: 4,
      replenishId: "",
      replenish: null,
      replenishFiles: [],
      downloading: false,
      downloadProgress: 0,
      remark: "",
      showActionsheet: false,
      groups: [
        {
          text: "图片",
          value: "img"
        },
        {
          text: "文件(Word、PDF)",
          value: "file"
        }
      ]
    };
  },
  onLoad(options) {
    common_vendor.index.setNavigationBarTitle({
      title: "材料补充"
    });
    common_vendor.index.setNavigationBarColor({
      frontColor: "#000000",
      backgroundColor: "#FFFFFF",
      animation: {
        duration: 500,
        timingFunc: "easeIn"
      }
    });
    var id = options.id;
    if (id && id !== "") {
      this.replenishId = id;
      this.doGetReplenishDetail();
    } else {
      this.showMessage("数据有误,请稍后重试", "error");
      setTimeout(function() {
        common_vendor.index.navigateBack();
      }, 1500);
    }
  },
  methods: {
    // 获取补充详情
    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;
        if (this.replenish.correctionFiles) {
          await this.doGetFileInfo(this.replenish.correctionFiles);
        }
      } catch (err) {
        common_vendor.index.hideLoading();
        this.showMessage(err.msg || "网络错误,请稍后重试", "error");
        setTimeout(() => {
          common_vendor.index.navigateBack();
        }, 1500);
      }
    },
    // 获取文件信息
    async doGetFileInfo(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);
          this.replenishFiles = 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(e) {
      const url = e.currentTarget.dataset.value;
      common_vendor.index.previewImage({
        urls: [url]
      });
    },
    // 下载文件
    doDownloadFile(e) {
      const item = e.currentTarget.dataset.value;
      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 downloadTask = common_vendor.index.downloadFile({
          url: item.netUrl + "." + item.fileType,
          header,
          success: (res) => {
            if (res.statusCode === 200) {
              common_vendor.index.__f__("log", "at pages/shop/addReplenishStuff/addReplenishStuff.vue:249", "下载文件成功", res);
              var path = "";
              if (res.tempFilePath.endsWith("." + item.fileType)) {
                path = res.tempFilePath;
              } else {
                path = res.tempFilePath + "." + item.fileType;
              }
              this.saveAndOpenFile(path, item.fileType);
            } else {
              throw new Error("下载失败");
            }
          }
        });
        downloadTask.onProgressUpdate((res) => {
          this.downloadProgress = Number(res.progress);
        });
        await new Promise((resolve, reject) => {
          downloadTask.onSuccess(resolve);
          downloadTask.onFail(reject);
        });
      } catch (err) {
        common_vendor.index.__f__("log", "at pages/shop/addReplenishStuff/addReplenishStuff.vue:272", "下载失败", err);
        this.showMessage("很抱歉，文件下载出现问题。建议您稍作等待，之后再尝试下载。", "error");
      } finally {
        this.downloadProgress = 0;
        this.downloading = false;
      }
    },
    saveAndOpenFile(path, fileType) {
      common_vendor.index.__f__("log", "at pages/shop/addReplenishStuff/addReplenishStuff.vue:281", "打开文件", path, fileType);
      const that = this;
      common_vendor.index.openDocument({
        filePath: path,
        fileType,
        showMenu: true,
        success(res) {
          that.showMessage("下载成功", "success");
        },
        fail(err) {
          that.showMessage("很抱歉，文件下载出现问题。建议您稍作等待，之后再尝试下载。", "error");
        }
      });
    },
    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.msgShow = true;
      if (this.$refs.msg) {
        this.$refs.msg.open({
          message: msg,
          type
        });
      }
    },
    bindChooseWay(e) {
      this.showActionsheet = false;
      const value = e.detail.value;
      if (value === "img") {
        common_vendor.index.chooseMedia({
          count: 4,
          mediaType: ["image"],
          sourceType: ["album"],
          success: (res) => {
            if (res.tempFiles.length > 0) {
              this.doUploadFile(1, res.tempFiles);
            }
          },
          fail: (err) => {
            this.showMessage(err.errMsg || "选择文件失败,请稍后重试", "error");
          }
        });
      } else {
        common_vendor.index.chooseMessageFile({
          count: 1,
          type: "file",
          extension: docFix,
          success: (res) => {
            if (res.tempFiles.length > 0) {
              this.doUploadFile(2, res.tempFiles);
            }
          },
          fail: (err) => {
            this.showMessage(err.errMsg || "选择文件失败,请稍后重试", "error");
          }
        });
      }
    },
    bindChooseFile() {
      const that = this;
      common_vendor.index.chooseImage({
        count: that.maxCount,
        success(res) {
          if (res.tempFilePaths && res.tempFilePaths.length > 0) {
            that.doUploadFile(res.tempFilePaths);
          }
        },
        fail(err) {
          that.showMessage("选择图片失败,请稍后重试", "error");
        }
      });
    },
    // 上传文件 type=1 图片  =2文件
    async doUploadFile(files) {
      try {
        common_vendor.index.showLoading({
          title: "上传中..."
        });
        const upUrl = common_js_net_mainUrl.upShopImgUrl;
        const upType = "image";
        const token = common_js_cache_storage.get("token");
        const header = token ? {
          "Auth": `Bearer ${token}`
        } : {};
        const uploadPromises = files.map((file, index) => {
          const filePath = file;
          return new Promise((resolve, reject) => {
            common_vendor.index.uploadFile({
              url: upUrl,
              header,
              filePath,
              name: upType,
              success: (res) => {
                try {
                  let data = res.data;
                  if (typeof data === "string") {
                    data = JSON.parse(data);
                  }
                  data.data.netUrl = common_js_net_mainUrl.sImgPrefix + data.data.fileId;
                  resolve(data.data);
                } catch (err) {
                  reject(new Error("解析上传结果失败"));
                }
              },
              fail: reject
            });
          });
        });
        const results = await Promise.all(uploadPromises);
        this.files = [...this.files, ...results];
        this.maxCount = this.maxFixedCount - this.files.length;
        common_vendor.index.hideLoading();
      } catch (err) {
        common_vendor.index.__f__("error", "at pages/shop/addReplenishStuff/addReplenishStuff.vue:416", "上传失败", err);
        common_vendor.index.hideLoading();
        this.showMessage("上传文件失败，请稍后重试", "error");
      }
    },
    doDelFile(e) {
      e.currentTarget.dataset.value;
      const index = e.currentTarget.dataset.index;
      if (index >= 0 && index < this.files.length) {
        this.files.splice(index, 1);
        this.maxCount = this.maxFixedCount - this.files.length;
      }
    },
    // 校验参数
    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();
        }
      }
    },
    // 文件类型判断工具方法
    isImageFile(fileName) {
      const imgExts = ["jpg", "jpeg", "png", "gif", "bmp"];
      const ext = fileName.split(".").pop().toLowerCase();
      return imgExts.includes(ext);
    },
    isDocumentFile(fileName) {
      const docExts = ["doc", "docx", "pdf", "xls", "xlsx", "ppt", "pptx", "txt"];
      const ext = fileName.split(".").pop().toLowerCase();
      return docExts.includes(ext);
    }
  }
};
if (!Array) {
  const _easycom_uni_popup_message2 = common_vendor.resolveComponent("uni-popup-message");
  const _easycom_uni_popup2 = common_vendor.resolveComponent("uni-popup");
  const _component_DownProgress = common_vendor.resolveComponent("DownProgress");
  (_easycom_uni_popup_message2 + _easycom_uni_popup2 + _component_DownProgress)();
}
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.isImageFile(item.fileType)
      }, $options.isImageFile(item.fileType) ? {
        c: item.netUrl,
        d: common_vendor.t(item.fileName)
      } : {
        e: common_vendor.t(item.fileName)
      }, {
        f: item
      });
    }),
    f: common_vendor.o((...args) => $options.doDownloadFile && $options.doDownloadFile(...args))
  } : {}) : {}, {
    g: common_vendor.o((...args) => $options.inputRemark && $options.inputRemark(...args)),
    h: $data.remark,
    i: common_vendor.f($data.files, (item, index, i0) => {
      return {
        a: index,
        b: item.netUrl,
        c: item.netUrl,
        d: common_vendor.t(item.fileName),
        e: item,
        f: index
      };
    }),
    j: common_vendor.o((...args) => $options.doPreImg && $options.doPreImg(...args)),
    k: common_vendor.o((...args) => $options.doDelFile && $options.doDelFile(...args)),
    l: $data.maxCount > 0
  }, $data.maxCount > 0 ? {
    m: common_vendor.o((...args) => $options.bindChooseFile && $options.bindChooseFile(...args))
  } : {}, {
    n: common_vendor.o((...args) => $options.doSubmit && $options.doSubmit(...args)),
    o: common_vendor.p({
      type: $data.msgType,
      message: $data.msgHint,
      duration: 2e3
    }),
    p: common_vendor.sr("msg", "0ecbe332-0"),
    q: common_vendor.p({
      type: "message"
    }),
    r: common_vendor.p({
      progress: $data.downloadProgress,
      isShow: $data.downloading
    })
  });
}
const MiniProgramPage = /* @__PURE__ */ common_vendor._export_sfc(_sfc_main, [["render", _sfc_render], ["__scopeId", "data-v-0ecbe332"]]);
swan.createPage(MiniProgramPage);
//# sourceMappingURL=../../../../.sourcemap/mp-baidu/pages/shop/addReplenishStuff/addReplenishStuff.js.map
