<template>
  <div>
    <div v-if="temType==='upload'">
      <Row>
        <div style="float: right">
          <Upload v-show="show" :data="formData" :headers="{'Character-Encoding':'utf-8'}"
                  :multiple="multiple" :format="format" :max-size="maxSize" :action="action"
                  :default-file-list="defaultFileList"
                  :before-upload="beforeUpload" :on-progress="onProgress" :on-success="onSuccess" :on-error="onError"
                  :on-preview="onPreview" :on-remove="onRemove" :on-format-error="onFormatError"
                  :on-exceeded-size="onExceededSize" :show-upload-list="showUpload">
            <Button icon="ios-cloud-upload-outline">{{buttonName}}</Button>
            <!--<div style="padding: 20px 0">
              <Icon type="ios-cloud-upload" size="52" style="color: #3399ff"></Icon>
              <p>点击或拖动文件到此处上传</p>
            </div>-->
          </Upload>
        </div>
      </Row>
      <Row>
        <Table ref="table" :width="tableWidth" :height="tableHeight" :columns="tableColumns" :data="tableData" border>
          <template slot="oldName" slot-scope="{ row,index }">
            <a @click="fileDownLoad(row.id)">{{row.oldName}}</a>
          </template>
          <template slot="fileType" slot-scope="{ row,index }">
            <Select v-model="tableData[index].fileType" placeholder="请选择文件类型" transfer
                    @on-change="fileTypeChange(index)">
              <Option v-for="item in fileTypes" :value="item.value" :key="item.value">{{ item.name }}</Option>
            </Select>
          </template>
          <template slot="actions" slot-scope="{ row,index }">
            <Button size="small" type="primary" ghost @click="fileDelete(row,index)">删除</Button>
          </template>
        </Table>
      </Row>
    </div>
    <div v-if="temType==='showFile'">
      <Table ref="table2" :width="tableWidth" :height="tableHeight" :columns="tableColumns2" :data="tableData" border>
        <template slot="oldName" slot-scope="{ row,index }">
          <a @click="fileDownLoad(row.id)">{{row.oldName}}</a>
        </template>
      </Table>
    </div>
  </div>
</template>

