<template>
  <div class="customer-css">
    <!-- 只有附件上传功能 -->
    <el-form label-position="top" style="margin-top: -5px;">
      <el-row style="margin-top: 10px">
        <el-col :span="4">
          <el-button class="customer-bun-min" type="primary" @click="handleUpload">Upload</el-button>
        </el-col>
      </el-row>

      <!-- 文件列表表格 -->
      <el-table
        :height="tableHeight"
        :data="fileList"
        ref="fileTableRef"
        style="width: 100%; margin-top: 10px;">
        <el-table-column
          prop="fileName"
          header-align="center"
          align="left"
          min-width="200"
          label="File">
        </el-table-column>
        <el-table-column
          prop="createdBy"
          header-align="center"
          align="center"
          min-width="100"
          label="Upload By">
        </el-table-column>
        <el-table-column
          prop="createDate"
          header-align="center"
          align="center"
          min-width="100"
          label="Upload Time">
        </el-table-column>
        <el-table-column
          header-align="center"
          align="center"
          width="100"
          fixed="right"
          label="Actions">
          <template slot-scope="scope">
            <a type="text" size="small" v-if="scope.row.id" @click="handleDownload(scope.row)">View |</a>
            <a type="text" size="small" v-if="scope.row.id" @click="deleteFileReal(scope.row)"> delete</a>
            <a type="text" size="small" v-else @click="deleteFile(scope.$index)"> delete</a>
          </template>
        </el-table-column>
      </el-table>
    </el-form>

    <!-- File Upload Dialog -->
    <el-dialog title="UpLoad" :visible.sync="ossVisible" v-drag width="400px" append-to-body :close-on-click-modal="false">
      <el-form ref="form" class="rq" label-width="80px" label-position="top">
        <el-row :gutter="10">
          <slot></slot>
          <el-col :span="24">
            <el-form-item label=" " class="auto">
              <el-upload drag :file-list="fileList2"
                         action="#" ref="upload"
                         :on-remove="onRemoveFile"
                         :on-change="onChangeFile"
                         multiple
                         :auto-upload="false">
                <i class="el-icon-upload"></i>
                <div class="el-upload__text">Drag files here, or<em> click to upload</em></div>
              </el-upload>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="Remark" 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">Confirm</el-button> -->
        <el-button type="primary" :loading="uploadLoading" @click="submitData">Confirm</el-button>
        <el-button @click="ossVisible = false">Close</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { removeOssFile } from "../../../api/srm/srmSupplier";
import { downLoadObjectFile } from "../../../api/supplierStock/supplierStockRequest";
import {
  ossUploadNoSaveOSSForYJY,
  queryOssFilePlus} from "../../../api/oss/oss";

