<template>
  <div>
    <el-form :model="inputQuery" :rules="formRules" ref="dataForm">
      <el-card style="margin-top: -30px">
        <el-button-group style="display: flex">
          <el-button type="primary" @click.native="submitUpload()" style="margin: 0 60px 10px auto; height: 35px"
                     :loading="loading">提交
          </el-button>
        </el-button-group>
        <el-row>
          <el-col :span="3">
            <div class="ao-text">
              <span>规格型号：</span>
            </div>
          </el-col>
          <el-col :span="8">
            <el-form-item prop="name">
              <el-input v-model="inputQuery.spec" auto-complete="off" :disabled="true"></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="3">
            <div class="ao-text">
              <span>物资名称：</span>
            </div>
          </el-col>
          <el-col :span="8">
            <el-form-item prop="code">
              <el-input v-model="inputQuery.coName" auto-complete="off" :disabled="true"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="3">
            <div class="ao-text">
              <span>批次号：</span>
            </div>
          </el-col>
          <el-col :span="8">
            <el-form-item prop="name">
              <el-input v-model="inputQuery.batchNo" auto-complete="off" :disabled="true"></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="3">
            <div class="ao-text">
              <span>价格：</span>
            </div>
          </el-col>
          <el-col :span="8">
            <el-form-item prop="code">
              <el-input v-model="inputQuery.price" auto-complete="off" :disabled="true"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="3">
            <div class="ao-text">
              <span>生产企业：</span>
            </div>
          </el-col>
          <el-col :span="8">
            <el-form-item prop="name">
              <el-input v-model="inputQuery.manufacturer" auto-complete="off" :disabled="true"></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="3">
            <div class="ao-text">
              <span>注册/备案号：</span>
            </div>
          </el-col>
          <el-col :span="8">
            <el-form-item prop="code">
              <el-input v-model="inputQuery.certCode" auto-complete="off" :disabled="true"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="3">
            <div class="ao-text">
              <span>生产日期：</span>
            </div>
          </el-col>
          <el-col :span="8">
            <el-form-item prop="code">
              <el-input v-model="inputQuery.productDate" auto-complete="off" :disabled="true"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="3">
            <div class="ao-text">
              <span>计量单位：</span>
            </div>
          </el-col>
          <el-col :span="8">
            <el-form-item prop="code">
              <el-input v-model="inputQuery.measname" auto-complete="off" :disabled="true"></el-input>
            </el-form-item>
          </el-col>

        </el-row>
        <el-row>
          <el-col :span="3">
            <div class="ao-text">
              <span>送货数量：</span>
            </div>
          </el-col>
          <el-col :span="8">
            <el-form-item prop="name">
              <el-input v-model="inputQuery.count" auto-complete="off" :disabled="true"></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="3">
            <div class="ao-text">
              <span>扫码数量：</span>
            </div>
          </el-col>
          <el-col :span="8">
            <el-form-item prop="code">
              <el-input v-model="inputQuery.scanCount" auto-complete="off" :disabled="true"></el-input>
            </el-form-item>
          </el-col>
        </el-row>


        <el-row>
          <el-col :span="3">
            <div class="ao-text">
              <span>检验报告上传：</span>
            </div>
          </el-col>
          <el-col :span="8">
            <el-form-item>
              <el-upload
                :disabled="formData.auditStatus == 1"
                class="upload-demo"
                ref="upload"
                :action="this.uploadUrl"
                :on-preview="uploadHandlePreview"
                :on-remove="uploadHandleRemove"
                :limit="1"
                :headers="headers"
                :on-exceed="uploadHandleExceed"
                accept=".jpg,.png,.pdf"
                :on-change="uploadOnchange"
                :on-success="uploadHandleSuccess"
                :on-error="uploadHandleError"
                :on-before="uploadHandleBefore"
                :file-list="fileList"
                :data="{type:'image2'}"
                :auto-upload="true">
                <el-button slot="trigger" size="small" type="primary" :disabled="formData.auditStatus == 1">
                  {{ choiceFile }}
                </el-button>
                <div>只能上传 jpg,png,pdf 文件，且不超过 10 MB</div>
              </el-upload>

            </el-form-item>
          </el-col>
          <el-col :span="3">
            <div class="ao-text" v-if="this.inputQuery.filePath!=null">
              <span>检验报告预览：</span>
            </div>
          </el-col>
          <el-col :span="8">
            <el-button type="primary" size="mini" icon="search" v-if="this.inputQuery.filePath!=null"
                       style="text-align:right" @click="showImgViewer">
              检验报告预览
            </el-button>
            <el-image-viewer v-if="imgViewerVisible" style="z-index:9999" :on-close="closeImgViewer"
                             :url-list="imgList"/>
          </el-col>


        </el-row>


        <el-row>
          <el-col :span="3">
            <div class="ao-text">
              <span>冷链报告上传：</span>
            </div>
          </el-col>
          <el-col :span="8">
            <el-form-item>
              <el-upload
                :disabled="formData.auditStatus == 1"
                class="upload-demo"
                ref="upload"
                :action="this.uploadUrl"
                :on-preview="uploadHandlePreview"
                :on-remove="uploadHandleRemove1"
                :limit="1"
                :headers="headers"
                :on-exceed="uploadHandleExceed"
                accept=".jpg,.png,.pdf"
                :on-change="uploadOnchange1"
                :on-success="uploadHandleSuccess1"
                :on-error="uploadHandleError"
                :on-before="uploadHandleBefore"
                :file-list="fileList"
                :data="{type:'image2'}"
                :auto-upload="true">
                <el-button slot="trigger" size="small" type="primary" :disabled="formData.auditStatus == 1">
                  {{ choiceFile1 }}
                </el-button>
                <div>只能上传 jpg,png,pdf 文件，且不超过 10 MB</div>
              </el-upload>

            </el-form-item>
          </el-col>
          <el-col :span="3">
            <div class="ao-text" v-if="this.inputQuery.coldFilePath!=null">
              <span>冷链报告预览：</span>
            </div>
          </el-col>
          <el-col :span="8">
            <el-button type="primary" size="mini" icon="search" v-if="this.inputQuery.coldFilePath!=null"
                       style="text-align:right" @click="showImgViewerCold">
              冷链报告预览
            </el-button>
            <el-image-viewer v-if="imgViewerVisibleCold" style="z-index:9999" :on-close="closeImgViewerCold" :url-list="imgListCold"/>

          </el-col>


        </el-row>



      </el-card>
    </el-form>

  </div>
