<template>
  <div class="mod-config">
    <div>
      <span @click="favoriteFunction()">
        <icon-svg :name="favorite?'xiangqufill':'xiangqu'" class="sl-svg"></icon-svg>
      </span>
    </div>

    <el-form :inline="true" label-position="top">
      <el-form-item :label="inputLabel.headerInput.label0">
        <el-select v-model="queryHeaderData.site" placeholder="请选择工厂" style="width: 120px;" clearable>
          <el-option
            v-for="item in siteOptions"
            :key="item.site"
            :label="item.siteName || item.site"
            :value="item.site">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item :label="inputLabel.headerInput.label1">
        <el-input style="width: 150px;" v-model="queryHeaderData.palletId" placeholder="托盘ID" clearable @keyup.enter.native="getDataList()"></el-input>
      </el-form-item>
      <el-form-item :label="inputLabel.headerInput.label2">
        <el-select v-model="queryHeaderData.palletFamily" placeholder="请选择" style="width: 120px;" clearable>
          <el-option label="全部" value=""></el-option>
          <el-option label="钢托盘" value="A01"></el-option>
          <el-option label="围挡托盘" value="A02"></el-option>
          <el-option label="平托盘+周转箱" value="A03"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item :label="inputLabel.headerInput.label3">
        <el-select v-model="queryHeaderData.status" placeholder="请选择" style="width: 120px;" clearable>
          <el-option label="全部" value=""></el-option>
          <el-option
            v-for="item in statusOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item :label="inputLabel.headerInput.label4">
        <el-input style="width: 150px;" v-model="queryHeaderData.locationCode" placeholder="所在站点" clearable @keyup.enter.native="getDataList()"></el-input>
      </el-form-item>
      <el-form-item style="margin-top: 20px;">
        <el-button @click="getDataList()" type="primary">查询</el-button>
        <!-- 导出按钮 - rqrq -->
        <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--primary el-button--medium">
          {{ '导出' }}
        </download-excel>
      </el-form-item>
      <el-form-item style="margin-top: 20px;">
<!--        <el-button @click="initModel()" type="primary">新增</el-button>-->
<!--        <el-button v-if="isAuth(':pallet:delete')" type="danger" @click="deleteHandle()"-->
<!--                   :disabled="dataListSelections.length <= 0">{{ buttons.deleteList}}-->
<!--        </el-button>-->
        <!-- 批量新增按钮 - rqrq -->
        <el-button @click="openBatchGenerateDialog()" type="success">批量新增托盘</el-button>
      </el-form-item>
    </el-form>

    <el-table
      id="palletTable"
      :height="height"
      :data="dataList"
      border
      v-loading="dataListLoading"
      @selection-change="selectionChangeHandle"
      style="width: 100%;">
      <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.columnHidden"> {{scope.row[item.columnProp]}}</span>
          <span v-if="item.columnImage"><img :src="scope.row[item.columnProp]"
                                             style="width: 100px; height: 80px"/></span>
        </template>
      </el-table-column>