export default {
  data() {
    return {
      height: 200,
      tableHeight: 240,
      searchData: {
        orderRef1: '',
        orderRef2: '',
        orderRef3: '',
        orderReftype: 'part',
        height: 240
      },
      fileList: [],
      fileList2: [],
      ossVisible: false,
      ossForm: {
        remark: '',
      },
      uploadLoading: false,
      // staged files selected in upload dialog but not yet persisted
      stagedFiles: [],
      stagedFileRemark: '',
    }
  },

  mounted() {
    this.setTableHeight(this.searchData.height)
  },

  methods: {
    resolveTableHeight (height) {
      const value = Number(height)
      if (!Number.isFinite(value)) {
        return 240
      }
      return Math.max(Math.floor(value), 180)
    },
    setTableHeight (height) {
      this.tableHeight = this.resolveTableHeight(height)
      this.$nextTick(() => {
        if (this.$refs.fileTableRef && this.$refs.fileTableRef.doLayout) {
          this.$refs.fileTableRef.doLayout()
        }
      })
    },
     // 获取基础数据列表S
    getBaseList (val, type) {
      this.$nextTick(() => {
        let strVal = ''
        // if (val === 1013) {
        //   if(type==1) {
        //     strVal = this.dataForm.partType
        //   }
        // }
        this.$refs.baseList.init(val, strVal)
      })
    },
    /* 列表方法的回调 */
    getBaseData (val) {
      // if (this.tagNo === 1013) {
      //   if(this.tagNo1==1) {
      //     this.dataForm.partType = val.Base_id
      //     this.dataForm.partTypeDesc = val.Base_desc
      //   }
      // }
    },
    //初始化组件的参数
    init(inData) {
      //初始化参数
      this.searchData = JSON.parse(JSON.stringify(inData));
      this.setTableHeight(this.searchData.height)
      //刷新表格
      this.searchTable();

    },
    searchTable(){
      queryOssFilePlus(this.searchData).then(({data}) => {
        //区分请求成功和失败的状况
        if (data && data.code == 0) {
          this.fileList = data.rows
        } else {
          this.fileList = [];
        }
      });
    },

   
    // Upload dialog open
    handleUpload() {
      this.$nextTick(() => {
        if (this.$refs.upload) {
          this.$refs.upload.clearFiles();
        }
      })
      this.fileList2 = [];
      this.ossForm.remark = '';
      this.ossVisible = true;
    },

    onRemoveFile(file, fileList) {
      this.fileList2 = fileList;
    },

    onChangeFile(file, fileList) {
      this.fileList2 = fileList;
    },

    // Stage files on dialog confirm
    handleUploadFiles() {
      if (this.fileList2.length === 0) {
        this.$message.error('Please select file(s)');
        return;
      }
      this.stagedFileRemark = this.ossForm.remark || '';
      for (let i = 0; i < this.fileList2.length; i++) {
        const f = this.fileList2[i].raw;
        this.stagedFiles.push(f);
        this.fileList.push({
          fileName: f.name,
          createdBy: this.$store.state.user.name,
          createDate: (this.dayjs ? this.dayjs().format('YYYY-MM-DD HH:mm:ss') : new Date().toISOString()),
          _staged: true,
          raw: f
        });
      }
      this.fileList2 = [];
      this.ossForm.remark = '';
      this.ossVisible = false;
      this.$message.success('Files staged');
     
    },

    // Preview/download
    handleDownload(row) {
      // 预览文件
      let image = ['jpg', 'jpeg', 'png', 'gif', 'bmp'];
      let video = ['mp4', 'avi', 'mov', 'wmv', 'flv'];
      let office = ['doc', 'docx', 'ppt', 'pptx', 'xls', 'xlsx'];
      let txt = ['txt'];
      let type = '';
      let pdf = ['pdf'];
      
      if (image.includes(row.fileType.toLowerCase())) {
        type = 'image/' + row.fileType;
        downLoadObjectFile(row).then(({ data }) => {
          const blob = new Blob([data], { type: type });
          const fileURL = URL.createObjectURL(blob);
          window.open(fileURL, '_blank');
        });
      } else if (video.includes(row.fileType.toLowerCase())) {
        type = 'video/' + row.fileType;
        downLoadObjectFile(row).then(({ data }) => {
          const blob = new Blob([data], { type: type });
          const fileURL = URL.createObjectURL(blob);
          window.open(fileURL, '_blank');
        });
      } else if (txt.includes(row.fileType.toLowerCase())) {
        type = 'text/plain';
        downLoadObjectFile(row).then(({ data }) => {
          const blob = new Blob([data], { type: type });
          const fileURL = URL.createObjectURL(blob);
          window.open(fileURL, '_blank');
        });
      } else if (office.includes(row.fileType.toLowerCase())) {
        if (row.fileType.toLowerCase() === 'doc' || row.fileType.toLowerCase() === 'docx') {
          type = 'application/vnd.openxmlformats-officedocument.wordprocessingml.document';
        } else if (row.fileType.toLowerCase() === 'ppt' || row.fileType.toLowerCase() === 'pptx') {
          type = 'application/vnd.openxmlformats-officedocument.presentationml.presentation';
        } else {
          type = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
        }
        downLoadObjectFile(row).then(({ data }) => {
          const blob = new Blob([data], { type: 'application/octet-stream;charset=utf-8' });
          const fileName = row.fileName;
          const linkNode = document.createElement('a');
          linkNode.download = fileName;
          linkNode.style.display = 'none';
          linkNode.href = URL.createObjectURL(blob);
          document.body.appendChild(linkNode);
          linkNode.click();
          URL.revokeObjectURL(linkNode.href);
          document.body.removeChild(linkNode);
        });
      } else if (pdf.includes(row.fileType.toLowerCase())) {
        type = 'application/pdf';
        downLoadObjectFile(row).then(({ data }) => {
          const blob = new Blob([data], { type: type });
          const fileURL = URL.createObjectURL(blob);
          window.open(fileURL, '_blank');
        });
      } else {
        this.$message({
          message: 'Unsupported file type',
          type: 'warning'
        });
      }
    },

submitData() {
  // 确保 addModelData 存在
  if (!this.addModelData) {
    this.addModelData = {};
  }
  
  // 检查是否有文件
  if (this.fileList2.length === 0) {
    this.$message.error('请选择文件');
    return;
  }
  
  this.stagedFileRemark = this.ossForm.remark || '';
  this.uploadLoading = true;
  
  // 准备要上传的文件
  const stagedFiles = [];
  for (let i = 0; i < this.fileList2.length; i++) {
    stagedFiles.push(this.fileList2[i].raw);
  }
  
  // 立即关闭弹窗
  this.ossVisible = false;
  this.fileList2 = [];
  this.ossForm.remark = '';
  
  // 先上传文件
  const uploadStagedFiles = () => {
    const formData = new FormData();
    for (let i = 0; i < stagedFiles.length; i++) {
      formData.append('file', stagedFiles[i]);
    }
    formData.append('orderRef1', this.searchData.orderRef1);
    formData.append('orderRef2', this.searchData.orderRef2 || '');
    formData.append('orderRef3', this.searchData.orderRef3);
    formData.append('createdBy', this.$store.state.user.name);
    formData.append('fileRemark', this.stagedFileRemark || '');
    formData.append('orderReftype', 'part');
    
    return ossUploadNoSaveOSSForYJY(formData);
  };
  
  uploadStagedFiles()
    .then(({ data }) => {
      if (data && data.code === 0) {
        // 移除临时文件，添加上传成功的文件
        this.fileList = this.fileList.filter(f => !f._staged);
        for (let i = 0; i < data.rows.length; i++) {
          this.fileList.push(data.rows[i]);
        }
        
        // 确保 addModelData.fileList 存在后再操作
        if (!this.addModelData.fileList) {
          this.addModelData.fileList = [];
        }
        this.addModelData.fileList = this.addModelData.fileList.concat(data.rows);
        
        // 清除暂存数据
        this.stagedFiles = [];
        this.stagedFileRemark = '';
        this.uploadLoading = false;
        
       
      } else {
        this.uploadLoading = false;
        this.$message.warning(data.msg || '文件上传失败');
        return Promise.reject(new Error(data ? data.msg : '上传失败'));
      }
    })
   
    .catch(err => {
      this.uploadLoading = false;
      this.$message.error(err.message || err);
    });
},

    deleteFileReal(row) {
      if (!row || !row.id) return;
      this.$confirm('Are you sure you want to delete this file?', 'Delete Confirmation', {
        confirmButtonText: 'OK',
        cancelButtonText: 'Cancel',
        type: 'warning'
      }).then(() => {
        removeOssFile([row.id]).then(({ data }) => {
          if (data && data.code === 0) {
            const idx = this.fileList.findIndex(f => f.id === row.id);
            if (idx !== -1) this.fileList.splice(idx, 1);
            this.$message.success(data.msg || 'File deleted');
          } else {
            this.$message.warning(data.msg || 'Delete failed');
          }
        }).catch(err => {
          this.$message.error('Delete failed:' + (err.message || err));
        });
      }).catch(() => { });
    },

    deleteFile(index) {
      const f = this.fileList[index];
      if (f && f._staged && f.raw) {
        const idx = this.stagedFiles.findIndex(sf => sf.name === f.raw.name && sf.size === f.raw.size);
        if (idx !== -1) this.stagedFiles.splice(idx, 1);
      }
      this.fileList.splice(index, 1);
    },
  },
}
</script>

<!--当前页面的标签样式-->
<style scoped lang="scss">
.rq .auto /deep/ .el-form-item__content {
  height: auto;
  line-height: 1.5;
}
</style>