<template>
  <div class="mod-config">
    <!-- 查询表单 - rqrq -->
    <el-form :inline="true" label-position="top">
      <el-form-item label="条码号">
        <el-input style="width: 120px;" v-model="queryHeaderData.unitId" placeholder="请输入条码号" @keyup.enter.native="getDataList()"></el-input>
      </el-form-item>
      <el-form-item label="物料编号">
        <el-input style="width: 120px;" v-model="queryHeaderData.partNo" placeholder="请输入物料编号" @keyup.enter.native="getDataList()"></el-input>
      </el-form-item>
      <el-form-item label="批次号">
        <el-input style="width: 120px;" v-model="queryHeaderData.batchNo" placeholder="请输入批次号" @keyup.enter.native="getDataList()"></el-input>
      </el-form-item>
      <el-form-item label="库位">
        <el-input style="width: 120px;" v-model="queryHeaderData.locationId" placeholder="请输入库位" @keyup.enter.native="getDataList()"></el-input>
      </el-form-item>
      <el-form-item label="仓库">
        <el-input style="width: 120px;" v-model="queryHeaderData.warehouseId" placeholder="请输入仓库" @keyup.enter.native="getDataList()"></el-input>
      </el-form-item>
      <el-form-item style="margin-top: 20px;">
        <el-button @click="getDataList()" type="primary">查询</el-button>
        <el-button @click="resetQuery()" type="default">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 功能按钮区 - rqrq -->
    <el-form :inline="true" label-position="top" style="margin-top: 3px">
      <el-button @click="openChangeWdrDialog()" type="primary" :disabled="dataListSelections.length === 0">Change W/D/R</el-button>
      <el-button @click="openChangeExpDateDialog()" type="primary" :disabled="dataListSelections.length === 0">Change Expiration Date</el-button>
      <el-button @click="openChangeAvailDialog()" type="primary" :disabled="dataListSelections.length === 0">Change Availability Control ID</el-button>
    </el-form>

    <!-- 主表格 - rqrq -->
    <el-table
      :height="height"
      :data="dataList"
      border
      v-loading="dataListLoading"
      @selection-change="selectionChangeHandle"
      style="width: 100%; margin-bottom: 15px;margin-top:3px">

      <!-- 选择列 - rqrq -->
      <el-table-column
        type="selection"
        header-align="center"
        align="center"
        width="50"
        :selectable="checkSelectable">
      </el-table-column>

      <!-- 动态列配置 - rqrq -->
      <el-table-column
        v-for="(item,index) in columnList" :key="index"
        :sortable="item.columnSortable"
        :prop="item.columnProp"
        :header-align="item.headerAlign"
        :show-overflow-tooltip="item.showOverflowTooltip"
        :align="item.align"
        :fixed="item.fixed==''?false:item.fixed"
        :min-width="item.columnWidth"
        :label="item.columnLabel">
        <template slot-scope="scope">
          <span v-if="item.columnProp === 'inStockFlag'">
            <span v-if="scope.row.inStockFlag === 'Y'">在库</span>
            <span v-else-if="scope.row.inStockFlag === 'N'">已出库</span>
            <span v-else-if="scope.row.inStockFlag === 'X'">未入库</span>
            <span v-else>{{ scope.row.inStockFlag }}</span>
          </span>
          <span v-else-if="item.columnProp === 'reserveFlag'">
            {{ scope.row.reserveFlag === 'Y' ? '是' : '否' }}
          </span>
          <span v-else-if="item.columnProp === 'freezeFlag'">
            {{ scope.row.freezeFlag === 'Y' ? '是' : '否' }}
          </span>
          <span v-else-if="item.columnProp === 'mergedFlag'">
            {{ scope.row.mergedFlag === 'Y' ? '是' : '否' }}
          </span>
          <span v-else-if="item.columnProp === 'manufactureDate' || item.columnProp === 'expiredDate' || item.columnProp === 'receiveDate' || item.columnProp === 'createdDate' || item.columnProp === 'modifiedDate' || item.columnProp === 'lastPrintDate'">
            {{ formatDate(scope.row[item.columnProp]) }}
          </span>
          <span v-else>{{ scope.row[item.columnProp] }}</span>
        </template>
      </el-table-column>

      <!-- 操作列 - rqrq -->
      <el-table-column label="操作" min-width="120" fixed="right" header-align="center" align="center">
        <template slot-scope="scope">
          <a @click="viewDetail(scope.row)" type="primary">查看详细</a>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 - rqrq -->
    <el-pagination
      @size-change="sizeChangeHandle"
      @current-change="currentChangeHandle"
      :current-page="pageIndex"
      :page-sizes="[30, 100, 500]"
      :page-size="pageSize"
      :total="totalPage"
      layout="total, sizes, prev, pager, next, jumper">
    </el-pagination>

    <!-- 查看详细信息弹窗 - rqrq -->
    <el-dialog
      title="查看详细信息"
      :visible.sync="dialogVisible"
      :close-on-click-modal="false"
      v-drag
      width="900px">

      <el-form :model="formData" ref="dataForm" label-position="top" style="margin-top: 1px; margin-left: 0px;">
        <!-- 基本信息（只读）- rqrq -->
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="条码号">
              <el-input v-model="formData.unitId" readonly></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="物料编号">
              <el-input v-model="formData.partNo" readonly></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="批次号">
              <el-input v-model="formData.batchNo" readonly></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="数量">
              <el-input v-model="formData.qty" readonly></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 订单参考信息 - rqrq -->
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="订单参考1">
              <el-input v-model="formData.orderRef1"  readonly></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="订单参考2">
              <el-input v-model="formData.orderRef2"  readonly></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="订单参考3">
              <el-input v-model="formData.orderRef3"  readonly></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 供应商/客户信息 - rqrq -->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="供应商ID">
              <el-input v-model="formData.supplierId"  readonly></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="客户ID">
              <el-input v-model="formData.customerId"  readonly></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 日期信息 - rqrq -->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="生产日期">
              <el-input v-model="formData.manufactureDate" readonly></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="失效日期">
              <el-input v-model="formData.expiredDate" readonly></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 来源信息 - rqrq -->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="来源类型">
              <el-input v-model="formData.sourceType"  readonly></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="来源参考">
              <el-input v-model="formData.sourceRef"  readonly></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 重量/体积信息 - rqrq -->
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="毛重">
              <el-input v-model="formData.grossWeight"  readonly></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="净重">
              <el-input v-model="formData.netWeight"  readonly></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="重量单位">
              <el-input v-model="formData.weightUnit"  readonly></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="EngChgLevel">
              <el-input v-model="formData.engChgLevel"  readonly></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="体积">
              <el-input v-model="formData.volume"  readonly></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="体积单位">
              <el-input v-model="formData.volumeUnit"  readonly></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 预留信息 - rqrq -->
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="预留订单参考1">
              <el-input v-model="formData.reserveOrderRef1"  readonly></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="预留订单参考2">
              <el-input v-model="formData.reserveOrderRef2"  readonly></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="预留订单参考3">
              <el-input v-model="formData.reserveOrderRef3"  readonly></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 备注 - rqrq -->
        <el-row>
          <el-col :span="24">
            <el-form-item label="备注">
              <el-input v-model="formData.remark" type="textarea" :rows="3" resize='none'  readonly></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <div slot="footer" class="dialog-footer" style="margin-top: 52px">
        <el-button type="primary" @click="dialogVisible = false">关闭</el-button>
      </div>
    </el-dialog>

    <!-- Change W/D/R 弹窗 - rqrq -->
    <el-dialog
      title="Change W/D/R"
      :visible.sync="wdrDialogVisible"
      :close-on-click-modal="false"
      v-drag
      width="400px">

      <el-form label-position="top" style="margin-top: 1px; margin-left: 0px;">
        <el-form-item label="To W/D/R">
          <el-input v-model="wdrFormData.toWdr" placeholder="请输入W/D/R"></el-input>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="saveWdrChange" :disabled="wdrSaveLoading">
          {{ wdrSaveLoading ? 'Save中...' : 'Save' }}
        </el-button>
        <el-button @click="closeWdrDialog" :disabled="wdrSaveLoading">Close</el-button>
      </div>
    </el-dialog>

    <!-- Change Expiration Date 弹窗 - rqrq -->
    <el-dialog
      title="Change Expiration Date"
      :visible.sync="expDateDialogVisible"
      :close-on-click-modal="false"
      v-drag
      width="400px">


      <el-form label-position="top" style="margin-top: 1px; margin-left: 0px;">
        <el-form-item label="New Expiration Date">
          <el-date-picker
            v-model="expDateFormData.newExpDate"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择失效日期"
            style="width: 100%">
          </el-date-picker>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="saveExpDateChange" :disabled="expDateSaveLoading">
          {{ expDateSaveLoading ? 'Save中...' : 'Save' }}
        </el-button>
        <el-button @click="closeExpDateDialog" :disabled="expDateSaveLoading">Close</el-button>
      </div>
    </el-dialog>

    <!-- Change Availability Control ID 弹窗 - rqrq -->
    <el-dialog
      title="Change Availability Control ID"
      :visible.sync="availDialogVisible"
      :close-on-click-modal="false"
      v-drag
      width="400px">

      <el-form label-position="top" style="margin-top: 1px; margin-left: 0px;">
        <el-form-item label="New Availability Control ID">
          <el-input v-model="availFormData.newAvailId" placeholder="请输入Availability Control ID" @blur="handleAvailIdBlur">
            <el-button slot="append" @click="showAvailList">List</el-button>
          </el-input>
        </el-form-item>
        <el-form-item label="New Availability Control Desc">
          <el-input v-model="availFormData.newAvailDesc" disabled placeholder="描述（自动填充）"></el-input>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="saveAvailChange" :disabled="availSaveLoading">
          {{ availSaveLoading ? 'Save中...' : 'Save' }}
        </el-button>
        <el-button @click="closeAvailDialog" :disabled="availSaveLoading">Close</el-button>
      </div>
    </el-dialog>

    <!-- Availability Control ID 选择弹窗 - rqrq -->
    <el-dialog
      title="选择 Availability Control ID"
      :visible.sync="availListDialogVisible"
      :close-on-click-modal="false"
      v-drag
      width="600px"
      append-to-body>

      <!-- 搜索区域 - rqrq -->
      <el-form :inline="true" label-position="top" style="margin-bottom: 10px;">
        <el-form-item label="ID">
          <el-input style="width: 150px;" v-model="availListQueryData.searchAvailabilityControlId" placeholder="请输入" @keyup.enter.native="getAvailList()" clearable></el-input>
        </el-form-item>
        <el-form-item label="描述">
          <el-input style="width: 150px;" v-model="availListQueryData.searchAvailabilityControlDesc" placeholder="请输入" @keyup.enter.native="getAvailList()" clearable></el-input>
        </el-form-item>
        <el-form-item style="margin-top: 20px;">
          <el-button @click="getAvailList()" type="primary">查询</el-button>
        </el-form-item>
      </el-form>

      <!-- 列表 - rqrq -->
      <el-table
        :data="availListData"
        border
        highlight-current-row
        v-loading="availListLoading"
        @row-dblclick="handleAvailListDblClick"
        height="300"
        style="width: 100%;">

        <el-table-column
          prop="availabilityControlId"
          header-align="center"
          align="center"
          label="Availability Control ID"
          min-width="180">
        </el-table-column>

        <el-table-column
          prop="availabilityControlDesc"
          header-align="center"
          align="left"
          label="描述"
          min-width="250"
          show-overflow-tooltip>
        </el-table-column>
      </el-table>

      <div slot="footer" class="dialog-footer">
        <el-button @click="availListDialogVisible = false">关闭</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { searchHandlingUnitList, batchChangeAvailabilityControlId, batchChangeExpiryDate, batchChangeWdr } from '@/api/warehouse/changeHUSpecialItem'