<!--      <el-table-column-->
<!--        fixed="right"-->
<!--        header-align="center"-->
<!--        align="center"-->
<!--        width="100"-->
<!--        label="操作">-->
<!--        <template slot-scope="scope">-->
<!--          <a @click="initModel(scope.row)" type="text" >编辑</a>-->
<!--&lt;!&ndash;          <a @click="delHeaderData(scope.row)" type="text" >删除</a>&ndash;&gt;-->
<!--        </template>-->
<!--      </el-table-column>-->
    </el-table>

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

    <!-- 新增/编辑dialog - rqrq -->
    <el-dialog :close-on-click-modal="false" :close-on-press-escape="false"
               v-drag :title="inputLabel.headerInput.label5"
               :visible.sync="setUp.reviewFlag" width="900px">
      <el-form :model="saveHeaderData" ref="dataForm"
               label-position="top" style="margin-top: 1px; margin-left: 0px;">
        <!-- 第一行：工厂+托盘ID+托盘尺寸+最大承重 - rqrq -->
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item :label="inputLabel.headerInput.label0" prop="site">
              <el-select v-model="saveHeaderData.site" placeholder="请选择工厂" style="width: 100%;" :disabled="setUp.readonlyFlag" @change="onSiteChange">
                <el-option
                  v-for="item in siteOptions"
                  :key="item.site"
                  :label="item.siteName || item.site"
                  :value="item.site">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item :label="inputLabel.headerInput.label1" prop="palletId">
              <el-input v-model="saveHeaderData.palletId" readonly placeholder="系统自动生成"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="托盘尺寸">
              <el-input v-model="saveHeaderData.palletSize" placeholder="如: 1200x1000"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="最大承重(kg)">
              <el-input v-model="saveHeaderData.maxLoad" placeholder="请输入最大承重"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 第二行：托盘大分类+托盘类型+分拣方式+自动分拣 - rqrq -->
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="托盘大分类" prop="palletFamily">
              <el-select v-model="saveHeaderData.palletFamily" placeholder="请选择" style="width: 100%;" @change="onPalletFamilyChange">
                <el-option
                  v-for="item in palletFamilyOptions"
                  :key="item.palletFamily"
                  :label="item.palletFamilyDesc || item.palletFamily"
                  :value="item.palletFamily">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="托盘类型" prop="palletType">
              <el-select v-model="saveHeaderData.palletType" placeholder="请先选择托盘大分类" style="width: 100%;" @change="onPalletTypeChange">
                <el-option
                  v-for="item in palletTypeOptions"
                  :key="item.palletType"
                  :label="item.typeDesc || item.palletType"
                  :value="item.palletType">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="分拣方式">
              <el-select v-model="saveHeaderData.soreType" placeholder="自动带出" style="width: 100%;">
                <el-option label="人工/混装" :value="0"></el-option>
                <el-option label="气胀轴自动分拣" :value="1"></el-option>
                <el-option label="抱箱自动分拣" :value="2"></el-option>
                <el-option label="直接出库" :value="3"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="自动分拣">
              <el-select v-model="saveHeaderData.autoSort" placeholder="自动带出" style="width: 100%;">
                <el-option label="是" value="Y"></el-option>
                <el-option label="否" value="N"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 第三行：状态+库位编码+WCS库位+空栈板标记 - rqrq -->
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item :label="inputLabel.headerInput.label3" prop="status">
              <el-select v-model="saveHeaderData.status" placeholder="请选择" style="width: 100%;">
                <el-option
                  v-for="item in statusOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="站点">
              <el-input v-model="saveHeaderData.locationCode" disabled placeholder="请输入站点编码"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="WCS站点">
              <el-input v-model="saveHeaderData.wcsLocation" disabled placeholder="请输入WCS站点"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="空栈板标记">
              <el-input v-model="saveHeaderData.emptyFlag" readonly placeholder="默认为N" style="background-color: #f5f7fa;"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 第四行：调用标志 - rqrq -->
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="调用标志">
              <el-select v-model="saveHeaderData.callingFlag" placeholder="请选择" disabled style="width: 100%;">
                <el-option label="是" value="Y"></el-option>
                <el-option label="否" value="N"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 备注占全行 - rqrq -->
        <el-row>
          <el-col :span="24">
            <el-form-item label="最近一次调用备注">
              <el-input v-model="saveHeaderData.remark" 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" :disabled="setUp.saveButton" @click="saveHeaderFunction()">
          {{ setUp.saveButton ? '保存中...' : '确定' }}
        </el-button>
        <el-button @click="setUp.reviewFlag = false" :disabled="setUp.saveButton">取消</el-button>
      </div>
    </el-dialog>

    <!-- 批量新增托盘弹窗 - rqrq -->
    <el-dialog :close-on-click-modal="false" :close-on-press-escape="false"
               v-drag :title="'批量新增托盘 - 工厂: ' + batchGenerateDialog.site"
               :visible.sync="batchGenerateDialog.visible" width="480px">

      <div v-loading="batchGenerateDialog.loading">
        <!-- 表头行 - rqrq -->
        <div style="display: flex; align-items: center; padding: 10px 0; margin-bottom: 5px; border-bottom: 1px solid #ebeef5; color: #606266; font-weight: bold;">
          <span style="flex: 1;">托盘类型</span>
          <span style="width: 100px; text-align: center;">当前数量</span>
          <span style="width: 140px; text-align: center;">需要新增</span>
        </div>

        <!-- 托盘列表 - rqrq -->
        <div v-for="(item, index) in batchGenerateDialog.palletNoList" :key="index"
             style="display: flex; align-items: center; padding: 12px 0; border-bottom: 1px dashed #ebeef5;">
          <span style="flex: 1; font-size: 14px; color: #303133;">
            {{ item.palletFamilyDesc }}
            <span style="color: #909399;">({{ item.prefix }})</span>
          </span>
          <span style="width: 100px; text-align: center; font-size: 15px; color: #409EFF; font-weight: bold;">
            {{ item.totalCount || 0 }}
          </span>
          <div style="width: 140px; text-align: center;">
            <el-input
              v-model.number="item.generateCount"
              placeholder="0"
              size="small"
              style="width: 100px;"
              @input="validateCount(item)">
            </el-input>
          </div>
        </div>

        <!-- 提示信息 - rqrq -->
        <div style="margin-top: 15px; color: #909399; font-size: 12px;">
          <i class="el-icon-info"></i> 单次每种类型最多新增1000个
        </div>
      </div>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" :disabled="batchGenerateDialog.saving" @click="doBatchGenerate()">
          {{ batchGenerateDialog.saving ? '生成中...' : '确定' }}
        </el-button>
        <el-button @click="batchGenerateDialog.visible = false" :disabled="batchGenerateDialog.saving">取消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import {
  userFavoriteList,
  saveUserFavorite,
  removeUserFavorite,
} from '@/api/userFavorite.js'
import {
  getPalletList,
  savePallet,
  updatePallet,
  deletePallet,
  checkPalletId,
  getPalletStatusOptions,
  getUserAuthorizedSites,
  getPalletFamilyList,
  getPalletTypeList,
  getMaxPalletNoByFamily,
  batchGeneratePallet
} from '@/api/warehouse/pallet.js'

