<template>
  <div class="mod-config">
    <el-form :inline="true" :model="dataForm" @keyup.enter.native="getDataList()">
      <el-form-item>
        <el-input v-model="dataForm.partNo" placeholder="物料编码" clearable></el-input>
      </el-form-item>
      <el-form-item>
        <el-input v-model="dataForm.batchNo" placeholder="批次号" clearable></el-input>
      </el-form-item>
      <el-form-item>
        <el-input v-model="dataForm.locationId" placeholder="库位" clearable></el-input>
      </el-form-item>
      <el-form-item>
        <el-input v-model="dataForm.descriptionLike" placeholder="物料描述" clearable></el-input>
      </el-form-item>
      <el-form-item>
        <el-input v-model="dataForm.minUnPrintQty" placeholder="最小未打印数量" type="number" clearable></el-input>
      </el-form-item>
      <el-form-item>
        <el-button @click="getDataList()">查询</el-button>
        <el-button @click="resetForm()">重置</el-button>
      </el-form-item>
    </el-form>

    <el-table
      :data="dataList"
      border
      :height="height"
      v-loading="dataListLoading"
      @selection-change="selectionChangeHandle"
      style="width: 100%;">
      <el-table-column
        type="selection"
        header-align="center"
        align="center"
        width="50">
      </el-table-column>
      <el-table-column
        prop="site"
        header-align="center"
        align="center"
        label="站点">
      </el-table-column>
      <el-table-column
        prop="warehouseId"
        header-align="center"
        align="center"
        label="仓库">
      </el-table-column>
      <el-table-column
        prop="partNo"
        header-align="center"
        align="center"
        label="物料编码">
      </el-table-column>
      <el-table-column
        prop="description"
        header-align="center"
        align="center"
        label="物料描述">
      </el-table-column>
      <el-table-column
        prop="umid"
        header-align="center"
        align="center"
        label="单位">
      </el-table-column>
      <el-table-column
        prop="batchNo"
        header-align="center"
        align="center"
        label="批次号">
      </el-table-column>
      <el-table-column
        prop="wdr"
        header-align="center"
        align="center"
        label="WDR">
      </el-table-column>
      <el-table-column
        prop="locationId"
        header-align="center"
        align="center"
        label="库位">
      </el-table-column>
      <el-table-column
        prop="qtyOnHand"
        header-align="center"
        align="center"
        label="现有库存">
      </el-table-column>
      <el-table-column
        prop="printQty"
        header-align="center"
        align="center"
        label="已打印数量">
      </el-table-column>
      <el-table-column
        prop="unPrintQty"
        header-align="center"
        align="center"
        label="未打印数量">
      </el-table-column>
      <el-table-column
        fixed="right"
        header-align="center"
        align="center"
        width="150"
        label="操作">
        <template slot-scope="scope">
          <a type="text" @click="createHuHandle(scope.row)">创建HU</a>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      @size-change="sizeChangeHandle"
      @current-change="currentChangeHandle"
      :current-page="pageIndex"
      :page-sizes="[ 20, 50, 100]"
      :page-size="pageSize"
      :total="totalPage"
      layout="total, sizes, prev, pager, next, jumper">
    </el-pagination>

     <!-- 创建HU弹窗 -->
     <el-dialog
       title="创建HandlingUnit"
       :visible.sync="createHuVisible"
       width="400px"
       :close-on-click-modal="false">
       <el-form :model="createHuForm" ref="createHuForm" class="create-hu-form">
         <el-row :gutter="20">
           <el-col :span="12">
             <el-form-item label="物料编码" prop="partNo" class="form-item-vertical">
               <el-input v-model="createHuForm.partNo" readonly></el-input>
             </el-form-item>
           </el-col>
           <el-col :span="12">
             <el-form-item label="批次号" prop="batchNo" class="form-item-vertical">
               <el-input v-model="createHuForm.batchNo" readonly></el-input>
             </el-form-item>
           </el-col>
         </el-row>

         <el-row :gutter="20">
           <el-col :span="12">
             <el-form-item label="WDR" prop="wdr" class="form-item-vertical">
               <el-input v-model="createHuForm.wdr" readonly></el-input>
             </el-form-item>
           </el-col>
           <el-col :span="12">
             <el-form-item label="库位" prop="locationId" class="form-item-vertical">
               <el-input v-model="createHuForm.locationId" readonly></el-input>
             </el-form-item>
           </el-col>
         </el-row>
         <el-row :gutter="20">
           <el-col :span="8">
             <el-form-item label="库存数量" prop="qtyOnHand" class="form-item-vertical">
               <el-input v-model="createHuForm.qtyOnHand" readonly></el-input>
             </el-form-item>
           </el-col>
           <el-col :span="8">
             <el-form-item label="未打印数量" prop="unPrintQty" class="form-item-vertical">
               <el-input v-model="createHuForm.unPrintQty" readonly></el-input>
             </el-form-item>
           </el-col>
           <el-col :span="8">
             <el-form-item label="单位" prop="umid" class="form-item-vertical">
               <el-input v-model="createHuForm.umid" readonly></el-input>
             </el-form-item>
           </el-col>
         </el-row>
         <el-row :gutter="20">
           <el-col :span="24">
             <el-form-item label="物料描述" prop="partDesc" class="form-item-vertical">
               <el-input v-model="createHuForm.partDesc" readonly></el-input>
             </el-form-item>
           </el-col>
         </el-row>

         <el-row :gutter="20">
           <el-col :span="12">
             <el-form-item label="包装数" prop="packageCount" class="form-item-vertical">
               <el-input
                 v-model="createHuForm.packageCount"
                 :min="1"
                 placeholder="请输入包装数">
               </el-input>
             </el-form-item>
           </el-col>
           <el-col :span="12">
             <el-form-item label="单包装数量" prop="perPackageQty" class="form-item-vertical">
               <el-input
                 v-model="createHuForm.perPackageQty"
                 :min="0.01"
                 :precision="2"
                 placeholder="请输入单包装数量">
               </el-input>
             </el-form-item>
           </el-col>
         </el-row>
       </el-form>
       <div slot="footer" class="dialog-footer">
         <el-button @click="createHuVisible = false">取消</el-button>
         <el-button type="primary" @click="createHuSubmit()" :loading="createHuLoading">创建并打印</el-button>
       </div>
     </el-dialog>
  </div>