import { activeList, getDescById } from '@/api/warehouse/availabilityControlId'

export default {
  data() {
    return {
      // 页面状态 - rqrq
      height: 500,
      dataListLoading: false,

      // 弹窗状态 - rqrq
      dialogVisible: false,

      // 三个功能弹窗状态 - rqrq
      wdrDialogVisible: false,
      expDateDialogVisible: false,
      availDialogVisible: false,
      wdrSaveLoading: false,
      expDateSaveLoading: false,
      availSaveLoading: false,

      // Availability Control ID列表弹窗状态 - rqrq
      availListDialogVisible: false,
      availListLoading: false,
      availListData: [],
      availListQueryData: {
        searchAvailabilityControlId: '',
        searchAvailabilityControlDesc: ''
      },

      // 数据列表 - rqrq
      dataList: [],
      dataListSelections: [],

      // 查询条件 - rqrq
      queryHeaderData: {
        site: this.$store.state.user.site,
        unitId: '',
        partNo: '',
        batchNo: '',
        locationId: '',
        warehouseId: '',
        inStockFlag: 'Y'
      },

      // 表单数据 - rqrq
      formData: {},

      // 三个功能表单数据 - rqrq
      wdrFormData: {
        toWdr: ''
      },
      expDateFormData: {
        newExpDate: ''
      },
      availFormData: {
        newAvailId: '',
        newAvailDesc: ''
      },

      // 分页信息 - rqrq
      pageIndex: 1,
      pageSize: 30,
      totalPage: 0,

      // 表格列配置 - rqrq
      columnList: [
        {
          columnProp: "unitId",
          headerAlign: "center",
          align: "center",
          columnLabel: "条码号",
          columnWidth: 150,
          columnSortable: false,
          showOverflowTooltip: true,
          fixed: ""
        },
        {
          columnProp: "partNo",
          headerAlign: "center",
          align: "center",
          columnLabel: "物料编号",
          columnWidth: 100,
          columnSortable: false,
          showOverflowTooltip: true,
          fixed: ""
        },
        {
          columnProp: "batchNo",
          headerAlign: "center",
          align: "center",
          columnLabel: "批次号",
          columnWidth: 140,
          columnSortable: false,
          showOverflowTooltip: true,
          fixed: ""
        },
        {
          columnProp: "qty",
          headerAlign: "center",
          align: "right",
          columnLabel: "数量",
          columnWidth: 70,
          columnSortable: false,
          showOverflowTooltip: true,
          fixed: ""
        },
        {
          columnProp: "locationId",
          headerAlign: "center",
          align: "center",
          columnLabel: "库位",
          columnWidth: 90,
          columnSortable: false,
          showOverflowTooltip: true,
          fixed: ""
        },
        {
          columnProp: "warehouseId",
          headerAlign: "center",
          align: "center",
          columnLabel: "仓库",
          columnWidth: 60,
          columnSortable: false,
          showOverflowTooltip: true,
          fixed: ""
        },
        {
          columnProp: "wdr",
          headerAlign: "center",
          align: "center",
          columnLabel: "WDR",
          columnWidth: 100,
          columnSortable: false,
          showOverflowTooltip: true,
          fixed: ""
        },
        {
          columnProp: "availabilityControlId",
          headerAlign: "center",
          align: "center",
          columnLabel: "Availability Control Id",
          columnWidth: 150,
          columnSortable: false,
          showOverflowTooltip: true,
          fixed: ""
        },
        {
          columnProp: "expiredDate",
          headerAlign: "center",
          align: "center",
          columnLabel: "失效日期",
          columnWidth: 100,
          columnSortable: false,
          showOverflowTooltip: true,
          fixed: ""
        },
        {
          columnProp: "engChgLevel",
          headerAlign: "center",
          align: "center",
          columnLabel: "EngChgLevel",
          columnWidth: 90,
          columnSortable: false,
          showOverflowTooltip: true,
          fixed: ""
        },
        {
          columnProp: "manufactureDate",
          headerAlign: "center",
          align: "center",
          columnLabel: "生产日期",
          columnWidth: 100,
          columnSortable: false,
          showOverflowTooltip: true,
          fixed: ""
        },
        {
          columnProp: "partDesc",
          headerAlign: "center",
          align: "center",
          columnLabel: "物料描述",
          columnWidth: 200,
          columnSortable: false,
          showOverflowTooltip: true,
          fixed: ""
        },
      ]
    }
  },
  watch: {
    wdrFormData: {
      deep: true,
      handler: function (newV, oldV) {
        this.wdrFormData.toWdr = this.wdrFormData.toWdr.toUpperCase()
      }
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.height = window.innerHeight - 220;
    })
    // 计算表格高度 - rqrq

    // 加载初始数据 - rqrq
    this.getDataList()
  },
  methods: {
    // 查询列表数据 - rqrq
    getDataList() {
      this.dataListLoading = true

      const params = {
        ...this.queryHeaderData,
        page: this.pageIndex,
        limit: this.pageSize
      }

      searchHandlingUnitList(params).then(({data}) => {
        this.dataListLoading = false
        if (data && data.code == 0) {
          this.dataList = data.page.list || []
          this.pageIndex = data.page.currPage
          this.totalPage = data.page.totalCount
        } else {
          this.dataList = []
          this.totalPage = 0
          this.$message.error(data.msg || '查询失败')
        }
      }).catch(() => {
        this.dataListLoading = false
        this.$message.error('查询失败')
      })
    },

    // 重置查询条件 - rqrq
    resetQuery() {
      this.queryHeaderData = {
        site: this.$store.state.user.site,
        unitId: '',
        partNo: '',
        batchNo: '',
        locationId: '',
        warehouseId: '',
        inStockFlag: ''
      }
      this.pageIndex = 1
      this.getDataList()
    },

    // 每页数变化 - rqrq
    sizeChangeHandle(val) {
      this.pageSize = val
      this.pageIndex = 1
      this.getDataList()
    },

    // 当前页变化 - rqrq
    currentChangeHandle(val) {
      this.pageIndex = val
      this.getDataList()
    },

    // 选择变化 - rqrq
    selectionChangeHandle(val) {
      this.dataListSelections = val
    },

    // 查看详细信息 - rqrq
    viewDetail(row) {
      this.formData = JSON.parse(JSON.stringify(row))
      this.dialogVisible = true
    },

    // 格式化日期 - rqrq
    formatDate(dateStr) {
      if (!dateStr) return ''
      const date = new Date(dateStr)
      const year = date.getFullYear()
      const month = String(date.getMonth() + 1).padStart(2, '0')
      const day = String(date.getDate()).padStart(2, '0')
      const hours = String(date.getHours()).padStart(2, '0')
      const minutes = String(date.getMinutes()).padStart(2, '0')
      const seconds = String(date.getSeconds()).padStart(2, '0')

      if (hours === '00' && minutes === '00' && seconds === '00') {
        return `${year}-${month}-${day}`
      }
      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
    },

    // 校验行是否可选择（必须有物料编号）- rqrq
    checkSelectable(row) {
      if (!row.partNo || row.partNo === '') {
        return false
      }
      return true
    },

    // ==================== Change W/D/R相关方法 - rqrq ====================

    // 打开Change W/D/R弹窗 - rqrq
    openChangeWdrDialog() {
      if (this.dataListSelections.length === 0) {
        this.$message.warning('请先选择要修改的记录')
        return
      }

      // 重置表单 - rqrq
      this.wdrFormData = {
        toWdr: ''
      }
      this.wdrDialogVisible = true
    },

    // 关闭W/D/R弹窗 - rqrq
    closeWdrDialog() {
      this.wdrDialogVisible = false
      this.wdrFormData = {
        toWdr: ''
      }
    },

    // 保存W/D/R修改 - rqrq
    saveWdrChange() {
      // 参数校验 - rqrq
      if (!this.wdrFormData.toWdr) {
        this.$message.warning('请输入W/D/R')
        return
      }

      // 构建提示信息，显示选中的标签数量 - rqrq
      const selectedCount = this.dataListSelections.length

      // 按库存关键字去重统计 - rqrq
      const inventoryKeySet = new Set()
      this.dataListSelections.forEach(item => {
        const key = `${item.site}|${item.partNo}|${item.locationId}|${item.batchNo}|${item.wdr}|${item.engChgLevel}`
        inventoryKeySet.add(key)
      })
      const inventoryCount = inventoryKeySet.size

      this.$confirm(`确认将选中的 ${selectedCount} 个标签（${inventoryCount}行库存）的W/D/R修改为 "${this.wdrFormData.toWdr}" 吗？`, '确认修改', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.doSaveWdrChange()
      }).catch(() => {
        // 取消操作
      })
    },

    // 执行W/D/R修改 - rqrq
    doSaveWdrChange() {
      this.wdrSaveLoading = true

      const requestData = {
        selectedItems: this.dataListSelections,
        newWdr: this.wdrFormData.toWdr
      }

      batchChangeWdr(requestData).then(({ data }) => {
        if (data && data.code == 0) {
          const result = data.row
          this.showChangeResult(result, 'W/D/R修改', () => {
            this.closeWdrDialog()
            this.getDataList()
          })
        } else {
          this.$alert(data.msg || 'W/D/R修改失败', '错误')
        }
      }).catch(error => {
        this.$message.error('W/D/R修改失败：' + (error.message || '网络错误'))
      }).finally(() => {
        this.wdrSaveLoading = false
      })
    },

    // ==================== Change Expiration Date相关方法 - rqrq ====================

    // 打开Change Expiration Date弹窗 - rqrq
    openChangeExpDateDialog() {
      if (this.dataListSelections.length === 0) {
        this.$message.warning('请先选择要修改的记录')
        return
      }

      // 重置表单 - rqrq
      this.expDateFormData = {
        newExpDate: ''
      }
      this.expDateDialogVisible = true
    },

    // 关闭Expiration Date弹窗 - rqrq
    closeExpDateDialog() {
      this.expDateDialogVisible = false
      this.expDateFormData = {
        newExpDate: ''
      }
    },

    // 保存Expiration Date修改 - rqrq
    saveExpDateChange() {
      // 参数校验 - rqrq
      if (!this.expDateFormData.newExpDate) {
        this.$message.warning('请选择失效日期')
        return
      }

      // 构建提示信息，显示选中的标签数量和去重后的库存行数 - rqrq
      const selectedCount = this.dataListSelections.length

      // 按库存关键字去重统计 - rqrq
      const inventoryKeySet = new Set()
      this.dataListSelections.forEach(item => {
        const key = `${item.site}|${item.partNo}|${item.locationId}|${item.batchNo}|${item.wdr}|${item.engChgLevel}`
        inventoryKeySet.add(key)
      })
      const inventoryCount = inventoryKeySet.size

      // 确认提示 - rqrq
      const confirmMsg = `您选择了 ${selectedCount} 个标签，涉及 ${inventoryCount} 行ERP库存。\n\n` +
        `注意：同一行ERP库存下的所有标签将一起被修改为新的失效日期：${this.expDateFormData.newExpDate}\n\n` +
        `确定要执行此操作吗？`

      this.$confirm(confirmMsg, '确认修改', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.doSaveExpDateChange()
      }).catch(() => {})
    },

    // 执行Expiration Date修改 - rqrq
    doSaveExpDateChange() {
      this.expDateSaveLoading = true

      const requestData = {
        selectedItems: this.dataListSelections,
        newExpiryDate: this.expDateFormData.newExpDate
      }

      batchChangeExpiryDate(requestData).then(({ data }) => {
        if (data && data.code == 0) {
          const result = data.row
          this.showChangeResult(result, '失效日期修改', () => {
            this.closeExpDateDialog()
            this.getDataList()
          })
        } else {
          this.$alert(data.msg || '修改失败', '提示', { type: 'error' })
        }
      }).catch((error) => {
        this.$message.error('修改失败：' + (error.message || '网络错误'))
      }).finally(() => {
        this.expDateSaveLoading = false
      })
    },

    // ==================== Change Availability Control ID相关方法 - rqrq ====================

    // 打开Change Availability Control ID弹窗 - rqrq
    openChangeAvailDialog() {
      if (this.dataListSelections.length === 0) {
        this.$message.warning('请先选择要修改的记录')
        return
      }

      // 重置表单 - rqrq
      this.availFormData = {
        newAvailId: '',
        newAvailDesc: ''
      }
      this.availDialogVisible = true
    },

    // 关闭Availability Control ID弹窗 - rqrq
    closeAvailDialog() {
      this.availDialogVisible = false
      this.availFormData = {
        newAvailId: '',
        newAvailDesc: ''
      }
    },

    // 显示Availability Control ID列表 - rqrq
    showAvailList() {
      this.availListQueryData = {
        searchAvailabilityControlId: '',
        searchAvailabilityControlDesc: ''
      }
      this.availListDialogVisible = true
      this.getAvailList()
    },

    // 查询Availability Control ID列表 - rqrq
    getAvailList() {
      this.availListLoading = true
      activeList().then(({ data }) => {
        this.availListLoading = false
        if (data && data.code == 0) {
          let list = data.rows || []
          // 前端过滤 - rqrq
          if (this.availListQueryData.searchAvailabilityControlId) {
            list = list.filter(item =>
              item.availabilityControlId &&
              item.availabilityControlId.toUpperCase().includes(this.availListQueryData.searchAvailabilityControlId.toUpperCase())
            )
          }
          if (this.availListQueryData.searchAvailabilityControlDesc) {
            list = list.filter(item =>
              item.availabilityControlDesc &&
              item.availabilityControlDesc.toUpperCase().includes(this.availListQueryData.searchAvailabilityControlDesc.toUpperCase())
            )
          }
          this.availListData = list
        } else {
          this.availListData = []
          this.$message.error(data.msg || '查询失败')
        }
      }).catch(() => {
        this.availListLoading = false
        this.$message.error('查询失败')
      })
    },

    // 双击选择Availability Control ID - rqrq
    handleAvailListDblClick(row) {
      this.availFormData.newAvailId = row.availabilityControlId
      this.availFormData.newAvailDesc = row.availabilityControlDesc || ''
      this.availListDialogVisible = false
    },

    // Availability Control ID失去焦点事件 - rqrq
    handleAvailIdBlur() {
      if (!this.availFormData.newAvailId) {
        this.availFormData.newAvailDesc = ''
        return
      }

      getDescById(this.availFormData.newAvailId).then(({ data }) => {
        if (data && data.code == 0) {
          // row可能是null或描述字符串 - rqrq
          this.availFormData.newAvailDesc = data.row || ''
        } else {
          this.availFormData.newAvailDesc = ''
        }
      }).catch(() => {
        this.availFormData.newAvailDesc = ''
      })
    },

    // 保存Availability Control ID修改 - rqrq
    saveAvailChange() {
      // 参数校验 - rqrq
      if (!this.availFormData.newAvailId) {
        this.$message.warning('请输入Availability Control ID')
        return
      }

      // 构建提示信息，显示选中的标签数量和去重后的库存行数 - rqrq
      const selectedCount = this.dataListSelections.length

      // 按库存关键字去重统计 - rqrq
      const inventoryKeySet = new Set()
      this.dataListSelections.forEach(item => {
        const key = `${item.site}|${item.partNo}|${item.locationId}|${item.batchNo}|${item.wdr}|${item.engChgLevel}`
        inventoryKeySet.add(key)
      })
      const inventoryCount = inventoryKeySet.size

      // 确认提示 - rqrq
      const confirmMsg = `您选择了 ${selectedCount} 个标签，涉及 ${inventoryCount} 行ERP库存。\n\n` +
        `注意：同一行ERP库存下的所有标签将一起被修改为新的 Availability Control ID：${this.availFormData.newAvailId}\n\n` +
        `确定要执行此操作吗？`

      this.$confirm(confirmMsg, '确认修改', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.doSaveAvailChange()
      }).catch(() => {})
    },

    // 执行Availability Control ID修改 - rqrq
    doSaveAvailChange() {
      this.availSaveLoading = true

      const requestData = {
        selectedItems: this.dataListSelections,
        newAvailabilityControlId: this.availFormData.newAvailId
      }

      batchChangeAvailabilityControlId(requestData).then(({ data }) => {
        if (data && data.code == 0) {
          const result = data.row
          this.showChangeResult(result, 'Availability Control ID修改', () => {
            this.closeAvailDialog()
            this.getDataList()
          })
        } else {
          this.$alert(data.msg || '修改失败', '提示', { type: 'error' })
        }
      }).catch((error) => {
        this.$message.error('修改失败：' + (error.message || '网络错误'))
      }).finally(() => {
        this.availSaveLoading = false
      })
    },

    // ==================== 通用结果显示方法 - rqrq ====================

    /**
     * 显示修改结果弹窗 - rqrq
     * @param result 后端返回的结果对象
     * @param title 操作标题
     * @param callback 弹窗关闭后的回调
     */
    showChangeResult(result, title, callback) {
      const successCount = result.successCount || 0
      const failCount = result.failCount || 0
      const failedUnitIds = result.failedUnitIds || []
      const failedReasons = result.failedReasons || []

      // 构建弹窗内容 - rqrq
      let htmlContent = `<div style="line-height: 1.8;">`
      htmlContent += `<p><b>成功数量：</b>${successCount}</p>`
      htmlContent += `<p><b>失败数量：</b>${failCount}</p>`

      if (failCount > 0 && failedUnitIds.length > 0) {
        // 失败序列号（用逗号分隔）- rqrq
        htmlContent += `<p><b>失败序列号：</b>${failedUnitIds.join(', ')}</p>`

        // 失败报错（只显示第一个）- rqrq
        const firstError = failedReasons.length > 0 ? failedReasons[0] : '未知错误'
        htmlContent += `<p><b>失败报错：</b>${firstError}</p>`
      }
      htmlContent += `</div>`

      // 根据是否有失败决定弹窗类型 - rqrq
      const dialogType = failCount > 0 ? 'warning' : 'success'
      const dialogTitle = failCount > 0 ? `${title}结果（部分失败）` : `${title}结果`

      this.$alert(htmlContent, dialogTitle, {
        dangerouslyUseHTMLString: true,
        confirmButtonText: '确定',
        type: dialogType,
        callback: () => {
          if (callback) callback()
        }
      })
    }
  }
}
</script>

<style scoped>
/* 按钮禁用样式 - rqrq */
.el-button:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}
</style>

