<template>
  <div class="col-sm-12" style="background-color: #FFFFFF">
    <div class="col-sm-12" style="padding:50px 100px;height: 25%">
      <div class="form-group col-sm-5" v-if="issearch">
        <v-select
          class="select select_list"
          :value.sync="useType"
          width="90%"
          v-model="useType"
          :options='typeOfUse'
          :valueSingle="true"></v-select>
      </div>
      <div class="form-group col-sm-2" style="text-align: center" v-if="issearch">
        <button type="button" class="btn btn-primary item_btn" @click="load">搜索</button>
      </div>
<!--      && source!='流程查看'-->
      <div class="form-group col-sm-2" style="text-align: center" v-if="isupload ">
        <button type="button" class="btn btn-primary item_btn" @click="showUpload = !showUpload">本地上传</button>
      </div>
      <div class="form-group col-sm-2" style="text-align: center" v-if="takeimg">
        <button type="button" class="btn btn-primary item_btn" @click="upload()">拍照</button>
      </div>
    </div>
    <hr style="width: 90%;margin: 0px auto;border: #999999 1px solid;"/>
    <div class="col-sm-12" style="overflow: scroll;height: 75%">
      <div :class="bootstraped ? bootstraped + ' showData' : 'col-sm-6 showData'" v-for="row in fileInfoData">
        <div class="col-sm-12 item">
          <div class="left col-sm-5">
            <a href="#" class="thumbnail" style="width: 100%;height: 100%">
              <img v-if="row.f_filetype === 'jpg'||row.f_filetype === 'png'||row.f_filetype === 'gif'||row.f_filetype === 'bmp'" :src="row.f_downloadURL" alt="..."/>
              <img v-if="row.f_filetype === 'pdf'" src="../../image/pdf.jpg" alt="" />
              <img v-if="row.f_filetype === 'xls'||row.f_filetype === 'xlsx'" src="../../image/excel.jpg" alt=""  />
              <img v-if="row.f_filetype === 'doc'||row.f_filetype === 'docx'" src="../../image/doc.jpg" alt=""  />
              <img v-if="row.f_filetype === 'dwg'" src="../../image/dwg.png" alt=""  />
              <img v-if="row.f_filetype === 'dxf'" src="../../image/dxf.png" alt=""  />
            </a>
          </div>
          <div class="right col-sm-7">
            <p :title="row.f_filename" class="clears"><strong>文件名：</strong>{{row.f_filename}}</p>
            <p :title="row.f_username" class="clears"><strong>操作员：</strong><span>{{row.f_username}}</span></p>
            <p :title="row.fusetype" class="clears"><strong>使用类型：</strong><span>{{row.fusetype}}</span></p>
            <p :title="row.f_uploaddate" class="clears"><strong>上传时间：</strong><span>{{row.f_uploaddate}}</span></p>
            <p :title="row.fremarks" class="clears"><strong>文件说明：</strong>{{row.fremarks}}</p>
            <p class="clears">
              <a v-if="row.f_filetype === 'jpg' || row.f_filetype==='png' || row.f_filetype==='gif' || row.f_filetype==='bmp'" :href="row.f_downloadURL" style="background:#6aa6e2" class="btn btn-primary" target="_blank" role="button">预览</a>
              <a v-if="row.f_filetype === 'dwg' || row.f_filetype==='dxf'" style="background:#6aa6e2" class="btn btn-primary" :href="row.f_downloadURL" role="button" download>下载</a>
              <a v-if="row.f_filetype !=='jpg' && row.f_filetype !=='png' && row.f_filetype !=='gif' && row.f_filetype !=='bmp' && row.f_filetype !=='dxf' && row.f_filetype !=='dwg'"
                 @click="downloadfile(row.f_downloadURL)" style="background:#6aa6e2" class="btn btn-primary" role="button">下载</a>
              <a v-if="isdelete && row.defname === defname" @click="delet($index, row)" href="#" class="btn btn-default" role="button" role="button">删除</a>
            </p>
          </div>
        </div>
      </div>
    </div>
  </div>
  <apply-high-meter
    v-if="showhighmeter"
    :show.sync="showhighmeter"
    :isusetype="isusetype"
    :isremark="isremark"
    @photo-finish="newPhoto"
    v-ref:ltgao
  ></apply-high-meter>
  <modal  :show.sync="showUpload" v-ref:modal backdrop="false">
    <header slot="modal-header" class="modal-header">
      <button type="button" class="close" @click="close"><span class="glyphicon glyphicon-remove"></span></button>
      <h4 class="modal-title" style="text-align: center">文件上传</h4>
    </header>
    <article slot="modal-body" class="modal-body form-horizontal">
      <div class="form-group" style="text-align: center">
        <file-upload class="my-file-uploader" :name="'myFile' + blodid"
                     action="rs/file/uploadFile" tagname="文件上传" :headers="headers" multiple v-ref:file></file-upload>
      </div>
      <div class="form-group" v-if="isusetype">
        <label class="col-sm-2 control-label">文件类型：</label>
        <div class="col-sm-10">
          <input-select
            class="select select_list"
            :value.sync="headers.fusetype"
            v-model="headers.fusetype"
            :options="$appdata.getParam('使用类型')"
            :valueSingle="true"></input-select>
        </div>
      </div>
      <div class="form-group" v-if="isremark" style="color: #df2424">
        <label class="col-sm-2 control-label">文件说明：</label>
        <div class="col-sm-10">
          <input class="form-control input_view" style=""
                 v-model="headers.fremarks"
                 :value="headers.fremarks"/>
        </div>
      </div>
    </article>
    <footer slot="modal-footer" class="modal-footer">
    </footer>
  </modal>