</template>

<script>
import { getInventoryStockList, createHandlingUnits, printLabel } from '@/api/warehouse/ifsInventoryInit'

export default {
  data () {
    return {
      dataForm: {
        partNo: '',
        batchNo: '',
        locationId: '',
        descriptionLike: '',
        minUnPrintQty: 0
      },
      dataList: [],
      pageIndex: 1,
      pageSize: 50,
      totalPage: 0,
      height: 500,
      dataListLoading: false,
      dataListSelections: [],
      createHuVisible: false,
      createHuLoading: false,
      createHuForm: {
        site: '',
        warehouseId: '',
        partNo: '',
        partDesc: '',
        batchNo: '',
        wdr: '',
        locationId: '',
        umid: '',
        perPackageQty: 1,
        packageCount: 1
      },
      createHuRules: {
        perPackageQty: [
          { required: true, message: '单包装数量不能为空', trigger: 'blur' },
          { type: 'number', min: 0.01, message: '单包装数量必须大于0', trigger: 'blur' }
        ],
        packageCount: [
          { required: true, message: '包装数不能为空', trigger: 'blur' },
          { type: 'number', min: 1, message: '包装数必须大于等于1', trigger: 'blur' }
        ]
      },
      // 打印相关配置
      reportId: 'HU_LABEL',
      zplCode: '',
      paperSize: 'A4',
      orientation: 'Portrait',
      dpi: 300
    }
  },
  activated () {
    this.getDataList()
  },
  methods: {
    // 获取数据列表
    getDataList () {
      this.dataListLoading = true
      const params = {
        page: this.pageIndex,
        size: this.pageSize,
        site: localStorage.getItem('site'),
        ...this.dataForm
      }
      getInventoryStockList(params).then(({ data }) => {
        if (data && data.code === 0) {
          this.dataList = data.page.list
          this.totalPage = data.page.totalCount
        } else {
          this.dataList = []
          this.totalPage = 0
        }
        this.dataListLoading = false
      }).catch(() => {
        this.dataListLoading = false
      })
    },
    // 每页数
    sizeChangeHandle (val) {
      this.pageSize = val
      this.pageIndex = 1
      this.getDataList()
    },
    // 当前页
    currentChangeHandle (val) {
      this.pageIndex = val
      this.getDataList()
    },
    // 多选
    selectionChangeHandle (val) {
      this.dataListSelections = val
    },
    // 创建HU
    createHuHandle (row) {
      this.createHuVisible = true
      this.createHuForm = {
        site: row.site,
        warehouseId: row.warehouseId,
        partNo: row.partNo,
        partDesc: row.description || '',
        batchNo: row.batchNo,
        wdr: row.wdr,
        locationId: row.locationId,
        qtyOnHand: row.qtyOnHand,
        unPrintQty: row.unPrintQty,
        umid: row.umid,
        perPackageQty: '',
        packageCount: 1
      }
      this.$nextTick(() => {
        this.$refs['createHuForm'].clearValidate()
      })
    },
    // 提交创建HU
    createHuSubmit () {
      this.$refs['createHuForm'].validate((valid) => {
        if (valid) {
          this.createHuLoading = true
          createHandlingUnits(this.createHuForm).then(({ data }) => {
            if (data && data.code === 0) {
              this.$message({
                message: '创建HandlingUnit成功',
                type: 'success',
                duration: 1500
              })
              let printLabelType;
              if (this.createHuForm.partNo && this.createHuForm.partNo.startsWith("80")) {
                printLabelType = '库存成品标签';
              } else {
                printLabelType = 'BIL标签';
              }

              // 创建成功后进行打印
              this.printHandlingUnits(data.unitIds,printLabelType)

              this.createHuVisible = false
              this.getDataList()
            } else {
              this.$message.error(data.msg || '创建HandlingUnit失败')
            }
            this.createHuLoading = false
          }).catch(() => {
            this.createHuLoading = false
          })
        }
      })
    },
    // 打印HandlingUnit标签
    async printHandlingUnits (unitIds,printLabelType) {
      if (!unitIds || unitIds.length === 0) {
        return
      }

      try {
        // 逐个打印每个HandlingUnit
        for (const unitId of unitIds) {
          await this.printViaServer(unitId,printLabelType)
        }
        this.$message({
          message: `成功打印 ${unitIds.length} 个HandlingUnit标签`,
          type: 'success',
          duration: 2000
        })
      } catch (error) {
        this.$message.error('打印失败: ' + error.message)
      }
    },
    // 通过服务器打印
    async printViaServer(unitId,printLabelType) {
      try {
        const printRequest = {
          reportId: this.reportId,
          zplCode: this.zplCode,
          paperSize: this.paperSize,
          orientation: this.orientation,
          dpi: this.dpi,
          userId: localStorage.getItem('userName'),
          username: localStorage.getItem('userName'),
          site: localStorage.getItem('site'),
          unitId: unitId,
          labelType: printLabelType
        }
        const { data } = await printLabel(printRequest)
        if (data.code === 200) {
          return Promise.resolve();
        } else {
          return Promise.reject(new Error(data.msg || '打印失败'));
        }
      } catch (error) {
        return Promise.reject(error);
      }
    },
    // 重置表单
    resetForm() {
      this.dataForm = {
        partNo: '',
        batchNo: '',
        locationId: '',
        descriptionLike: '',
        minUnPrintQty: 0
      }
      this.pageIndex = 1
      this.getDataList()
    }
  }
}
</script>

<style scoped>
.mod-config .el-form-item {
  margin-bottom: 15px;
}

/* 创建HU表单样式 */
.create-hu-form .form-item-vertical {
  margin-bottom: 20px;
}

.create-hu-form .form-item-vertical .el-form-item__label {
  display: block;
  text-align: left;
  padding: 0 0 8px 0;
  line-height: 1.5;
  font-weight: 500;
}

.create-hu-form .form-item-vertical .el-form-item__content {
  margin-left: 0 !important;
}

.create-hu-form .el-row {
  margin-bottom: 0;
}
</style>
