<template>
  <div class="oFileUpload controller" :class="[preview ? '' : 'o-unit']" v-if="widget.type == 'file'">
    <van-field :name="widget.model" :label="widget.name || '附件'" :required="fileCheck ? false : options.required || false" :rules="rule" v-if="!preview">
      <template #input>
        <!-- image/*, *.xlsx, *.xls, application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document, *.txt, *.pdf -->
        <van-uploader
          v-model="dataModel"
          :before-read="beforeRead"
          :before-delete="beforeDelete"
          :after-read="afterRead"
          :disabled="options.disabled || false"
          :max-count="options.length"
          accept="image/*, *.xlsx, *.xls,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel, application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document, *.txt, *.pdf"
          preview-size="0.6rem"
        >
          <!-- <template v-slot:preview-cover="props">
                        {{ props }}
                    </template> -->
          <!-- <template #preview-cover>
                        2323
                    </template> -->
        </van-uploader>
      </template>
    </van-field>
    <van-field v-else :name="widget.model" :label="widget.name || '附件'" class="preview">
      <template #input>
        <div class="preview_file" v-for="(item, index) in dataModel" :key="index">
          <div class="preview_item">
            <i class="van-icon van-icon-description van-uploader__file-icon"></i>
            <span style="white-space: nowrap; overflow: hidden; text-overflow: ellipsis; width: 2rem">{{ item.name || item.url }}</span>
          </div>
          <div class="preview_btn">
            <van-button @click="downLoadFile2(item.url)" type="info" size="mini">下载</van-button>
            <van-button :disabled="!checkFileSuffix(item.url)" v-if="checkFileSuffix(item.url)" @click="downLoadFile(item.url)" type="info" size="mini">预览</van-button>
          </div>
        </div>
        <!-- <div class="van-uploader__preview" v-for="(item, index) in dataModel" :key="index">
                    <div class="van-uploader__file" style="width: 0.6rem; height: 0.6rem;" >
                        <i class="van-icon van-icon-description van-uploader__file-icon"></i>
                        <div class="van-uploader__file-name van-ellipsis">
                            {{ item.name || item.url }}
                        </div>
                    </div>
                    <div style="text-align: center">
                        <van-button @click="downLoadFile2(item.url)" type="info" size="mini">下载</van-button>
                        <van-button :disabled="!checkFileSuffix(item.url)" @click="downLoadFile(item.url)" type="info" size="mini">预览</van-button>
                    </div>
                </div> -->
      </template>
    </van-field>

    <van-popup position="bottom" v-model="filePreview" style="height: 100%; border-radius: 0">
      <van-sticky>
        <m-header :backUrl="backUrl" :isFixed="false" name="预览" />
      </van-sticky>
      <div id="previewIframe" style="height: calc(100vh - 0.44rem)" v-if="filePreview && (fileType == 'xls' || fileType == 'pdf')"></div>
      <div style="height: calc(100vh - 0.44rem)" v-if="filePreview && fileType == 'doc'"></div>
      <!-- <div ref="pdf" style="height: calc(100vh - 0.44rem);" v-if="filePreview && fileType == 'pdf'">
            </div> -->
    </van-popup>
  </div>
</template>
<script>
import MHeader from "@/components/MHeader";
import setLoading from "@/common/loading";
import { uploadFile, oaUploadFile } from "@/views/message/api";
import { browser } from "@/common/common";
import { postMessage } from "@/helpers/native-message";
export default {
  name: "oFileUpload",
  components: { MHeader },
  props: ["widget", "preview", "value", "fileCheck"],
  data() {
    // xls, doc, pdf
    return {
      dataModel: this.widget.options?.defaultValue || null,
      filePreview: false,
      fileType: "xls",
      previewUrl: "",
      numPages: 1,
      backUrl: {
        status: true,
        callBack: () => {
          this.filePreview = false;
        },
      },
    };
  },
  mounted() {
    // 初始化参数
    if (this.value) {
      const widget = this.widget;
      const model = widget.originModel || widget.model;
      for (let v in this.value) {
        if (v == model) {
          this.dataModel = this.value[v];
        }
      }
    }
  },
  methods: {
    checkFileSuffix(url) {
      let urlArr = url.split(".");
      let suffix = urlArr[urlArr.length - 1];
      //  || suffix == 'doc' || suffix == 'docx'
      if (suffix == "xlsx" || suffix == "xls" || suffix == "pdf") {
        return true;
      } else {
        return false;
      }
    },
    getFileSuffix(url) {
      let urlArr = url.split(".");
      let suffix = urlArr[urlArr.length - 1];
      if (suffix == "xlsx" || suffix == "xls") {
        return "xls";
      } else if (suffix == "doc" || suffix == "docx") {
        return "doc";
      } else if (suffix == "pdf") {
        return "pdf";
      } else {
        return "";
      }
    },
    beforeRead(file) {
      const isLt2M = file.size / 1024 / 1024 < 5;
      if (!isLt2M) {
        this.$toast("上传文件大小不能超过 5MB");
        return false;
      }
      return true;
    },
    beforeDelete(file, detail) {
      this.dataModel.splice(detail.index, 1);
      if (!this.dataModel || (this.dataModel && this.dataModel.length <= 0)) {
        this.$emit("fileCheckRequired", false);
      }
      return true;
    },
    async afterRead(file, detail) {
      // 上传头像
      try {
        setLoading(true);
        file.status = "uploading";
        file.message = "上传中...";
        let formData = new FormData();
        formData.append("file", file.file);
        let res = null;
        const query = this.$route.query;
        if (query.processId) {
          formData.append("processId", query.processId);
          res = await oaUploadFile(formData);
        } else {
          res = await uploadFile(formData);
        }
        let result = res.data;
        if (result.code == 200) {
          file.status = "done";
          this.dataModel[detail.index] = {
            url: result.data.url,
            name: file.file.name,
            file: {
              name: file.file.name,
            },
          };
          // 目前只对 退费模板做处理（id: 19）
          if (query.processId == 19) {
            this.$emit("fileCheckRequired", true);
          }
        } else {
          file.status = "failed";
          file.message = "上传失败";
          this.$toast(result.msg);
          this.dataModel.splice(detail.index, 1);
          return false;
        }
        setLoading(false);
      } catch (err) {
        setLoading(false);
        file.status = "failed";
        file.message = "上传失败";
        this.dataModel.splice(detail.index, 1);
        return false;
      }
    },
    downLoadFile2(file) {
      this.$toast.loading({
        duration: 0, // 持续展示 toast
        forbidClick: true,
        message: "下载中...",
      });
      if (browser().isApp) {
        postMessage({ api: "downloadFile", content: { downloadUrl: file } }, () => {
          this.$toast.clear();
        });
      } else {
        this.$toast.clear();
        window.location.href = file;
      }
    },
    downLoadFile(file) {
      // this.previewUrl = 'https://view.officeapps.live.com/op/view.aspx?src=' + file
      this.filePreview = true;
      this.fileType = this.getFileSuffix(file);

      if (this.fileType == "xls" || this.fileType == "pdf") {
        this.$toast.loading({
          duration: 0, // 持续展示 toast
          forbidClick: true,
          message: "加载中...",
        });
        let _this = this;
        this.$nextTick(() => {
          let iframe = document.createElement("iframe");
          iframe.id = "preview_iframe";
          iframe.style.width = "100%";
          iframe.style.height = "100%";
          iframe.style.border = "none";
          if (this.fileType == "xls") {
            if (browser().android) {
              iframe.src = "https://api.idocv.com/view/url?url=" + encodeURIComponent(file + "?times=" + new Date().getTime());
            } else {
              iframe.src = "https://view.officeapps.live.com/op/view.aspx?src=" + file;
            }
          } else {
            iframe.src = window.location.origin + location.pathname + "/pdf/web/viewer.html?file=" + encodeURIComponent(file);
          }
          if (iframe.attachEvent) {
            iframe.attachEvent("onload", function () {
              _this.$toast.clear();
            });
          } else {
            iframe.onload = function () {
              _this.$toast.clear();

              // setTimeout(() => {
              //     let dom =  document.querySelector('#preview_iframe').contentWindow.document
              //     let scripts = dom.querySelectorAll('script[src]')
              //     if(scripts)
              // }, 2000);
            };
          }
          document.querySelector("#previewIframe").appendChild(iframe);
        });
      } else if (this.fileType == "doc") {
        //     // this.previewUrl = 'https://view.officeapps.live.com/op/view.aspx?src=' + file
      }
    },
  },
  computed: {
    options() {
      return this.widget.options || {};
    },
    rule() {
      let rules = this.widget.rules || [];
      if (rules && rules.length > 0) {
        rules.forEach((item) => {
          if (item.pattern) {
            item.pattern = eval(item.pattern);
          }
          // 判断是否上传文件
          if (this.fileCheck) {
            item.required = false;
          }
        });
      }
      return rules;
    },
  },
  watch: {
    // dataModel: {
    //     deep: true,
    //     handler(newValue) {
    //         if (newValue !== undefined && newValue !== null) {
    //         }
    //     }
    // },
  },
};
</script>

<style lang="less" scoped>
@import url("./controlCommon.less");
.oFileUpload {
  /deep/.van-uploader__wrapper--disabled {
    opacity: 0.9;
  }
  /deep/.van-field__control--custom {
    flex-wrap: wrap;
  }

  .preview_file {
    width: 100%;
    font-size: 14px;
    display: flex;
    justify-content: space-between;
    background: #f7f7f7;
    padding: 0.08rem;
    margin-bottom: 0.08rem;
    .preview_item {
      display: flex;
      padding-top: 0.03rem;
      flex-basis: 70%;
    }
    .preview_btn {
      text-align: right;
      flex-basis: 30%;
    }
  }
}
</style>
