<script>
import {ossUpload, previewOssFileById, queryOss, removeOss} from "../../../api/oss/oss";

export default {
  name: "ossComponents",
  props:{
    orderRef1:{
      type:String,
      default:''
    },
    orderRef2:{
      type:String,
      default:''
    },
    orderRef3:{
      type:String,
      default:''
    },
    columns:{
      type:Array,
      required:true
    },
    height:{
      type:[String,Number],
      default:'35vh'
    },
    title:{
      type:String,
      default:'附件信息'
    },
    label:{
      type:String,
      default:'单号'
    },
    disabled:{
      type:Boolean,
      default:false
    },
    saveVisible:{
      type:Boolean,
      default:true
    },
    downloadVisible:{
      type:Boolean,
      default:true
    },
    previewVisible:{
      type:Boolean,
      default:true
    },
    removeVisible:{
      type:Boolean,
      default:true
    },
    visibleFlag: {
      type: Boolean,
      default: true
    }
  },
  data(){
    return{
      dataList:[],
      queryLoading:false,
      uploadLoading:false,
      selectionDataList:[],
      ossVisible:false,
      visibleFlag: true,
      ossForm:{
        orderRef2:'',
        orderRef3:'',
        remark:''
      },
      fileList:[],
    }
  },
  methods:{
    handleSelectionChange(val){
      this.selectionDataList = val
    },
    handleQuery(){
      if (!this.params.orderRef1 && !this.params.orderRef2){
        return;
      }
      let params = {
        ...this.params,
      }
      this.queryLoading = true;
      queryOss(params).then(({data})=>{
        if (data && data.code === 0){
          this.dataList = data.rows;
        }else {
          this.$message.warning(data.msg);
        }
        this.queryLoading = false;
      }).catch((error)=>{
        this.$message.error(error);
        this.queryLoading = false;
      })
    },
    handleUpload(){
      this.$nextTick(()=>{
        if (this.$refs.upload){
          this.$refs.upload.clearFiles();
        }
      })
      this.fileList = [];
      this.ossForm.remark = '';
      this.ossVisible = true
    },
    onRemoveFile(file, fileList){
      this.fileList = fileList
    },
    onChangeFile(file, fileList){
      this.fileList = fileList
    },
    handleUploadFiles(){
      if (this.fileList.length === 0){
        this.$message.error('请选择文件');
        return;
      }
      let formData = new FormData();
      for (let i = 0; i < this.fileList.length; i++) {
        formData.append('file', this.fileList[i].raw);
      }
      formData.append('orderRef1', this.orderRef1);
      formData.append('orderRef2', this.ossForm.orderRef2);
      formData.append('orderRef3', this.orderRef3);
      formData.append('fileRemark', this.ossForm.remark);
      this.uploadLoading = true;
      ossUpload(formData).then(({data})=>{
        if (data && data.code === 0){
          this.$message.success(data.msg);
          this.handleQuery();
          this.ossVisible = false;
        }else {
          this.$message.warning(data.msg);
        }
        this.uploadLoading = false;
      }).catch((error)=>{
        this.$message.error(error);
        this.uploadLoading = false;
      })
    },
    handleRemove(row){
      this.$confirm('确认删除吗？', '提示').then(() => {
        let ids = [row.id]
        removeOss(ids).then(({data})=>{
          if (data && data.code === 0){
            this.$message.success(data.msg);
            this.handleQuery();
          }else {
            this.$message.warning(data.msg);
          }
        }).catch((error)=>{
          this.$message.error(error);
        })
      }).catch(()=>{

      })
    },
    previewFile(row){
      // 预览文件
      let type = '';
      let image = ['jpg', 'jpeg', 'png', 'gif', 'bmp'];
      if (image.includes(row.fileType.toLowerCase())){
        type = 'image/' + row.fileType;
      }
      let video = ['mp4', 'avi', 'mov', 'wmv', 'flv'];
      if (video.includes(row.fileType.toLowerCase())){
        type = 'video/' + row.fileType;
      }

      let txt = ['txt'];
      if (txt.includes(row.fileType.toLowerCase())){
        type = 'text/plain;charset=utf-8';
      }
      let office = ['doc', 'ppt', 'pptx'];
      if (office.includes(row.fileType.toLowerCase())){
        this.$message.warning(`该文件格式暂不支持预览`)
        return
      }

      let excel = ['xlsx','xls'];
      if (excel.includes(row.fileType.toLowerCase())){
        type = row.fileType.toLowerCase();
      }
      let word = ['docx'];
      if (word.includes(row.fileType.toLowerCase())){
        type = 'docx'
      }
      let pdf = ['pdf'];
      if (pdf.includes(row.fileType.toLowerCase())){
        type = 'application/pdf;charset-UTF-8';
      }

      if (type === ''){
        this.$message.warning(`该文件格式暂不支持预览`)
        return;
      }
      let params = {
        id:row.id,
      }
      previewOssFileById(params).then(({data}) => {
        const blob = new Blob([data], { type: type });
        // 创建URL来生成预览
        const fileURL = URL.createObjectURL(blob);
        if (type === 'xls' || type === 'docx' || type === 'xlsx'){
          const { href } = this.$router.resolve({
            name: 'pre',
            query:{
              src: fileURL,
              type:type
            }
          })
          window.open(href, '_blank')
        }else {
          // 在新标签页中打开文件预览
          const newTab = window.open(fileURL, '_blank');
        }
      });
    },
    handleDownload(){
      if (this.selectionDataList.length === 0){
        this.$message.warning('请选择要下载的附件');
        return;
      }
      for (let i = 0; i < this.selectionDataList.length; i++) {
        let params = {
          id:this.selectionDataList[i].id,
        }
        previewOssFileById(params).then((response) => {
          const blob = new Blob([response.data], { type: response.headers['content-type'] });
          const link = document.createElement('a');
          link.href = URL.createObjectURL(blob);
          link.setAttribute('download', this.selectionDataList[i].fileName);
          link.target = '_blank';  // 打开新窗口预览
          link.click();
          URL.revokeObjectURL(link.href);
          this.$refs.table.clearSelection();
        });
      }
    }
  },
  computed:{
    params:{
      get(){
        return{
          orderRef1:this.orderRef1,
          orderRef2:this.orderRef2,
          orderRef3:this.orderRef3,
        }
      }
    },
    effectiveVisibleFlag() {
      return this.visibleFlag !== undefined && this.visibleFlag !== null ? this.visibleFlag : true;
    }
  },
  watch:{
    params:{
      handler(){
        this.ossForm.orderRef2 = this.orderRef2;
        this.ossForm.orderRef3 = this.orderRef3;
        this.dataList = [];
        this.handleQuery();
      }
    },
    orderRef2(newVal) {
      this.ossForm.orderRef2 = newVal;
    },
    'ossForm.orderRef2'(newVal) {
      this.$emit('update:orderRef2', newVal);
    }
  },
  mounted() {
    this.ossForm.orderRef2 = this.orderRef2;
    console.log(this)
  }
}
</script>

