<template>
  <div class="customer-css">
    <el-dialog :title="titleCon" :close-on-click-modal="false" :visible.sync="visible" width="380px" 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: 110px">
              <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: 110px"></el-input>
          </el-form-item>
          <el-form-item label=" ">
           <el-button type="primary" @click="exportExcel()">下载文件模板</el-button>
          </el-form-item>
        </el-row>
      </el-form>
      <!-- 栈板托数记录 -->
      <div style="margin: 15px 0;">
        <div style="margin-bottom: 10px;">
          <span >栈板记录:</span>
          <el-tooltip effect="dark" placement="top">
            <div slot="content">
              <div>栈板维护功能说明：</div>
              <div>• 系统会自动加载当前BU下的所有栈板</div>
              <div>• 栈板高度单位为米(M)，请输入准确数值</div>
              <div>• 只有托数大于0的栈板记录才会被保存</div>
            </div>
            <i class="el-icon-question" style="color: #17b3a3; margin-left: 8px; cursor: pointer; font-size: 16px;"></i>
          </el-tooltip>
        </div>
        <el-table :data="palletRecords" border style="width: 100%; margin-bottom: 15px;" class="zxClass"
                  max-height="200" v-if="palletRecords.length > 0">
          <el-table-column label="栈板类型" min-width="100">
            <template slot-scope="scope">
              <el-input v-model="scope.row.palletType" disabled style="width: 100%;"></el-input>
            </template>
          </el-table-column>
          <el-table-column label="栈板高度(M)" width="100">
            <template slot-scope="scope">
              <el-input v-model="scope.row.height" type="text"  placeholder="请输入高度" style="width: 100%;"></el-input>
            </template>
          </el-table-column>
          <el-table-column label="托数" width="80">
            <template slot-scope="scope">
              <el-input v-model="scope.row.palletQty" type="text" placeholder="请输入托数" style="width: 100%;"></el-input>
            </template>
          </el-table-column>
        </el-table>
        <div v-if="palletRecords.length === 0" style="text-align: center; color: #999; padding: 20px; border: 1px dashed #ddd;">
          正在加载栈板记录...
        </div>
      </div>

      <!-- 文件上传区域 -->
      <div style="margin: 15px 0;">
        <div style="margin-bottom: 10px;">文件上传:</div>
        <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>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" :loading="saveLoading" :disabled="saveLoading" @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,updateExportFlag,searchPalletList} 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,
        saveLoading: false,
        fileList: [],
        pageData: {
          site: '',
          buNo: '',
          delNo:'',
          cmcInvoice:'',
          createBy: this.$store.state.user.name,
        },
        // 栈板记录
        palletRecords: [],
        // 导出 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: "/ecss/coDel/searchCoDelPalletList",
          columnMapping:  excelOpts.PalletSku.columnMapping,//可以直接用table，不需要的列就剔除
          mergeSetting: [],//需要合并的列
          params: searchData,
          fileName: this.exportName+".xlsx",
          rowFetcher: res => res.data,
          columnFormatter: [],
          dropColumns: [],//需要剔除的列，例如dropColumns: ["netWeight"]，即剔除净重列
        });
        // 导出成功后更新export_flag字段
        let updateData = {
          site: this.pageData.site,
          buNo: this.pageData.buNo,
          delNo: this.pageData.delNo,
          exportFlag: 'Y',
          updateBy: this.$store.state.user.name
        }

        updateExportFlag(updateData).then(({data}) => {
          if (data.code === 0) {
            console.info('更新成功:');
          }
        }).catch(error => {
          this.$message.warning('导出成功，但更新导出状态失败');
          console.error('更新导出状态失败:', error);
        });
      },
      // 初始化组件的参数
      init (inData) {
        this.fileList = []
        this.palletRecords = [] // 重置栈板记录
        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,
        }

        // 默认根据buNo获取全部栈板
        this.loadAllPallets()

        // 打开页面
        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.palletRecords = [] // 清空栈板记录
        // 清空文件上传记录
        this.$refs.uploadFile.clearFiles()
        // 刷新报工的页面
        this.$emit('refreshTable')

      },

      // 保修当前的数据
      saveUploadFile () {
        // 判断文件是否上传
        if (null == this.fileList || 0 === this.fileList.length) {
          this.$message.error("请先上传文件!")
          return false
        }

        // 过滤出托数大于0的栈板记录
        const validPalletRecords = this.palletRecords.filter(record => {
          return record.palletQty && parseFloat(record.palletQty) > 0
        })

        // 验证有效的栈板记录
        for (let i = 0; i < validPalletRecords.length; i++) {
          const record = validPalletRecords[i]
          if (!record.pallet) {
            this.$message.error(`栈板不能为空!`)
            return false
          }
          if (!record.height || record.height <= 0) {
            this.$message.error(`栈板高度必须大于0!`)
            return false
          }
        }
        this.saveLoading = true
        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)
        // 只添加托数大于0的栈板记录数据
        formData.append("palletRecords", JSON.stringify(validPalletRecords))
        // 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: '确定'
            })
            this.deleteFile()
          }
        }).catch((error) => {
          console.error('保存失败:', error)
          this.$message.error('保存失败，请重试')
        }).finally(() => {
          this.saveLoading = false
        })
      },

      // 下载
      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
      },



      // 根据buNo加载全部栈板
      loadAllPallets() {
        let searchData = {
          palletType: '', // 不限制栈板类型，获取全部
          buNo: this.pageData.buNo
        }
        searchPalletList(searchData).then(({data}) => {
          if (data.code === 0) {
            const pallets = data.rows || []
            // 为每个栈板创建一条记录
            this.palletRecords = pallets.map(pallet => ({
              pallet: pallet.palletNo,
              palletType: pallet.palletType,
              palletQty: '', // 默认为空，用户需要输入
              height: '' // 使用栈板的默认高度
            }))
          }
        }).catch(error => {
          console.error('加载栈板列表失败:', error)
          // 如果加载失败，至少添加一行空记录
          this.palletRecords = [{
            pallet: '',
            palletType: '',
            palletQty: '',
            height: ''
          }]
        })
      },
    }
  }
</script>
<style scoped>
/deep/ .zxClass .cell {
  line-height: 24px;
  font-size: 12px;
  height: 24px;
}
</style>