</template>

<script>
import {HttpResetClass} from 'vue-client'
import {isEmpty} from "../../Util";
export default {
  title: '附件',
  props: ['blodid', 'businessid', 'isremark', 'isusetype', 'takeimg', 'defname', 'isupload', 'isdelete', 'bootstraped', 'issearch','source'],
  data () {
    return {
      fileInfoData: [], // 数据库存储的文件记录对象数组
      headers: {'username': this.$login.f.name, 'blodid': '','businessid':'', 'fremarks': '','defname':'','fusetype':''}, // 调用rs/file/uploadFile 的参数
      showUpload: false, // 上传模态框控制
      showhighmeter: false, // 高拍仪组件控制
      useType: null
    }
  },
  ready () {
    this.headers.blodid = this.blodid
    this.headers.businessid = this.businessid
    this.headers.defname = this.defname
    if (this.blodid || this.businessid) {
      this.load()
    }
  },
  methods: {
    delet(index, row) {
      this.$resetdelete('rs/entity/t_files', {id: row.id}, {resolveMsg: '删除成功', rejectMsg: '删除失败'}).then((res) => {
        this.$dispatch("delResid",row.id)
        this.load()
      })
    },
    // 下载
    downloadfile(filepath){
      var link = document.createElement('a');
      link.href = filepath;
      // 设置下载属性，使得点击时触发下载
      link.download = filepath.split('/').pop(); // 获取文件名并设置为下载时的文件名
      // 隐藏链接（非必需，但避免不必要的视觉干扰）
      link.style.display = 'none';
      // 将链接添加到文档中
      document.body.appendChild(link);
      // 触发点击事件开始下载
      link.click();
      // 下载后移除链接（可选，为了保持DOM清洁）
      document.body.removeChild(link);
    },
    // 关闭文件上传对话框
    close () {
      this.showUpload = false
      this.showhighmeter = false
      // 将选的文件清空
      this.$refs.file.$el.querySelector('input').value = ''
      this.headers.fusetype = ''
      this.headers.fremarks = ''
      this.load()
    },
    // 查询
    async load() {
      let condition = ''
      if(this.businessid){
        condition = `f_businessid= '${this.headers.businessid}' `
      }else{
        condition = `f_blobid= '${this.headers.blodid}' `
      }
      if (this.defname === '冲正'){
        condition += `and defname= '${this.defname}' `
      }
      if (!isEmpty(this.useType)) {
        condition += `and fusetype like '${this.useType}'`
      }
      let http = new HttpResetClass()
      let data = {
        tablename: 't_files',
        condition: condition + ` order by f_uploaddate desc `
      }
      let getFile = await http.load('POST', 'rs/sql/applySingleTable', {data: data}, {
        warnMsg: null,
        resolveMsg: null
      })

      for (var i = 0; i < getFile.data.length; i++) {
        // 如果使用类型包含导入字样,则是execl文件导入的,不做显示
        if(getFile.data[i].fusetype&&(getFile.data[i].fusetype.includes('execl导入'))){
          getFile.data.splice(i,1)
          i--
          continue
        }
        let temp = getFile.data[i].f_downloadpath
        if (temp.includes('http:')){
          getFile.data[i].f_downloadURL = temp
        } else {
          let URL = temp.substring(temp.lastIndexOf(":\\") + 2)
          getFile.data[i].f_downloadURL = "http://" + location.host + "/" + URL
        }
      }
      this.fileInfoData = []
      this.fileInfoData = getFile.data
    },
    // 打开高拍仪
    upload () {
      if(this.showhighmeter){
        this.$refs.ltgao.closeVideo()
      }
      this.showhighmeter = !this.showhighmeter
    },
    // 高拍仪回调
    newPhoto(Imgbase64, fusetype, fremarks) {
      this.headers.fusetype = fusetype
      this.headers.fremarks = fremarks

      let form = new FormData()
      let xhr = new XMLHttpRequest()
      let formDataBoundary = "----WebkitFormBoundary" + "GaoPaiYi";
      form.append('Content-Type', 'multipart/form-data;boundary=' + formDataBoundary)
      form.append('file', this.convertBase64ToBlob(Imgbase64), "GaoPaiYi.jpg")
      xhr.open("POST", "rs/file/uploadFile")

      if (this.headers) {
        for (var header in this.headers) {
          xhr.setRequestHeader(header, encodeURIComponent(this.headers[header]))
        }
      }
      xhr.send(form)
      setTimeout(() => {
        this.close()
      }, 5000)
    },
    convertBase64ToBlob(base64String) {
      // 将base64解码
      var bytes = atob(base64String);
      //var bytes = base64;
      var bytesCode = new ArrayBuffer(bytes.length);
      // 转换为类型化数组
      var byteArray = new Uint8Array(bytesCode);

      // 将base64转换为ascii码
      for (var i = 0; i < bytes.length; i++) {
        byteArray[i] = bytes.charCodeAt(i);
      }
      // 生成Blob对象（文件对象）
      return new Blob([bytesCode], {type: 'image/jpeg'});
    },
  },
  computed: {
    typeOfUse () {
      return [{label: '全部', value: ''}, ...this.$appdata.getParam('使用类型')]
    }
  },
  events: {
    onFileUpload: function (file, res) {
      this.$dispatch("resid",res.id)
      this.headers.fremarks=''
      this.close()
    },
    onFileChange: function ( res) {
      const regex = /^[^#]+$/;
      for (let i=0;i<res.length;i++){
        if (!regex.test(res[i].name)){
          this.$showMessage(`第${i+1}个文件名不能包含#号`, 'error')
          this.close()
        }
      }
    }
  }
}
</script>

<style scoped>
.clears{
  overflow:hidden;
  text-overflow:ellipsis;
  white-space:nowrap;
}
.showData {
  padding: 15px 10px 0px 10px;
  box-sizing: border-box;
  height: 230px;
  font-family: "微软雅黑";
}
.showData .item{
  padding-bottom: 10px;
  border-bottom: solid 1px #c1c1c1;
}
.left {
  padding-right: 10px;
}
.left img{
  height: 100%;
  width: 100%;
}
.right{
  height: 100%;
  /*display: -webkit-flex;*/
  /*display: flex;*/
  /*flex-direction: column;*/
  /*justify-content: space-around;*/
}
.item_btn{
  width: 80%;
  background-color: #6aa6e2;
  border-radius: 4px;
  color: #FFFFFF;
  font-family: PingFang;
}
</style>