<script>
  import uuid from 'uuid'
  import {downFileFdfs} from '../bc-libs/print-util'

  let _this;
  import {getToken, TOKEN_KEY} from '../bc-libs/token-util'
  import {deleteAttachment, editAttachment,getAttachmentList} from '../bc-upload/attachment-api'

  export default {
    name: 'bcUploadTable',
    props: {
      temType:{//组件类型 upload上传组件 showFile展示附件
        type:String,
        default:'upload'
      },
      show: {
        type: Boolean,
        default: true
      },
      multiple: {//是否支持多选文件
        type: Boolean,
        default: false
      },
      action: {//上传的地址，必填
        type: String,
        default: 'cas/api/v1/attach/binary?' + TOKEN_KEY + '=' + getToken()
      },
      format: {//支持的文件类型，与 accept 不同的是，format 是识别文件的后缀名，accept 为 input 标签原生的 accept 属性，会在选择文件时过滤，可以两者结合使用
        type: Array,
        default: function () {
          return []
        }
      },
      maxSize: {//文件大小限制，单位 kb
        type: Number,
        default: null,
      },
      fileArr: {//当前已上传文件集合
        type: Array,
        default: function () {
          return []
        }
      },
      fid: {//具体的某个业务标识ID，不传自动生成，传了就会使用传的值，主要提供修改功能使用
        type: String,
        default: ''
      },
      tableWidth: {//表格宽度
        type: Number,
        default: null
      },
      tableHeight: {//表格高度
        type: Number,
        default: null
      },
      buttonName: {//按钮名称
        type: String,
        default: "上传文件"
      },
      fileTypes: {//附件类型的字典
        type: Array,
        default: function () {
          return []
        }
      },
      searchParams:{//查询的条件，展示表格时使用，内容可以是attachmentDomian的字段，一般传fid或者batchId即可
        type: Object,
        default: function () {
          return {}
        }
      },
    },
    data() {
      return {
        //showUploadModal:false,
        defaultFileList: [],//默认已上传的文件列表  属性必含 name,url
        batchKey: null,//批次key
        tableData: [],
        showUpload: false,
        fileSize:null,//文件大小
        formData:{batchKey: this.batchKey, fid: this.fid,fileSize: this.fileSize},
        tableColumns: [
          {type: 'index', width: 80, align: 'center', title: "序号"},
          {title: '类型', key: 'fileType', width: 240, slot: 'fileType'},
          {title: '文件', key: 'oldName', slot: 'oldName'},
          {title: '操作', key: 'actions', slot: 'actions', width: 80},
        ],
        tableColumns2: [
          {type: 'index', width: 80, align: 'center', title: "序号"},
          {title: '类型', key: 'fileType'},
          {title: '文件', key: 'oldName', slot: 'oldName'},
        ],
      }
    }, methods: {
      beforeUpload(file) {//上传文件之前的钩子
        this.fileSize=file.size;
        this.$set(this.formData,'fileSize',file.size);
        if (!this.batchKey) {//如果没有生产批次key,那就初始化生成一下
          this.batchKey = uuid.v4();
        }
        if (!this.fid) {//如果没有生产批次key,那就初始化生成一下
          this.fid = uuid.v4();
        }
        this.$set(this.formData,'fid',this.fid)
        this.showUpload = true;
      },
      onProgress(event, file, fileList) {//文件上传时的钩子

      },
      onSuccess(response, file, fileList) {//文件上传成功时的钩子，对应的方法中的参数内容注意顺序
        this.fileArr.push(file.response.result[0]);
        this.tableData.push(file.response.result[0]);
        this.showUpload = false
        this.$emit('on-success',this.fid, this.batchKey, file.response.result[0], this.fileArr);
      },
      onError(response, file, fileList) {//文件上传失败时的钩子
        this.$Modal.error({
          title: '上传失败',
          content: response.error.message ? response.error.message : response.error,
        });
        this.$emit('on-error', fileList);
        return false;
      },
      onPreview(file) {//点击已上传的文件链接时的钩子

      },
      onRemove(file, fileList) {//文件列表移除文件时的钩子
        deleteAttachment(file.response.result[0].id).then(data => {
          this.$emit('on-remove', file.response.result[0]);
        }).catch(err => {
          this.$Message.error('操作失败！')
          console.log(err)
        })

      },
      onFormatError(file, fileList) {//文件格式验证失败时的钩子

      },
      onExceededSize(file, fileList) {//文件超出指定大小限制时的钩子

      },
      clearCaChe() {//文件超出指定大小限制时的钩子

      },
      fileDelete(row, index) {
        deleteAttachment(row.id).then(data => {
          this.tableData.splice(index, 1);
        }).catch(err => {
          this.$Message.error('删除操作失败！<br>错误信息：' + err)
          console.log(err)
        })
      },
      fileDownLoad(id) {
        downFileFdfs(id)
      },
      fileTypeChange(index) {
        editAttachment(this.tableData[index]).then(res => {
        }).catch(err => {
          this.$Message.error("文件类型设置失败！<br>失败原因：" + err)
        })
      },
      getFileList(params){
        getAttachmentList(params).then(res=>{
          if(res.data && res.data.result){
           /* this.$nextTick(function () {*/
              this.tableData=res.data.result
         /*   })*/
          }
        }).catch(err=>{
          this.$Message.error("获取附件信息出错！<br>错误信息："+err)
        })
      }
    }, mounted: function () {
      _this = this;
    }, watch: {
      show: {
        immediate: true,
        handler: function () {
        },
      },
      searchParams: {
        immediate: true,
        handler: function () {
          if(this.temType==='showFile' &&  !$.isEmptyObject(this.searchParams)){
                this.getFileList(this.searchParams);
          }
        }
      },
      fid:{
        immediate: true,
        handler: function () {
          if(this.fid){
            this.getFileList({fid:this.fid});
          }
        }
      }
    }
  }
</script>

<style scoped>

</style>