export default {
  data() {
    return {
      saveHeaderData: {
        id: null,
        site: '',
        palletId: '',
        palletType: '',
        palletSize: '',
        maxLoad: null,
        status: 'AVAILABLE',
        locationCode: '',
        wcsLocation: '',  // WCS库位 - rqrq
        palletFamily: '',  // 托盘大分类 - rqrq
        soreType: 0,  // 分拣方式 - rqrq
        autoSort: 'N',  // 自动分拣，默认N - rqrq
        emptyFlag: 'N',  // 空栈板标记，默认N且不可修改 - rqrq
        callingFlag: 'N',  // 调用标志，默认N - rqrq
        remark: '',
        createdBy: this.$store.state.user.name,
        updatedBy: this.$store.state.user.name
      },
      queryHeaderData: {
        site: '',
        palletId: '',
        palletType: '',
        palletFamily: '',
        status: '',
        locationCode: '',
        page: 1,
        limit: 20
      },
      setUp: {
        reviewFlag: false,
        saveButton: false,
        readonlyFlag: false,
      },
      inputLabel: {
        headerInput: {
          label0: '工厂',
          label1: '托盘ID',
          label2: '托盘大分类',
          label3: '托盘状态',
          label4: '所在站点',
          label5: '托盘信息',
        },
      },
      statusOptions: [],
      siteOptions: [],
      palletFamilyOptions: [],  // 托盘大分类选项 - rqrq
      palletTypeOptions: [],  // 托盘类型选项 - rqrq
      selectedPalletTypeData: null,  // 选中的托盘类型完整数据 - rqrq
      // table高度
      height: 450,
      // 是否收藏
      favorite: false,
      functionId: this.$route.meta.menuId,
      // 展示列集 - rqrq
      columnList: [
        {
          columnProp: "site",
          headerAlign: "center",
          align: "center",
          columnLabel: "工厂",
          columnWidth: 50,
        },
        {
          columnProp: "palletId",
          headerAlign: "center",
          align: "center",
          columnLabel: "托盘ID",
          columnWidth: 100,
        },
        {
          columnProp: "palletFamilyDesc",
          headerAlign: "center",
          align: "center",
          columnLabel: "托盘大分类",
          columnWidth: 150,
        },
        {
          columnProp: "typeDesc",
          headerAlign: "center",
          align: "center",
          columnLabel: "托盘类型",
          columnWidth: 180,
        },
        {
          columnProp: "soreTypeText",
          headerAlign: "center",
          align: "center",
          columnLabel: "分拣方式",
          columnWidth: 120,
        },
        {
          columnProp: "autoSortText",
          headerAlign: "center",
          align: "center",
          columnLabel: "自动分拣",
          columnWidth: 80,
        },
        {
          columnProp: "callingFlagText",
          headerAlign: "center",
          align: "center",
          columnLabel: "调用标志",
          columnWidth: 80,
        },
        {
          columnProp: "remark",
          headerAlign: "center",
          align: "left",
          columnLabel: "最近一次调用备注",
          columnWidth: 150,
        },
        {
          columnProp: "locationCode",
          headerAlign: "center",
          align: "center",
          columnLabel: "所在站点",
          columnWidth: 80,
        },
        {
          columnProp: "wcsLocation",
          headerAlign: "center",
          align: "center",
          columnLabel: "WCS库位",
          columnWidth: 80,
        },
        {
          columnProp: "emptyFlagText",
          headerAlign: "center",
          align: "center",
          columnLabel: "空栈板标记",
          columnWidth: 80,
        },
        {
          columnProp: "statusText",
          headerAlign: "center",
          align: "center",
          columnLabel: "托盘状态",
          columnWidth: 80,
        },
        {
          columnProp: "createdBy",
          headerAlign: "center",
          align: "center",
          columnLabel: "创建人",
          columnWidth: 100,
        },
        {
          columnProp: "createdTime",
          headerAlign: "center",
          align: "center",
          columnLabel: "创建时间",
          columnWidth: 150,
        },
        {
          columnProp: "updatedBy",
          headerAlign: "center",
          align: "center",
          columnLabel: "修改人",
          columnWidth: 100,
        },
        {
          columnProp: "updatedTime",
          headerAlign: "center",
          align: "center",
          columnLabel: "修改时间",
          columnWidth: 150,
        },
        {
          columnProp: "palletSize",
          headerAlign: "center",
          align: "center",
          columnLabel: "托盘尺寸",
          columnWidth: 120,
        },
        {
          columnProp: "maxLoad",
          headerAlign: "center",
          align: "center",
          columnLabel: "最大承重(kg)",
          columnWidth: 120,
        },
      ],
      // 数据集
      dataList: [],
      buttons: {
        deleteList: '批量删除',
      },
      // 分页
      pageIndex: 1,
      pageSize: 20,
      totalPage: 0,
      dataListLoading: false,
      dataListSelections: [],
      // 导出相关 - rqrq
      exportData: [],
      exportName: '托盘信息' + this.dayjs().format('YYYYMMDDHHmmss'),
      exportHeader: ["托盘信息"],
      exportFooter: [],
      // 验证规则
      dataRule: {
        site: [
          { required: true, message: '工厂不能为空', trigger: 'change' }
        ],
        palletType: [
          { required: true, message: '托盘类型不能为空', trigger: 'change' }
        ],
        status: [
          { required: true, message: '托盘状态不能为空', trigger: 'change' }
        ]
      },
      // 批量新增弹窗状态 - rqrq
      batchGenerateDialog: {
        visible: false,
        loading: false,
        saving: false,
        site: '',
        palletNoList: []  // 各类托盘编号信息列表
      }
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.height = window.innerHeight - 220;
    })
  },
  activated() {
    this.getDataList()
    this.getStatusOptions()
    this.getSiteOptions()
  },
  methods: {
    // 获取状态选项
    getStatusOptions() {
      getPalletStatusOptions().then(({data}) => {
        if (data && data.code === 0) {
          this.statusOptions = data.options
        }
      })
    },
    // 获取工厂选项
    getSiteOptions() {
      const params = {
        userName: this.$store.state.user.name
      }
      getUserAuthorizedSites(params).then(({data}) => {
        if (data && data.code === 0) {
          this.siteOptions = data.data
        }
      }).catch(error => {
        console.error('获取工厂列表失败:', error)
      })
    },
    // 删除托盘
    delHeaderData(row) {
      this.$confirm(`确定删除托盘 [${row.palletId}]?`, '操作提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deletePallet([row.id]).then(({data}) => {
          if (data.code == 0) {
            this.$message.success(data.msg)
            this.getDataList()
          } else {
            this.$alert(data.msg, '操作提示', {
              confirmButtonText: '确定'
            });
          }
        })
      })
    },
    // 保存托盘
    saveHeaderFunction() {
      this.$refs.dataForm.validate((valid) => {
        if (valid) {
          this.setUp.saveButton = true

          // 准备提交数据
          let submitData = { ...this.saveHeaderData }

          // 如果是新增，清空托盘ID让后端自动生成
          if (!submitData.id) {
            submitData.palletId = ''
          }

          const apiMethod = submitData.id ? updatePallet : savePallet

          apiMethod(submitData).then(({data}) => {
            this.setUp.saveButton = false
            if (data.code == 0) {
              this.$message.success(data.msg)
              this.getDataList()
              this.setUp.reviewFlag = false
            } else {
              this.$alert(data.msg, '操作提示', {
                confirmButtonText: '确定'
              });
            }
          }).catch(() => {
            this.setUp.saveButton = false
          })
        }
      })
    },
    // 初始化表单 - rqrq
    initModel(row) {
      this.setUp.reviewFlag = true
      this.setUp.saveButton = false
      this.setUp.readonlyFlag = false

      if (row) {
        // 编辑模式 - rqrq
        this.setUp.readonlyFlag = true
        this.saveHeaderData = {
          id: row.id,
          site: row.site,
          palletId: row.palletId,
          palletType: row.palletType,
          palletSize: row.palletSize,
          maxLoad: row.maxLoad,
          status: row.status,
          locationCode: row.locationCode,
          wcsLocation: row.wcsLocation || '',  // WCS库位 - rqrq
          palletFamily: row.palletFamily || '',  // 托盘大分类 - rqrq
          soreType: row.soreType != null ? row.soreType : 0,  // 分拣方式 - rqrq
          autoSort: row.autoSort || 'N',  // 自动分拣 - rqrq
          emptyFlag: row.emptyFlag || 'N',  // 空栈板标记（只读） - rqrq
          callingFlag: row.callingFlag || 'N',  // 调用标志 - rqrq
          remark: row.remark || '',
          updatedBy: this.$store.state.user.name
        }

        // 编辑时加载托盘大分类和类型选项 - rqrq
        if (row.site) {
          this.getPalletFamilyOptions(row.site)
          if (row.palletFamily) {
            this.getPalletTypeOptions(row.site, row.palletFamily)
          }
        }
      } else {
        // 新增模式 - rqrq
        this.saveHeaderData = {
          id: null,
          site: '',
          palletId: '系统自动生成',
          palletType: '',
          palletSize: '',
          maxLoad: null,
          status: 'AVAILABLE',
          locationCode: '',
          wcsLocation: '',  // WCS库位 - rqrq
          palletFamily: '',  // 托盘大分类 - rqrq
          soreType: 0,  // 分拣方式 - rqrq
          autoSort: 'N',  // 自动分拣，默认N - rqrq
          emptyFlag: 'N',  // 空栈板标记，默认N且不可修改 - rqrq
          callingFlag: 'N',  // 调用标志，默认N - rqrq
          remark: '',
          createdBy: this.$store.state.user.name
        }
      }
    },
    // 工厂change事件 - rqrq
    onSiteChange(value) {
      console.log('工厂变更 - rqrq：', value)

      // 清空托盘相关字段 - rqrq
      this.saveHeaderData.palletFamily = ''
      this.saveHeaderData.palletType = ''
      this.saveHeaderData.soreType = 0
      this.saveHeaderData.autoSort = 'N'
      this.palletFamilyOptions = []
      this.palletTypeOptions = []
      this.selectedPalletTypeData = null

      // 加载新工厂的托盘大分类 - rqrq
      if (value) {
        this.getPalletFamilyOptions(value)
      }
    },
    // 获取托盘大分类选项 - rqrq
    getPalletFamilyOptions(site) {
      if (!site) {
        this.palletFamilyOptions = []
        return
      }

      getPalletFamilyList({ site }).then(({data}) => {
        if (data && data.code === 0) {
          this.palletFamilyOptions = data.rows || []
        }
      }).catch(() => {
        this.palletFamilyOptions = []
      })
    },
    // 获取托盘类型选项 - rqrq
    getPalletTypeOptions(site, palletFamily) {
      if (!site) {
        this.palletTypeOptions = []
        return
      }

      const params = { site }
      if (palletFamily) {
        params.palletFamily = palletFamily
      }

      getPalletTypeList(params).then(({data}) => {
        if (data && data.code === 0) {
          this.palletTypeOptions = data.rows || []
        }
      }).catch(() => {
        this.palletTypeOptions = []
      })
    },
    // 托盘大分类change事件 - rqrq
    onPalletFamilyChange(value) {
      console.log('托盘大分类变更 - rqrq：', value)

      // 清空托盘类型相关字段 - rqrq
      this.saveHeaderData.palletType = ''
      this.saveHeaderData.soreType = 0
      this.saveHeaderData.autoSort = 'N'
      this.selectedPalletTypeData = null

      // 重新加载托盘类型列表 - rqrq
      if (value && this.saveHeaderData.site) {
        this.getPalletTypeOptions(this.saveHeaderData.site, value)
      } else {
        this.palletTypeOptions = []
      }
    },
    // 托盘类型change事件 - 参考palletAssembly.vue逻辑 - rqrq
    onPalletTypeChange(value) {
      console.log('托盘类型变更 - rqrq：', value)

      // 查找选中的托盘类型完整数据 - rqrq
      const selectedType = this.palletTypeOptions.find(item => item.palletType === value)

      if (selectedType) {
        this.selectedPalletTypeData = selectedType

        // 根据托盘类型自动带出字段 - rqrq
        this.saveHeaderData.soreType = selectedType.wcsSoreType != null ? selectedType.wcsSoreType : 0
        this.saveHeaderData.autoSort = selectedType.wcsAutoSort || 'N'

        console.log('自动带出分拣方式 - rqrq：', this.saveHeaderData.soreType)
        console.log('自动带出自动分拣 - rqrq：', this.saveHeaderData.autoSort)
      } else {
        // 未找到数据，重置为默认值 - rqrq
        this.saveHeaderData.soreType = 0
        this.saveHeaderData.autoSort = 'N'
        this.selectedPalletTypeData = null
      }
    },
    // 收藏功能
    favoriteFunction() {
      let userFavorite = {
        userId: this.$store.state.user.id,
        functionId: this.$route.meta.menuId,
      }
      if (this.favorite) {
        this.$confirm(`确定取消收藏`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          removeUserFavorite(userFavorite).then(({data}) => {
            this.$message.success(data.msg)
            this.favorite = false
          })
        })
      } else {
        saveUserFavorite(userFavorite).then(({data}) => {
          this.$message.success(data.msg)
          this.favorite = true
        })
      }
    },
    // 获取数据列表 - rqrq
    getDataList() {
      this.dataListLoading = true
      this.queryHeaderData.page = this.pageIndex
      this.queryHeaderData.limit = this.pageSize

      getPalletList(this.queryHeaderData).then(({data}) => {
        if (data && data.code === 0) {
          // 处理数据，添加文本显示字段 - rqrq
          this.dataList = (data.page.list || []).map(item => {
            return {
              ...item,
              // 分拣方式文本显示 - rqrq
              soreTypeText: this.getSoreTypeText(item.soreType),
              // 自动分拣文本显示 - rqrq
              autoSortText: item.autoSort === 'Y' ? '是' : item.autoSort === 'N' ? '否' : '',
              // 空栈板标记文本显示 - rqrq
              emptyFlagText: item.emptyFlag === 'Y' ? '是' : item.emptyFlag === 'N' ? '否' : '',
              // 调用标志文本显示 - rqrq
              callingFlagText: item.callingFlag === 'Y' ? '是' : item.callingFlag === 'N' ? '否' : '',
              // 状态文本显示 - rqrq
              statusText: this.getStatusText(item.status)
            }
          })
          this.totalPage = data.page.totalCount
        } else {
          this.dataList = []
          this.totalPage = 0
        }
        this.dataListLoading = false
      })
    },
    // 获取分拣方式文本 - rqrq
    getSoreTypeText(soreType) {
      const soreTypeMap = {
        0: '人工/混装',
        1: '气胀轴自动分拣',
        2: '抱箱自动分拣',
        3: '直接出库'
      }
      return soreTypeMap[soreType] !== undefined ? soreTypeMap[soreType] : ''
    },
    // 获取状态文本 - rqrq
    getStatusText(status) {
      const statusMap = {
        'AVAILABLE': '可用',
        'OCCUPIED': '使用中',
        'DAMAGED': '损坏',
        'DISABLED': '禁用'
      }
      return statusMap[status] || status
    },
    // 每页数
    sizeChangeHandle(val) {
      this.pageSize = val
      this.pageIndex = 1
      this.getDataList()
    },
    // 当前页
    currentChangeHandle(val) {
      this.pageIndex = val
      this.getDataList()
    },
    // 多选
    selectionChangeHandle(val) {
      this.dataListSelections = val
    },
    // 批量删除
    deleteHandle() {
      var ids = this.dataListSelections.map(item => {
        return item.id
      })
      this.$confirm(`确定批量删除选中的托盘?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deletePallet(ids).then(({data}) => {
          if (data && data.code === 0) {
            this.$message.success('操作成功')
            this.getDataList()
          } else {
            this.$alert(data.msg, '错误', { confirmButtonText: '确定' })
          }
        })
      })
    },
    // 导出相关方法 - rqrq
    async createExportData() {
      const queryParams = {
        ...this.queryHeaderData,
        page: 1,
        limit: 999999  // 设置一个很大的数字来获取全部数据 - rqrq
      }
      const {data} = await getPalletList(queryParams)
      if (data && data.code === 0) {
        return (data.page.list || []).map(item => {
          return {
            ...item,
            soreTypeText: this.getSoreTypeText(item.soreType),
            autoSortText: item.autoSort === 'Y' ? '是' : item.autoSort === 'N' ? '否' : '',
            emptyFlagText: item.emptyFlag === 'Y' ? '是' : item.emptyFlag === 'N' ? '否' : '',
            callingFlagText: item.callingFlag === 'Y' ? '是' : item.callingFlag === 'N' ? '否' : '',
            statusText: this.getStatusText(item.status)
          }
        })
      }
      return []
    },
    startDownload() {
      // 开始导出 - rqrq
    },
    finishDownload() {
      // 导出完成 - rqrq
    },
    fields() {
      let json = "{"
      this.columnList.forEach((item, index) => {
        if (index == this.columnList.length - 1) {
          json += "\"" + item.columnLabel + "\"" + ":" + "\"" + item.columnProp + "\""
        } else {
          json += "\"" + item.columnLabel + "\"" + ":" + "\"" + item.columnProp + "\"" + ","
        }
      })
      json += "}"
      let s = eval("(" + json + ")")
      return s
    },
    // 打开批量新增弹窗 - rqrq
    openBatchGenerateDialog() {
      // 从store获取当前工厂 - rqrq
      this.batchGenerateDialog.site = this.$store.state.user.site
      this.batchGenerateDialog.palletNoList = []
      this.batchGenerateDialog.saving = false
      this.batchGenerateDialog.visible = true
      // 自动查询托盘数量 - rqrq
      this.loadPalletMaxNos()
    },
    // 加载托盘最大编号数据 - rqrq
    loadPalletMaxNos() {
      this.batchGenerateDialog.loading = true
      getMaxPalletNoByFamily({ site: this.batchGenerateDialog.site }).then(({data}) => {
        this.batchGenerateDialog.loading = false
        if (data && data.code === 0) {
          this.batchGenerateDialog.palletNoList = (data.rows || []).map(item => ({
            ...item,
            generateCount: null
          }))
        } else {
          this.$alert(data.msg || '获取托盘编号信息失败', '错误', { confirmButtonText: '确定' })
          this.batchGenerateDialog.palletNoList = []
        }
      }).catch(() => {
        this.batchGenerateDialog.loading = false
        this.$alert('获取托盘编号信息失败', '错误', { confirmButtonText: '确定' })
        this.batchGenerateDialog.palletNoList = []
      })
    },
    // 校验新增数量 - rqrq
    validateCount(item) {
      if (item.generateCount !== null && item.generateCount !== '') {
        let val = parseInt(item.generateCount)
        if (isNaN(val) || val < 0) {
          item.generateCount = null
        } else if (val > 1000) {
          item.generateCount = 1000
          this.$message.warning('单次最多新增1000个')
        } else {
          item.generateCount = val
        }
      }
    },
    // 执行批量生成 - rqrq
    doBatchGenerate() {
      // 1. 校验工厂 - rqrq
      if (!this.batchGenerateDialog.site) {
        this.$message.warning('请先选择工厂')
        return
      }

      // 2. 校验是否有需要生成的数量 - rqrq
      const generateItems = this.batchGenerateDialog.palletNoList.filter(item =>
        item.generateCount !== null && item.generateCount !== '' && parseInt(item.generateCount) > 0
      )
      if (generateItems.length === 0) {
        this.$message.warning('请至少输入一种托盘的新增数量')
        return
      }

      // 3. 校验数量不超过1000 - rqrq
      for (let item of generateItems) {
        if (parseInt(item.generateCount) > 1000) {
          this.$alert(`${item.palletFamilyDesc}新增数量不能超过1000`, '错误', { confirmButtonText: '确定' })
          return
        }
      }

      // 4. 确认提示 - rqrq
      let confirmMsg = '确定要生成以下托盘吗？\n\n'
      generateItems.forEach(item => {
        confirmMsg += `${item.palletFamilyDesc}(${item.prefix}): ${item.generateCount}个\n`
      })

      this.$confirm(confirmMsg, '确认批量生成', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.executeBatchGenerate(generateItems)
      }).catch(() => {})
    },
    // 执行批量生成请求 - rqrq
    async executeBatchGenerate(generateItems) {
      this.batchGenerateDialog.saving = true

      let successCount = 0
      let failedCount = 0
      let resultMsg = ''

      // 依次生成每种类型的托盘 - rqrq
      for (let item of generateItems) {
        try {
          const { data } = await batchGeneratePallet({
            site: this.batchGenerateDialog.site,
            palletFamily: item.palletFamily,
            count: item.generateCount,
            username: this.$store.state.user.name
          })

          if (data && data.code === 0) {
            successCount++
            resultMsg += `✓ ${item.palletFamilyDesc}: 生成${data.count}个 (${data.startPalletId} ~ ${data.endPalletId})\n`
          } else {
            failedCount++
            resultMsg += `✗ ${item.palletFamilyDesc}: ${data.msg || '生成失败'}\n`
          }
        } catch (e) {
          failedCount++
          resultMsg += `✗ ${item.palletFamilyDesc}: 请求异常\n`
        }
      }

      this.batchGenerateDialog.saving = false

      // 显示结果 - rqrq
      if (failedCount === 0) {
        this.$alert(resultMsg, '生成成功', {
          confirmButtonText: '确定',
          type: 'success',
          callback: () => {
            this.batchGenerateDialog.visible = false
            this.getDataList()
          }
        })
      } else {
        this.$alert(resultMsg, `生成结果（成功${successCount}，失败${failedCount}）`, {
          confirmButtonText: '确定',
          type: failedCount === generateItems.length ? 'error' : 'warning',
          callback: () => {
            // 刷新编号信息 - rqrq
            this.onBatchSiteChange(this.batchGenerateDialog.site)
            this.getDataList()
          }
        })
      }
    }
  },
  created() {
    // 初始化收藏状态
    this.favorite = false
  }
}
</script>

<style scoped>
.sl-svg {
  overflow: hidden;
  float: right;
}
</style>