</template>

<script>
import draggable from "vuedraggable";
import store from "@/store";
import {updateBizById, updateById} from '@/api/inout/orderDetailBiz'
import {previewImage,previewFile} from '@/api/purchase/supCompany'
import ElImageViewer from "element-ui/packages/image/src/image-viewer";


export default {
  name: "DialogCheck",
  props: {
    closeDialog: {
      type: Function,
      required: true,
    },
    inputQuery: {
      type: Object,
      required: true,
    },
    checkFileName: {
      type: Object,
      required: true,
    },


  },
  data() {
    return {
      imgList: [],
      imgListCold:[],
      imgViewerVisible: false,
      imgViewerVisibleCold:false,
      BASE_URL: process.env.VUE_APP_BASE_API,
      code: "",
      formData: {
        ggxh: "",
        cpmctymc: "",
        machineNo: "",
        invoiceCode: "",
        invoiceEncode: "",
        price: "",
        remark: "",
        licenseUrl: ""
      },
      // formRules: {
      //   name: [
      //     {required: true, message: "请输入证书名称", trigger: "blur"}
      //   ],
      //   code: [
      //     {required: true, message: "请输入证书编号", trigger: "blur"}
      //   ],
      // },
      loading: false,
      uploadUrl: "",
      fileList: [],
      headers: {},
      choiceFile: "选取文件",
      choiceFile1: "选取文件",

    };
  },
  components: {
    draggable, ElImageViewer
  },
  methods: {
    submitUpload() {
      this.loading = true
      updateBizById(this.inputQuery).then((res) => {
        this.loading = false
        if (res.code == 20000) {
          this.$message({
            type: "success",
            message: "修改成功！",
          });
          this.closeDialog();
        }
      }).catch(() => {
        this.loading = false
      })


    },

    // onSubmit() {
    //   this.loading = true;
    //   this.formData.customerId = this.inputQuery.customerId;
    //   if (this.formData.customerId == null) {
    //     this.formData.customerId = store.getters.customerId
    //   }
    //   this.formData.type = this.addType;
    //   //证书类型：1:供应商；2.生产企业；3.产品品种
    //   if (this.addType == 2) {
    //     this.formData.manufacturerIdFk = this.inputQuery.manufacturerId;
    //   } else if (this.addType == 3) {
    //     this.formData.manufacturerIdFk = this.inputQuery.manufacturerIdFk;
    //     this.formData.productIdFk = this.inputQuery.productId;
    //   }
    //   if (this.formData.auditStatus != 1)
    //     this.formData.auditStatus = "6";
    //
    //   if (this.editTye == 1) {
    //     insertCompanyCert(this.formData).then(response => {
    //       this.loading = false;
    //       if (response.code === 20000) {
    //         this.$message.success("添加成功");
    //         this.closeDialog(true);
    //       } else {
    //         this.$message.error(response.message);
    //       }
    //     });
    //   } else {
    //     updateCompanyCert(this.formData).then(response => {
    //       this.loading = false;
    //       if (response.code === 20000) {
    //         this.$message.success("添加成功");
    //         this.closeDialog(true);
    //       } else {
    //         this.$message.error(response.message);
    //       }
    //     });
    //   }
    //
    //
    // },
    uploadHandleRemove(file, fileList) {
      this.inputQuery.filePath = null;
      this.inputQuery.checkFileName = null;
      console.log(file, fileList);
    },
    uploadHandleRemove1(file, fileList) {
      this.inputQuery.coldFilePath = null;
      this.inputQuery.checkColdFileName = null;
      console.log(file, fileList);
    },
    uploadHandlePreview(file) {
      console.log(file);
      console.log(this.fileList);
    },
    uploadHandleExceed(files, fileList) {
      this.$message.warning(`当前限制选择 1 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
    },
    uploadOnchange(file, fileList) {
      this.inputQuery.checkFileName = file.name;
      let fileName = file.name;
      let uid = file.uid
      let pos = fileName.lastIndexOf(".");
      let lastName = fileName.substring(pos, fileName.length);
      if (lastName.toLowerCase() !== ".jpg" && lastName.toLowerCase() !== ".png" && lastName.toLowerCase() !== ".doc" && lastName.toLowerCase() !== ".pdf") {
        this.$message.error("上传文件只能是 jpg,png,doc,pdf 格式");
        for (let i = 0; i < fileList.length; i++) {//从list删除
          if (fileList[i].uid === uid) {
            fileList.splice(i, 1)
          }
        }
        return;
      }
      // 限制上传文件的大小
      const isLt = file.size / 1024 / 1024 / 30 <= 1;
      if (!isLt) {
        this.$message.error("上传文件大小不能超过 30MB");
        for (let i = 0; i < fileList.length; i++) {
          if (fileList[i].uid === uid) {
            fileList.splice(i, 1)
          }
        }
      }
      return isLt;
    },
    uploadOnchange1(file, fileList) {
      this.inputQuery.checkColdFileName = file.name;
      let fileName = file.name;
      let uid = file.uid
      let pos = fileName.lastIndexOf(".");
      let lastName = fileName.substring(pos, fileName.length);
      if (lastName.toLowerCase() !== ".jpg" && lastName.toLowerCase() !== ".png" && lastName.toLowerCase() !== ".doc" && lastName.toLowerCase() !== ".pdf") {
        this.$message.error("上传文件只能是 jpg,png,doc,pdf 格式");
        for (let i = 0; i < fileList.length; i++) {//从list删除
          if (fileList[i].uid === uid) {
            fileList.splice(i, 1)
          }
        }
        return;
      }
      // 限制上传文件的大小
      const isLt = file.size / 1024 / 1024 / 30 <= 1;
      if (!isLt) {
        this.$message.error("上传文件大小不能超过 30MB");
        for (let i = 0; i < fileList.length; i++) {
          if (fileList[i].uid === uid) {
            fileList.splice(i, 1)
          }
        }
      }
      return isLt;
    },
    uploadHandleSuccess(response, file, fileList) {
      if (response.code === 20000) {
        this.inputQuery.filePath = response.data.name;
        // this.onSubmit();
      } else {
        this.$message.error("文件上传失败：" + response.message);
      }
    },
    uploadHandleSuccess1(response, file, fileList) {
      if (response.code === 20000) {
        this.inputQuery.coldFilePath = response.data.name;
        // this.onSubmit();
      } else {
        this.$message.error("文件上传失败：" + response.message);
      }
    },
    uploadHandleError() {

    },
    uploadHandleBefore(file) {
      console.log(file)
      let isJPG = file.type === 'image/jpeg';
      let isPNG = file.type === 'image/png';
      if (!isJPG && !isPNG) {
        this.$message.error('只能上传jpg或png格式');
      }
      return isJPG || isPNG;
    },
    showImgViewer(row) {
      if(this.inputQuery.filePath.substr(-1) == ','){
        this.inputQuery.filePath=this.inputQuery.filePath.slice(0, this.inputQuery.filePath.length-1);
      }
      this.certFileUrl =
        this.BASE_URL +
        "/udiwms/image/register/file/getImage?type=image2&name="+this.inputQuery.filePath;
      this.imgList = [];
      this.imgList.push(this.certFileUrl)
      let index = this.inputQuery.filePath.lastIndexOf('.');
      if(index===-1){
        this.$message.error("文件名异常!")
        return false
      }
      if(this.inputQuery.filePath.substr(index+1)==='pdf'){
        let pdf = "application/pdf"
        let binaryData = [];
        previewFile(this.certFileUrl).then(res=>{
          binaryData.push(res);
          let URL = window.URL.createObjectURL(new Blob(binaryData, {type: pdf}));
          window.open(URL);
        })
        // window.open(this.imgList[0])
        return false
      }
      this.imgViewerVisible = true;
      // previewImage({
      //   imageUrl: this.inputQuery.licenseUrl,
      //   certFileUrl: this.certFileUrl,
      // }).then((response) => {
      //   if (response.code === 20000) {
      //   }
      //   console.log(this.imgList);
      // });
      const m = (e) => {
        e.preventDefault();
      };
      document.body.style.overflow = "hidden";
      document.addEventListener("touchmove", m, false); // 禁止页面滑动
    },

    showImgViewerCold(row){
      if(this.inputQuery.coldFilePath.substr(-1) == ','){
        this.inputQuery.coldFilePath=this.inputQuery.coldFilePath.slice(0, this.inputQuery.coldFilePath.length-1);
      }
      this.certFileUrl =
        this.BASE_URL +
        "/udiwms/image/register/file/getImage?type=image2&name="+this.inputQuery.coldFilePath;
      this.imgList = [];
      this.imgList.push(this.certFileUrl)
      let index = this.inputQuery.coldFilePath.lastIndexOf('.');
      if(index===-1){
        this.$message.error("文件名异常!")
        return false
      }
      if(this.inputQuery.coldFilePath.substr(index+1)==='pdf'){
        let pdf = "application/pdf"
        let binaryData = [];
        previewFile(this.certFileUrl).then(res=>{
          binaryData.push(res);
          let URL = window.URL.createObjectURL(new Blob(binaryData, {type: pdf}));
          window.open(URL);
        })
        // window.open(this.imgList[0])
        return false
      }
      this.imgViewerVisible = true;
      // previewImage({
      //   imageUrl: this.inputQuery.licenseUrl,
      //   certFileUrl: this.certFileUrl,
      // }).then((response) => {
      //   if (response.code === 20000) {
      //   }
      //   console.log(this.imgList);
      // });
      const m = (e) => {
        e.preventDefault();
      };
      document.body.style.overflow = "hidden";
      document.addEventListener("touchmove", m, false); // 禁止页面滑动
    },


    closeImgViewer() {
      this.imgViewerVisible = false;
      const m = (e) => {
        e.preventDefault()
      };
      document.body.style.overflow = 'auto';
      document.removeEventListener("touchmove", m, true);
    },

    closeImgViewerCold(){
      this.imgViewerVisibleCold = false;
      const m = (e) => { e.preventDefault() };
      document.body.style.overflow = 'auto';
      document.removeEventListener("touchmove", m, true);
    },

  },
  filters: {},
  mounted() {
    document.body.ondrop = function (event) {
      event.preventDefault();
      event.stopPropagation();
    };
  },
  created() {
    this.uploadUrl = this.BASE_URL + "/udiwms/upload/register/file";
    this.headers = {
      ADMINID: store.getters.adminId,
      ADMINTOKEN: store.getters.token,
    };
    if (this.formData.formData == null) {
      this.formData = {}
    } else if (this.inputQuery.formData != null && this.inputQuery.formData.addType == 1) {
      this.formData = {}
    } else {
      this.formData = this.inputQuery.formData;
      console.log(this.inputQuery.formData);
    }
    if (this.inputQuery.filePath != null) {
      this.choiceFile = "更换检验报告";
    } else {
      this.choiceFile = "选取检验报告";
    }

    if (this.inputQuery.coldFilePath != null) {
      this.choiceFile1 = "更换冷链报告";
    } else {
      this.choiceFile1 = "选取冷链报告";
    }
  },
};
</script>
<style>

.ao-text {
  width: 100%;
  font-size: 13px;
  font-family: "Microsoft YaHei";
  float: right;
  text-align: right;
  margin-top: 10px;
}

</style>



