<template>
  <div class="customer-css">
    <el-dialog :title="titleCon" :close-on-click-modal="false" :visible.sync="visible" @close="handleDialogClose" width="390px" style="height: 520px;" class="customer-dialog">
      <el-form :inline="true" label-position="top" label-width="80px">
        <el-button type="primary" @click="downloadFile()">下载文件模板</el-button>
        <el-form-item label="BU" v-if="pageData.flag !== 'poPartPrint'">
          <el-select v-model="bu" placeholder="请选择"  style="width: 295px">
            <el-option
              v-for = "i in userBuList"
              :key = "i.buNo"
              :label = "i.sitename"
              :value = "i.buNo">
            </el-option>
          </el-select>
        </el-form-item>
        <el-row>
          <el-col :span="24">
            <el-upload class="customer-upload" drag action="javascript:void(0);" ref="uploadFile" :limit="1" accept=".xlsx,.xls"
                       :before-upload="beforeUploadHandle" :on-change="onChange" :auto-upload="false" style="text-align: left;">
              <i class="el-icon-upload"></i>
              <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
            </el-upload>
          </el-col>
        </el-row>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="saveUploadFile()" :loading="uploadLoading">保存</el-button>
        <el-button type="primary" @click="closeDialog">关闭</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  uploadExcel, // 导入项目文件
  uploadTemplateExcel, // 导入模板文件
  uploadPartAttributeExcel, // 导入物料属性文件
  queryFileId, // 查询文件ID
  getSiteAndBuByUserName
} from "@/api/qc/qc.js"
import { uploadPoPartPrintExcel, queryFileIdWms } from '@/api/wms/wms.js'
import { downLoadObjectFile } from '@/api/eam/eam_object_list.js'
import axios from 'axios'
import Vue from 'vue'
export default {
  data() {
    return {
      titleCon: '文件导入',
      visible: false,
      fileList: [],
      bu: '',
      userBuList:[],
      uploadLoading: false, // 上传loading状态
      pageData: {
        flag: '',
        createBy: '',
        site: ''
      },
    }
  },
  created(){
    this.getSiteAndBu();
  },
  methods: {
    // 获取用户的bu
    getSiteAndBu () {
      let tempData = {
        username: this.$store.state.user.name,
      }
      getSiteAndBuByUserName(tempData).then(({data}) => {
        if (data.code === 0) {
          this.userBuList = data.rows
        }
      })
    },
    //初始化组件的参数
    init(currentRow) {
      // 获得类别
      this.pageData = JSON.parse(JSON.stringify(currentRow))
      //打开页面
      this.visible = true;
    },
    // 上传之前
    beforeUploadHandle(file) {
      let extName = file[0].name.substring(file[0].name.lastIndexOf('.')).toLowerCase()
      if (!(extName === '.xlsx' || extName === '.xls')) {
        this.$message.error('数据导入失败，请选择正确的xlsx模板文件')
        return false
      }
    },
    /*选择上传文件时*/
    onChange(file){
      this.fileList.push(file);
    },
    /*关闭modal*/
    closeDialog(){
      // 清空文件列表数据
      this.fileList = [];
      // 清空 el-upload 组件的文件列表
      if (this.$refs.uploadFile) {
        this.$refs.uploadFile.clearFiles();
      }
      // 重置 BU 选择
      this.bu = '';
      // 重置loading状态
      this.uploadLoading = false;
      // 刷新报工的页面
      this.$emit('refreshPageTables');
      // 关闭当前的页面
      this.visible = false;
    },
    
    /*对话框关闭事件 - 确保清理所有数据*/
    handleDialogClose(){
      // 清空文件列表数据
      this.fileList = [];
      // 清空 el-upload 组件的文件列表
      if (this.$refs.uploadFile) {
        this.$refs.uploadFile.clearFiles();
      }
      // 重置 BU 选择
      this.bu = '';
      // 重置loading状态
      this.uploadLoading = false;
      // 重置 pageData
      this.pageData = {
        flag: '',
        createBy: '',
        site: ''
      };
    },
    /*保修当前的数据*/
    saveUploadFile(){
      if (this.pageData.flag !== 'poPartPrint' && (this.bu === '' || this.bu == null)){
        this.$message.warning("请选择BU!");
        return false;
      }
      /*判断文件是否上传*/
      if(null == this.fileList || 0 == this.fileList.length){
        this.$message.error("请先上传文件!");
        return false;
      }
      
      // 开启loading
      this.uploadLoading = true;
      
      const formData = new FormData();
      formData.append("file", this.fileList[0].raw);
      formData.append("createBy", this.pageData.createBy);
      formData.append("site", this.pageData.site);
      if (this.pageData.flag === 'item'){
        uploadExcel(formData).then(({data}) => {
          if (data.code === 0) {
            this.$message.success(data.msg);
            // 清空文件上传记录
            this.$refs.uploadFile.clearFiles();
            // 关闭窗口并刷新页面
            this.closeDialog();
          }else {
            this.$message.warning(data.msg);
          }
        }).catch((error) => {
          this.$message.error('上传失败：' + (error.message || '网络错误'));
        }).finally(() => {
          // 关闭loading
          this.uploadLoading = false;
        })
      } else if (this.pageData.flag === 'template') {
        formData.set('site',this.bu)
        uploadTemplateExcel(formData).then(({data}) => {
          if (data.code === 0) {
            this.$message.success(data.msg);
            // 清空文件上传记录
            this.$refs.uploadFile.clearFiles();
            // 关闭窗口并刷新页面
            this.closeDialog();
          }else {
            this.$message.warning(data.msg);
          }
        }).catch((error) => {
          this.$message.error('上传失败：' + (error.message || '网络错误'));
        }).finally(() => {
          // 关闭loading
          this.uploadLoading = false;
        })
      } else if (this.pageData.flag === 'partAttribute') {
        uploadPartAttributeExcel(formData).then(({data}) => {
          if (data.code === 0) {
            this.$message.success(data.msg);
            // 清空文件上传记录
            this.$refs.uploadFile.clearFiles();
            // 关闭窗口并刷新页面
            this.closeDialog();
          } else {
            this.$message.warning(data.msg);
          }
        }).catch((error) => {
          this.$message.error('上传失败：' + (error.message || '网络错误'));
        }).finally(() => {
          // 关闭loading
          this.uploadLoading = false;
        })
      } else if (this.pageData.flag === 'poPartPrint') {
        // 采购标签导入
        formData.append("buNo", this.pageData.buNo);
        formData.append("orderNo", this.pageData.orderNo);
        formData.append("partNo", this.pageData.partNo);
        formData.append("partDesc", this.pageData.partDesc);
        formData.append("poOrderNo", this.pageData.poOrderNo);
        formData.append("poItemNo", this.pageData.poItemNo);
        formData.append("supplierId", this.pageData.supplierId);
        formData.append("supplierName", this.pageData.supplierName);
        formData.append("orderQty", this.pageData.orderQty);
        formData.append("inspectionNo", this.pageData.inspectionNo);
        uploadPoPartPrintExcel(formData).then(({data}) => {
          if (data.code === 0) {
            this.$message.success(data.msg);
            // 清空文件上传记录
            this.$refs.uploadFile.clearFiles();
            // 关闭窗口并刷新页面
            this.closeDialog();
          } else {
            this.$message.warning(data.msg);
          }
        }).catch((error) => {
          this.$message.error('上传失败：' + (error.message || '网络错误'));
        }).finally(() => {
          // 关闭loading
          this.uploadLoading = false;
        })
      }
      // 不要在这里重置 bu，因为已经在 closeDialog 中重置了
    },
    // 下载
    async downloadFile(){
      let file = {
        id: 0,
        fileName: ''
      }
      let tempData = {
        orderRef1: '',
        orderRef2: ''
      }
      if (this.pageData.flag === 'item') { // 检验项目
        tempData.orderRef1 = 'qc';
        tempData.orderRef2 = 'itemFormat';
        await queryFileId(tempData).then(({data}) => {
          if (data && data.code === 0) {
            file.id = data.data.id
            file.fileName = data.data.fileName
          } else {
            this.$alert(data.msg, '错误', {
              confirmButtonText: '确定'
            })
          }
        })
      } else if (this.pageData.flag === 'template') { // 检验模板
        tempData.orderRef1 = 'qc';
        tempData.orderRef2 = 'templateFormat';
        await queryFileId(tempData).then(({data}) => {
          if (data && data.code === 0) {
            file.id = data.data.id
            file.fileName = data.data.fileName
          } else {
            this.$alert(data.msg, '错误', {
              confirmButtonText: '确定'
            })
          }
        })
      } else if (this.pageData.flag === 'partAttribute') { // 物料属性设置
        tempData.orderRef1 = 'qc';
        tempData.orderRef2 = 'partAttributeFormat';
        await queryFileId(tempData).then(({data}) => {
          if (data && data.code === 0) {
            file.id = data.data.id
            file.fileName = data.data.fileName
          } else {
            this.$alert(data.msg, '错误', {
              confirmButtonText: '确定'
            })
          }
        })
      } else if (this.pageData.flag === 'poPartPrint') { // 采购标签导入
        tempData.orderRef1 = 'wms';
        tempData.orderRef2 = 'PoPartPrint';
        await queryFileIdWms(tempData).then(({data}) => {
          if (data && data.code === 0) {
            file.id = data.data.id
            file.fileName = data.data.fileName
          } else {
            this.$alert(data.msg, '错误', {
              confirmButtonText: '确定'
            })
          }
        })
      }
      await downLoadObjectFile(file).then(({data}) => {
        console.log(file)
        // 不限制文件下载类型
        const blob = new Blob([data], {type: "application/octet-stream"})
        // 下载文件名称
        const fileName = file.fileName
        // a标签下载
        const linkNode = document.createElement('a')
        // a标签的download属性规定下载文件的名称
        linkNode.download = fileName
        linkNode.style.display = 'none'
        // 生成一个Blob URL
        linkNode.href = URL.createObjectURL(blob)
        document.body.appendChild(linkNode)
        // 模拟在按钮上的一次鼠标单击
        linkNode.click()
        // 释放URL 对象
        URL.revokeObjectURL(linkNode.href)
        document.body.removeChild(linkNode)
      })
    },

  }
}
</script>
<style scoped lang="scss">
</style>