<template>
<div>
  <template v-if="saveVisible&&effectiveVisibleFlag">
    <el-button type="primary" v-if="this.orderRef1 && this.orderRef2 && !disabled" @click="handleUpload">上传附件</el-button>
  </template>
  <template v-if="downloadVisible">
    <el-button type="primary" @click="handleDownload">下载</el-button>
  </template>
  <el-table
    :height="height"
    :data="dataList"
    ref="table"
    v-loading="queryLoading"
    border
    @selection-change="handleSelectionChange"
    style="width: 100%;margin-top: 5px">
    <el-table-column type="selection" label="序号" align="center"/>
    <el-table-column
      v-for="(item,index) in columns" :key="index"
      :sortable="item.columnSortable"
      :prop="item.columnProp"
      :header-align="item.headerAlign"
      :show-overflow-tooltip="item.showOverflowTooltip"
      :align="item.align"
      :fixed="item.fixed===''?false:item.fixed"
      :min-width="item.columnWidth"
      :label="item.columnLabel">
      <template slot-scope="scope">
        <span v-if="!item.columnHidden">{{scope.row[item.columnProp]}}</span>
        <span v-if="item.columnImage"><img :src="scope.row[item.columnProp]" style="width: 100px; height: 80px"/></span>
      </template>
    </el-table-column>
    <el-table-column
      fixed="right"
      header-align="center"
      align="center"
      width="120"
      label="操作" v-if="removeVisible || previewVisible">
      <template slot-scope="{row,$index}">
        <template v-if="removeVisible&&effectiveVisibleFlag">
          <el-link style="cursor:pointer;" v-if="!disabled" @click="handleRemove(row)">删除</el-link>
        </template>
        <template v-if="previewVisible">
          <el-link style="cursor:pointer;" @click="previewFile(row)">预览</el-link>
        </template>
      </template>
    </el-table-column>
  </el-table>

  <el-dialog :title="title" :visible.sync="ossVisible" v-drag width="400px" append-to-body :close-on-click-modal="false">
    <el-form ref="form" :model="ossForm" label-width="80px" label-position="top">
      <el-row :gutter="10">
        <el-col :span="12">
          <el-form-item :label="label">
            <el-input v-model="ossForm.orderRef2" readonly></el-input>
          </el-form-item>
        </el-col>
        <slot></slot>
        <el-col :span="24">
          <el-form-item label=" " class="auto">
            <el-upload drag :file-list="fileList"
                       action="#" ref="upload"
                       :on-remove="onRemoveFile"
                       :on-change="onChangeFile"
                       multiple
                       :auto-upload="false">
              <i class="el-icon-upload"></i>
              <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
            </el-upload>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="备注" class="auto">
            <el-input type="textarea" v-model="ossForm.remark" resize="none" :autosize="{minRows: 3, maxRows: 3}"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button type="primary" :loading="uploadLoading" @click="handleUploadFiles">确定</el-button>
      <el-button @click="ossVisible = false">关闭</el-button>
    </span>
  </el-dialog>
</div>
</template>

<style scoped>
.auto /deep/ .el-form-item__content{
  height: auto;
  line-height: 1;
}
</style>
