<template>
  <div class="customer-css">
    <el-dialog :title="titleCon" :close-on-click-modal="false" :visible.sync="visible" width="400px" style="height: 520px;" class="customer-dialog" @close="deleteFile">
      <el-form :inline="true" label-position="top" label-width="80px">
        <el-row>
          <el-form-item label="BU">
            <el-select v-model="pageData.buNo" placeholder="请选择" disabled  style="width: 120px">
              <el-option
                v-for = "i in buList"
                :key = "i.buNo"
                :label = "i.buDesc"
                :value = "i.buNo">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item :label="'CMC Invoice:'">
            <el-input v-model="pageData.cmcInvoice" disabled style="width: 120px"></el-input>
          </el-form-item>
          <el-form-item label=" ">
<!--            <download-excel
              :fields="fields()"
              :data="exportData"
              type="xls"
              :name="exportName"
              :header="exportHeader"
              :footer="exportFooter"
              :fetch="createExportData"
              :before-generate="startDownload"
              :before-finish="finishDownload"
              worksheet="导出信息"
              class="el-button el-button&#45;&#45;primary el-button&#45;&#45;medium">
              {{ '导出模版' }}
            </download-excel>-->
           <el-button type="primary" @click="exportExcel()">下载文件模板</el-button>
          </el-form-item>
        </el-row>
        <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">保存</el-button>
        <el-button type="primary" @click="closeDialog">关闭</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
  import {queryFileId} from "@/api/qc/qc.js"
  import {saveCoDelPalletDataByExcel,searchEcssCoDelNotifyDetail} from '@/api/ecss/ecss.js'
  import {downLoadObjectFile} from '@/api/eam/eam_object_list.js'
  import {getBuList}from  '@/api/factory/site.js'
  import excel from "@/utils/excel-util.js";
  import excelOpts from '@/utils/export-options.js'
  export default {
    name: 'bomComponentUpload',
    data() {
      return {
        buList: [],
        titleCon: '文件导入',
        visible: false,
        fileList: [],
        pageData: {
          site: '',
          buNo: '',
          delNo:'',
          cmcInvoice:'',
          createBy: this.$store.state.user.name,
        },
        // 导出 start
        exportData: [],
        exportName: '装箱数据导入模版',
        exportHeader: [""],
        exportFooter: [],
        // 导出 end
        columnList1: [
          {
            columnProp: "seqNo",
            columnLabel: "序号",
          },
          {
            columnProp: "cmcInvoice",
            columnLabel: "发票号",
          },
          {
            columnProp: "seqNo",
            columnLabel: "托盘号/箱号",
          },
          {
            columnProp: "customerPO",
            columnLabel: "PO",
          },
          {
            columnProp: "pn",
            columnLabel: "PN",
          },
          {
            columnProp: "qty",
            columnLabel: "数量",
          },
          {
            columnProp: "boxQty",
            columnLabel: "箱数",
          },
          {
            columnProp: "Rolls",
            columnLabel: "Rolls",
          },
          {
            columnProp: "pallet_qty",
            columnLabel: "托数",
          },
          {
            columnProp: "length",
            columnLabel: "长(M)",
          },
          {
            columnProp: "width",
            columnLabel: "宽(M)",
          },
          {
            columnProp: "height",
            columnLabel: "高(M)",
          },
          {
            columnProp: "volume",
            columnLabel: "体积",
          },
          {
            columnProp: "grossWeight",
            columnLabel: "毛重",
          },
          {
            columnProp: "netWeight",
            columnLabel: "净重",
          }
        ],
      }
    },
    methods: {
      async exportExcel() {
        let searchData={
          site: this.pageData.site,
          buNo: this.pageData.buNo,
          delNo: this.pageData.delNo,
          cmcInvoice: this.pageData.cmcInvoice,
          shippingMode: this.pageData.shippingMode,
          destination : this.pageData.destination,
          createBy: this.$store.state.user.name,
        }
        excel.exportTable({
          url: "/select/ecssMapper/searchEcssCoDelNotifyDetail/list",
          columnMapping:  excelOpts.PalletSku.columnMapping,//可以直接用table，不需要的列就剔除
          mergeSetting: [],//需要合并的列
          params: searchData,
          fileName: this.exportName+".xlsx",
          rowFetcher: res => res.data,
          columnFormatter: [],
          dropColumns: [],//需要剔除的列，例如dropColumns: ["netWeight"]，即剔除净重列
        });
      },
      // 初始化组件的参数
      init (inData) {
        this.fileList = []
        let tempData = {
          username: this.$store.state.user.name,
        }
        getBuList(tempData).then(({data}) => {
          if (data.code === 0) {
            this.buList = data.row2
          }
        })
        console.log(inData)
        this.pageData={
          site: inData.site,
          buNo: inData.buNo,
          delNo: inData.delNo,
          cmcInvoice: inData.cmcInvoice,
          shippingMode: inData.shippingMode,
          destination : inData.destination,
          walMartOrderFlag: inData.walMartOrderFlag,
          createBy: this.$store.state.user.name,
        }
        // 打开页面
        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.deleteFile()
        // 关闭当前的页面
        this.visible = false
      },
      deleteFile(){
        this.fileList = []
        // 清空文件上传记录
        this.$refs.uploadFile.clearFiles()
        // 刷新报工的页面
        this.$emit('refreshTable')

      },

      // 保修当前的数据
      saveUploadFile () {
        // 判断文件是否上传
        if (null == this.fileList || 0 === this.fileList.length) {
          this.$message.error("请先上传文件!")
          return false
        }
        const formData = new FormData()
        formData.append("buNo",this.pageData.buNo)
        formData.append("site",this.pageData.site)
        formData.append("delNo",this.pageData.delNo)
        formData.append("cmcInvoice",this.pageData.cmcInvoice)
        formData.append("walMartOrderFlag",this.pageData.walMartOrderFlag)
        formData.append("username",this.$store.state.user.name)
        formData.append("file", this.fileList[0].raw)
        // formData.append("createBy", this.pageData.createBy)
        saveCoDelPalletDataByExcel(formData).then(({data}) => {
          if (data.code === 0) {
            this.$message.success(data.msg)
            // 关闭窗口并刷新页面
            this.closeDialog()
          } else {
            this.$alert(data.msg, '错误', {
              confirmButtonText: '确定'
            })
          }
        })
      },

      // 下载
      async downloadFile () {
        let file = {
          id: 0,
          fileName: ''
        }
        let tempData = {
          orderRef1: 'ecss',
          orderRef2: 'upLoadPallet'
        }
        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: '确定'
            })
          }
        })

        await downLoadObjectFile(file).then(({data}) => {
          // 不限制文件下载类型
          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)
        })
      },

      //导出excel
      async createExportData() {
        let searchData={
          site: this.pageData.site,
          buNo: this.pageData.buNo,
          delNo: this.pageData.delNo,
          cmcInvoice: this.pageData.cmcInvoice,
          createBy: this.$store.state.user.name,
        }
        await searchEcssCoDelNotifyDetail(searchData).then(({data}) => {
          this.exportList= data.rows
          this.exportList.forEach(o => o.cmcInvoice=this.pageData.cmcInvoice);
        })

        return this.exportList;
      },
      startDownload() {
        //  this.exportData = this.dataList

      },
      finishDownload() {
      },
      fields() {
        let json = "{"
        this.columnList1.forEach((item, index) => {
          if (index == this.columnList1.length - 1) {
            json += "\"" + item.columnLabel + "\"" + ":" + "\"" + item.columnProp + "\""
          } else {
            json += "\"" + item.columnLabel + "\"" + ":" + "\"" + item.columnProp + "\"" + ","
          }
        })
        json += "}"
        let s = eval("(" + json + ")")

        return s
      },
    }
  }
</script>
