<template>
  <div>
    <el-card :body-style="cardBodyStyle">
      <el-form :model="query" label-width="90" label-position="right">
        <el-row :gutter="24">
          <el-col :span="6">
            <el-form-item label="库房名称">
              <el-select
                v-model="query.wareId"
                clearable
                filterable
                placeholder="请选择库房"
                style="width: 100%;"
                @visible-change="handleWareVisible"
              >
                <el-option
                  v-for="item in wareOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="垛位名称">
              <el-input v-model="query.stackName" clearable placeholder="请输入垛位名称" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="品名">
              <el-input v-model="query.materialName" clearable placeholder="请输入品名" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="钢种">
              <el-input v-model="query.stGrade" clearable placeholder="请输入钢种" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="24">
          <el-col :span="6">
            <el-form-item label="规格型号">
              <el-input v-model="query.attrib_03" clearable placeholder="请输入规格型号" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="捆包号">
              <el-input v-model="query.bundleNo" clearable placeholder="请输入捆包号" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="材料号">
              <el-input v-model="query.prodNo" clearable placeholder="请输入材料号" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="订单号">
              <el-input v-model="query.attrib_01" clearable placeholder="请输入订单号" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="24">
          <el-col :span="6">
            <el-form-item label="合约号">
              <el-input v-model="query.attrib_02" clearable placeholder="请输入合约号" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="捆绑号">
              <el-input v-model="query.attrib_04" clearable placeholder="请输入捆绑号" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="货权单位">
              <el-select
                  v-model="query.ownerCompany"
                  clearable
                  filterable
                  placeholder="请选择货权单位"
                  style="width: 100%;"
                  @visible-change="handleOwnerVisible"
              >
                <el-option
                    v-for="item in ownerCompanyOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="客户名称">
              <el-select
                  v-model="query.customerCompany"
                  clearable
                  filterable
                  placeholder="请选择客户名称"
                  style="width: 100%;"
                  @visible-change="handleCustomerVisible"
              >
                <el-option
                    v-for="item in customerCompanyOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

<!--        <el-row :gutter="10">-->

<!--&lt;!&ndash;          <el-col :span="6">&ndash;&gt;-->
<!--&lt;!&ndash;            <el-form-item label="出库车号">&ndash;&gt;-->
<!--&lt;!&ndash;              <el-input v-model="query.outTruckNo" clearable placeholder="请输入出库车号" />&ndash;&gt;-->
<!--&lt;!&ndash;            </el-form-item>&ndash;&gt;-->
<!--&lt;!&ndash;          </el-col>&ndash;&gt;-->
<!--        </el-row>-->

        <el-row :gutter="24">
          <el-col :span="8">
            <el-form-item label="入库时间">
              <el-date-picker
                v-model="query.outDtmRange"
                type="datetimerange"
                range-separator="至"
                start-placeholder="开始时间"
                end-placeholder="结束时间"
                :default-time="defaultRangeTime"
                style="width: 100%;"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <el-row :gutter="24">
        <el-col >
            <el-button type="primary" @click="handleSearch">查询</el-button>
            <el-button @click="handleReset">重置</el-button>
            <el-button type="primary" @click="handleTransferOwnership">货权转移</el-button>
            <el-button type="primary" @click="handleAllocate">配货</el-button>
            <el-button type="primary" @click="handleOutStock">出库</el-button>
            <el-button type="success" @click="handleExport">导出</el-button>

            <el-dropdown style="margin-left: 1%" @command="handleOtherCommand">
              <el-button>
                其他操作
                <i class="el-icon-arrow-down el-icon--right" />
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item command="cancelIn">取消入库</el-dropdown-item>
                  <!--                    <el-dropdown-item command="batchEdit">批量修改</el-dropdown-item>-->
                  <el-dropdown-item command="batchMove">批量倒垛</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>

            <el-dropdown style="margin-left: 1%" @command="handleLockCommand">
              <el-button type="danger">
                封锁出仓
                <i class="el-icon-arrow-down el-icon--right" />
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item command="lock">封锁</el-dropdown-item>
                  <el-dropdown-item command="unlock">取消封锁</el-dropdown-item>
                  <el-dropdown-item command="inStock">入仓</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
        </el-col>
      </el-row>
    </el-card>

    <el-card :body-style="cardBodyStyle" class="summary-card">
      <el-row :gutter="20">
        <el-col :span="6">
          <div class="summary-item">
            <span class="summary-label">数量统计：</span>
            <span class="summary-value">{{ statistics.totalQuantity ?? '-' }}</span>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="summary-item">
            <span class="summary-label">重量统计：</span>
            <span class="summary-value">{{ statistics.totalWeight ?? '-' }}</span>
          </div>
        </el-col>
      </el-row>
    </el-card>

    <el-card :body-style="cardBodyStyle">
      <el-table
        ref="tableRef"
        v-loading="tableLoading"
        :data="tableData"
        border
        highlight-current-row
        @selection-change="handleSelectionChange"
      >
        <el-table-column
            type="selection"
            width="55"
            header-align="center"
            align="center"
            fixed="left"
        />
        <el-table-column
          label="操作"
          width="100"
          header-align="center"
          align="center"
          fixed="left"
        >
          <template #default="{ row }">
            <el-button type="text" size="small" @click="handleEdit(row)">编辑</el-button>
          </template>
        </el-table-column>

        <el-table-column label="仓库名称" min-width="140" header-align="center" align="center">
          <template #default="{ row }">
            {{ row.outWareName ?? row.wareName ?? '-' }}
          </template>
        </el-table-column>
        <el-table-column label="垛位名称" min-width="140" header-align="center" align="center">
          <template #default="{ row }">
            {{ row.outStackName ?? row.stackName ?? '-' }}
          </template>
        </el-table-column>
        <el-table-column label="层号" width="100" header-align="center" align="center">
          <template #default="{ row }">
            {{ row.outLayerNo ?? row.layerNo ?? '-' }}
          </template>
        </el-table-column>
        <el-table-column label="物料名称" min-width="160" header-align="center" align="center">
          <template #default="{ row }">
            {{ row.materialName ?? '-' }}
          </template>
        </el-table-column>
        <el-table-column label="钢种" width="140" header-align="center" align="center">
          <template #default="{ row }">
            {{ row.ST_GRADE ?? row.stGrade ?? '-' }}
          </template>
        </el-table-column>
        <el-table-column label="规格型号" min-width="160" header-align="center" align="center" show-overflow-tooltip>
          <template #default="{ row }">
            {{ row.attrib03 ?? row.materialStandard ?? '-' }}
          </template>
        </el-table-column>
        <el-table-column prop="inDtm" label="入库时间" min-width="180" header-align="center" align="center" show-overflow-tooltip />
        <el-table-column prop="ownerCompany" label="货权公司" min-width="160" header-align="center" align="center" show-overflow-tooltip />
        <el-table-column prop="receivingCompany" label="收货公司" min-width="160" header-align="center" align="center" show-overflow-tooltip />
        <el-table-column label="最终客户公司" min-width="180" header-align="center" align="center" show-overflow-tooltip>
          <template #default="{ row }">
            {{ row.customerCompany ?? row.CustomerCompany ?? '-' }}
          </template>
        </el-table-column>
        <el-table-column prop="prodNo" label="材料号" min-width="140" header-align="center" align="center" show-overflow-tooltip />
        <el-table-column label="入库车号" min-width="140" header-align="center" align="center" show-overflow-tooltip>
          <template #default="{ row }">
            {{ row.inTruckNo ?? row.carNo ?? '-' }}
          </template>
        </el-table-column>
        <el-table-column prop="attrib01" label="订单号" min-width="160" header-align="center" align="center" show-overflow-tooltip />
        <el-table-column prop="attrib02" label="合约号" min-width="160" header-align="center" align="center" show-overflow-tooltip />
        <el-table-column prop="attrib04" label="捆包号" min-width="160" header-align="center" align="center" show-overflow-tooltip />
        <el-table-column prop="attrib05" label="产地" min-width="160" header-align="center" align="center" show-overflow-tooltip />
        <el-table-column label="重量" min-width="140" header-align="center" align="right" show-overflow-tooltip>
          <template #default="{ row }">
            {{ row.weight ?? row.WEIGHT ?? '-' }}
          </template>
        </el-table-column>
        <el-table-column label="数量" min-width="140" header-align="center" align="right" show-overflow-tooltip>
          <template #default="{ row }">
            {{ row.quantity ?? row.QUANTITY ?? '-' }}
          </template>
        </el-table-column>
<!--        <el-table-column label="出库标记" width="140" header-align="center" align="center">-->
<!--          <template #default="{ row }">-->
<!--            <el-tag :type="flagTagType(row.outFlag)" effect="plain">-->
<!--              {{ flagLabel(row.outFlag) }}-->
<!--            </el-tag>-->
<!--          </template>-->
<!--        </el-table-column>-->
        <el-table-column prop="deliveryAddress" label="收货地址" min-width="200" header-align="center" align="center" show-overflow-tooltip />
<!--        <el-table-column prop="outDtm" label="出库时间" min-width="180" header-align="center" align="center" show-overflow-tooltip />-->
        <el-table-column prop="remark1" label="备注" min-width="160" header-align="center" align="center" show-overflow-tooltip />
      </el-table>
    </el-card>

    <el-card :body-style="cardBodyStyle">
      <el-pagination
        :current-page="currentPage"
        :page-size="pageSize"
        :page-sizes="pageSizes"
        :total="totalRows"
        background="background"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-card>

    <!-- 编辑弹窗 -->
    <PopupEdit ref="popupEditRef" @success="handleEditSuccess" />

    <!-- 配货弹窗 -->
    <PopupDistribution ref="popupDistributionRef" @success="handleDistributionSuccess" />

    <!-- 出库弹窗 -->
    <PopupOutStock ref="popupOutStockRef" @success="handleOutStockSuccess" />

    <!-- 批量修改弹窗 -->
    <PopupBatchEdit ref="popupBatchEditRef" @success="handleBatchEditSuccess" />

    <!-- 批量倒垛弹窗 -->
    <PopupBatchMove ref="popupBatchMoveRef" @success="handleBatchMoveSuccess" />

    <!-- 货权转移弹窗 -->
    <PopupTransferOwnership ref="popupTransferOwnershipRef" @success="handleTransferOwnershipSuccess" />
  </div>
</template>

<script setup>
import {getCurrentInstance, onMounted, reactive, ref} from 'vue'
import {ElMessage, ElMessageBox} from 'element-plus'
import tools from '@/tools'
import PopupDistribution from '../components/PopupDistribution.vue'
import PopupOutStock from '../components/PopupOutStock.vue'
import PopupBatchEdit from '../components/PopupBatchEdit.vue'
import PopupBatchMove from '../components/PopupBatchMove.vue'
import PopupTransferOwnership from '../components/PopupTransferOwnership.vue'
import PopupEdit from '../components/PopupEdit.vue'
import axios from "axios";

const {proxy} = getCurrentInstance()

const cardBodyStyle = ref(tools.style.card)
const tableLoading = ref(false)
const tableData = ref([])
const currentPage = ref(1)
const totalRows = ref(0)
const pageSizes = ref([10, 20, 50, 100])
const pageSize = ref(10)
const tableRef = ref(null)
const popupDistributionRef = ref(null)
const popupOutStockRef = ref(null)
const popupBatchEditRef = ref(null)
const popupBatchMoveRef = ref(null)
const popupTransferOwnershipRef = ref(null)
const popupEditRef = ref(null)
const multipleSelection = ref([])

const listUrl = ref('sto/WareStore/query')
const statisticsUrl = ref('sto//WareStore/statistics')

const wareOptions = ref([])
const ownerCompanyOptions = ref([])
const customerCompanyOptions = ref([])
const statistics = reactive({
  totalQuantity: 0,
  totalWeight: 0
})
const defaultRangeTime = [
  new Date(0, 0, 0, 0, 0, 0),
  new Date(0, 0, 0, 23, 59, 59)
]

const toOptions = (list, labelKey, valueKey) =>
  (list || []).map((item) => {
    if (typeof item === 'string') {
      return {
        label: item,
        value: item
      }
    }
    return {
      label: item?.[labelKey] ?? item?.label ?? item?.name ?? item?.value ?? '',
      value: item?.[valueKey] ?? item?.value ?? item?.id ?? item?.code ?? item?.label ?? ''
    }
  }).filter((item) => item.label !== '' && item.value !== '')

const createDefaultQuery = () => {
  const today = new Date()
  const start = new Date(today.getFullYear(), today.getMonth(), today.getDate())
  const end = new Date(today.getFullYear(), today.getMonth(), today.getDate(), 23, 59, 59, 999)
  return {
    wareId: '',
  stackName: '',
  materialName: '',
    stGrade: '',
  materialStandard: '',
    attrib_03: '',
    bundleNo: '',
    prodNo: '',
    attrib_01: '',
    attrib_02: '',
    attrib_04: '',
    attrib_05: '',
    remark_1: '',
  ownerCompany: '',
    customerCompany: '',
    outTruckNo: '',
    outFlag: '',
    outDtmRange: [start, end]
  }
}
const query = reactive(createDefaultQuery())

const formatDateTime = (value, isEnd = false) => {
  if (!value) return ''
  const date = new Date(value)
  if (Number.isNaN(date.getTime())) return ''
  if (isEnd && date.getHours() === 0 && date.getMinutes() === 0 && date.getSeconds() === 0) {
    date.setHours(23, 59, 59, 999)
  }
  const pad = (num) => String(num).padStart(2, '0')
  const yyyy = date.getFullYear()
  const mm = pad(date.getMonth() + 1)
  const dd = pad(date.getDate())
  const hh = pad(date.getHours())
  const mi = pad(date.getMinutes())
  const ss = pad(date.getSeconds())
  return `${yyyy}-${mm}-${dd} ${hh}:${mi}:${ss}`
}

const buildQueryParams = () => {
  const [startOut, endOut] = query.outDtmRange || []
  return {
    wareId: query.wareId,
    stackName: query.stackName,
    materialName: query.materialName,
    stGrade: query.stGrade,
    materialStandard: query.materialStandard,
    attrib_03: query.attrib_03,
    bundleNo: query.bundleNo,
    prodNo: query.prodNo,
    attrib_01: query.attrib_01,
    attrib_02: query.attrib_02,
    attrib_04: query.attrib_04,
    ownerCompany: query.ownerCompany,
    customerCompany: query.customerCompany,
    outTruckNo: query.outTruckNo,
    outFlag: query.outFlag,
    startDtm: formatDateTime(startOut),
    endDtm: formatDateTime(endOut, true)
  }
}

const getTableData = () => {
  tableLoading.value = true
  const param = {
    page: currentPage.value,
    rows: pageSize.value,
    params: JSON.stringify(buildQueryParams())
  }
  proxy.$axios.get(listUrl.value, param).then((response) => {
    if (response.data.code === '0') {
      tableData.value = response.data.data.records || []
      totalRows.value = response.data.data.total || 0
    } else {
      ElMessage.error(`查询失败：${response.data.msg || ''}`)
    }
  }).catch((error) => {
    ElMessage.error(`查询失败：${error.message || ''}`)
  }).finally(() => {
    tableLoading.value = false
  })
}

const getStatistics = () => {
  const param = {
    params: JSON.stringify(buildQueryParams())
  }
  proxy.$axios
    .get(statisticsUrl.value, param)
    .then((response) => {
      if (response.data.code === '0' || response.data.code === 0) {
        const data = response.data.data || {}
        statistics.totalQuantity =
          data.TOTALQUANTITY ??
          data.outQuantity ??
          data.OUT_QUANTITY ??
          data.totalQty ??
          0
        statistics.totalWeight =
          data.TOTALWEIGHT ??
          data.outWeight ??
          data.OUT_WEIGHT ??
          data.totalWgt ??
          0
      } else {
        ElMessage.error(`统计失败：${response.data.msg || ''}`)
      }
    })
    .catch((error) => {
      ElMessage.error(`统计失败：${error.message || ''}`)
    })
}

const handleSearch = () => {
  currentPage.value = 1
  getTableData()
  getStatistics()
}

const handleReset = () => {
  Object.assign(query, createDefaultQuery())
  handleSearch()
}

// 按钮操作区
const handleTransferOwnership = () => {
  if (multipleSelection.value.length === 0) {
    ElMessage.warning('请先选择要转移货权的数据')
    return
  }
  popupTransferOwnershipRef.value?.open(multipleSelection.value)
}

const handleTransferOwnershipSuccess = () => {
  // 货权转移成功后刷新数据
  getTableData()
  getStatistics()
  // 清空选中
  if (tableRef.value) {
    tableRef.value.clearSelection()
  }
}

const handleAllocate = () => {
  if (multipleSelection.value.length === 0) {
    ElMessage.warning('请先选择要配货的数据')
    return
  }
  popupDistributionRef.value?.open(multipleSelection.value)
}

const handleSelectionChange = (selection) => {
  multipleSelection.value = selection
}

const handleDistributionSuccess = () => {
  // 配货成功后刷新数据
  getTableData()
  getStatistics()
  // 清空选中
  if (tableRef.value) {
    tableRef.value.clearSelection()
  }
}

const handleOutStock = () => {
  if (multipleSelection.value.length === 0) {
    ElMessage.warning('请先选择要出库的数据')
    return
  }
  popupOutStockRef.value?.open(multipleSelection.value)
}

const handleOutStockSuccess = () => {
  // 出库成功后刷新数据
  getTableData()
  getStatistics()
  // 清空选中
  if (tableRef.value) {
    tableRef.value.clearSelection()
  }
}

const handleExport = () => {
  if (multipleSelection.value.length === 0) {
    ElMessage.warning('请选择要导出的数据');
    return;
  }
  const exportData = mapTableData(multipleSelection.value)
  axios({
    method: 'POST',
    url: '/sto/InRecord/exportInRecode',
    data: exportData,  // 使用转换后的数据
    responseType: 'blob',
    headers: {
      'Content-Type': 'application/json'
    }
  }).then((response) => {
    // 创建下载链接
    const url = window.URL.createObjectURL(new Blob([response.data]));
    const link = document.createElement('a');
    link.href = url;
    link.setAttribute('download', `入库记录_${new Date().getTime()}.xlsx`);
    document.body.appendChild(link);
    link.click();
    link.remove();
    window.URL.revokeObjectURL(url);

    ElMessage.success('导出成功');
  }).catch((error) => {
    console.error('导出失败:', error);
    ElMessage.error('导出失败，请重试');
  });
}
const mapTableData = (backendData) => {
  if (!backendData || !Array.isArray(backendData)) {
    return [];
  }

  return backendData.map(item => {
    return {
      // 表格选择框需要的字段
      id: item.id,
      wareId: item.wareId,
      stackId: item.stackId,
      storeId: item.storeId,

      // 仓库信息（前端使用 outWareName/wareName 逻辑）
      wareName: item.wareName,
      outWareName: item.outWareName || item.wareName,

      // 垛位信息（前端使用 outStackName/stackName 逻辑）
      stackName: item.stackName,
      outStackName: item.outStackName || item.stackName,

      // 层号（前端使用 outLayerNo/layerNo 逻辑）
      layerNo: item.layerNo,
      outLayerNo: item.outLayerNo || item.layerNo,

      // 物料信息
      materialName: item.materialName,

      // 钢种（统一使用 stGrade）
      stGrade: item.stGrade,
      ST_GRADE: item.stGrade, // 兼容原有大写字段

      // 规格型号（将 attrib03 映射到 materialStandard）
      attrib03: item.attrib_03, // 注意：后端返回的是 attrib_03
      materialStandard: item.attrib_03, // 前端表格需要的字段

      // 入库时间
      inDtm: item.inDtm,

      // 公司信息
      ownerCompany: item.ownerCompany,
      receivingCompany: item.receivingCompany,
      customerCompany: item.customerCompany,
      CustomerCompany: item.customerCompany, // 兼容大写

      // 编号信息
      prodNo: item.prodNo,
      inTruckNo: item.inTruckNo,
      carNo: item.inTruckNo, // 兼容 carNo 字段

      // 属性字段（后端返回的是 attrib_01, attrib_02 等）
      attrib01: item.attrib01,
      attrib02: item.attrib02,
      attrib04: item.attrib04,
      attrib05: item.attrib05,

      // 重量和数量
      weight: item.weight,
      WEIGHT: item.weight, // 兼容大写
      quantity: item.quantity,
      QUANTITY: item.quantity, // 兼容大写

      // 其他字段
      outFlag: item.outFlag,
      deliveryAddress: item.deliveryAddress,
      remark1: item.remark1,

      // 如果需要保留原始数据
      _rawData: item
    };
  });
};

const handleOtherCommand = (command) => {
  // 其他操作下拉：取消入库、批量修改、批量倒垛
  switch (command) {
    case 'cancelIn':
      handleCancelInbound()
      break
    case 'batchEdit':
      handleBatchEdit()
      break
    case 'batchMove':
      handleBatchMove()
      break
    default:
      break
  }
}

// 取消入库
const handleCancelInbound = () => {
  if (multipleSelection.value.length === 0) {
    ElMessage.warning('请先选择要取消入库的数据')
    return
  }
  if(multipleSelection.value.length>1){
    ElMessage.warning('一次只能取消一个入库单')
    return;
  }
  
  ElMessageBox.confirm(
    '确认取消入库吗?',
    '提示',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    const params = {
      id: multipleSelection.value[0].id,
      prodId:multipleSelection.value[0].storeId
    };
    handleCancelInStore(params)
  }).catch(() => {
    // 取消操作
    ElMessage.info('已取消操作')
  })
}
const handleCancelInStore = (params) => {
  proxy.$axios.post('/sto/InRecord/cancelInStore',
      { params: JSON.stringify(params) }
  ).then((response) => {
    console.log('完整响应对象:', response);
    console.log('响应数据:', response.data);

    // 首先检查 response 是否存在以及是否包含 data 属性
    if (!response || !response.data) {
      ElMessage.error('服务器未返回有效数据');
      return;
    }
    if (response.data.code == '0') {
      ElMessage.success('取消入库成功');
      getTableData();
      getStatistics()
    } else {
      ElMessage.error(response.data.msg || response.data.message || '操作失败');
    }
  }).catch((error) => {
    console.error('取消入库失败:', error);
    ElMessage.error('请求失败，请重试');
  });
}

// 批量修改
const handleBatchEdit = () => {
  if (multipleSelection.value.length === 0) {
    ElMessage.warning('请先选择要批量修改的数据')
    return
  }
  popupBatchEditRef.value?.open(multipleSelection.value)
}

const handleBatchEditSuccess = () => {
  // 批量修改成功后刷新数据
  getTableData()
  getStatistics()
  // 清空选中
  if (tableRef.value) {
    tableRef.value.clearSelection()
  }
}

// 批量倒垛
const handleBatchMove = () => {
  if (multipleSelection.value.length === 0) {
    ElMessage.warning('请先选择要批量倒垛的数据')
    return
  }
  popupBatchMoveRef.value?.open(multipleSelection.value)
}

const handleBatchMoveSuccess = () => {
  // 批量倒垛成功后刷新数据
  getTableData()
  getStatistics()
  // 清空选中
  if (tableRef.value) {
    tableRef.value.clearSelection()
  }
}

// 执行取消入库
const executeCancelInbound = async () => {
  try {
    // 收集选中的行ID
    const ids = multipleSelection.value.map(row => row.id || row.prodNo).filter(id => id)
    
    if (ids.length === 0) {
      ElMessage.warning('选中的数据中没有有效的ID')
      return
    }
    
    // TODO: 根据实际API调整接口地址和参数格式
    const url = 'sto/InRecord/cancel' // 需要根据实际API调整
    const param = {
      ids: JSON.stringify(ids),
      jsonList: JSON.stringify(multipleSelection.value)
    }
    
    const response = await proxy.$axios.post(url, param)
    
    if (response.data.code === 0 || response.data.code === '0') {
      ElMessage.success('取消入库成功')
      // 刷新数据
      getTableData()
      getStatistics()
      // 清空选中
      if (tableRef.value) {
        tableRef.value.clearSelection()
      }
    } else {
      ElMessage.error(`取消入库失败：${response.data.msg || ''}`)
    }
  } catch (error) {
    ElMessage.error(`取消入库失败：${error.message || ''}`)
  }
}

const handleLockCommand = (command) => {
  // 封锁出仓下拉：封锁、取消封锁、入仓
  switch (command) {
    case 'lock':
      handleLock()
      break
    case 'unlock':
      handleUnlock()
      break
    case 'inStock':
      handleInStock()
      break
    default:
      break
  }
}

// 封锁
const handleLock = () => {
  if (multipleSelection.value.length === 0) {
    ElMessage.warning('请先选择要封锁的材料')
    return
  }
  
  ElMessageBox.confirm(
    '确认将选中的材料进行封锁吗?',
    '提示',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    // 确认后执行封锁
    executeLock()
  }).catch(() => {
    // 取消操作
    ElMessage.info('已取消操作')
  })
}

// 执行封锁
const executeLock = async () => {
  try {
    // 收集选中的行ID
    const ids = multipleSelection.value.map(row => row.id || row.prodNo).filter(id => id)
    
    if (ids.length === 0) {
      ElMessage.warning('选中的数据中没有有效的ID')
      return
    }
    
    // TODO: 根据实际API调整接口地址和参数格式
    const url = 'sto/OutRecord/lock' // 需要根据实际API调整
    const param = {
      ids: JSON.stringify(ids),
      jsonList: JSON.stringify(multipleSelection.value)
    }
    
    const response = await proxy.$axios.post(url, param)
    
    if (response.data.code === 0 || response.data.code === '0') {
      ElMessage.success('封锁成功')
      // 刷新数据
      getTableData()
      getStatistics()
      // 清空选中
      if (tableRef.value) {
        tableRef.value.clearSelection()
      }
    } else {
      ElMessage.error(`封锁失败：${response.data.msg || ''}`)
    }
  } catch (error) {
    ElMessage.error(`封锁失败：${error.message || ''}`)
  }
}

// 取消封锁
const handleUnlock = () => {
  if (multipleSelection.value.length === 0) {
    ElMessage.warning('请先选择要取消封锁的材料')
    return
  }
  
  ElMessageBox.confirm(
    '确认将选中的材料取消封锁吗?',
    '提示',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    // 确认后执行取消封锁
    executeUnlock()
  }).catch(() => {
    // 取消操作
    ElMessage.info('已取消操作')
  })
}

// 执行取消封锁
const executeUnlock = async () => {
  try {
    // 收集选中的行ID
    const ids = multipleSelection.value.map(row => row.id || row.prodNo).filter(id => id)
    
    if (ids.length === 0) {
      ElMessage.warning('选中的数据中没有有效的ID')
      return
    }
    
    // TODO: 根据实际API调整接口地址和参数格式
    const url = 'sto/OutRecord/unlock' // 需要根据实际API调整
    const param = {
      ids: JSON.stringify(ids),
      jsonList: JSON.stringify(multipleSelection.value)
    }
    
    const response = await proxy.$axios.post(url, param)
    
    if (response.data.code === 0 || response.data.code === '0') {
      ElMessage.success('取消封锁成功')
      // 刷新数据
      getTableData()
      getStatistics()
      // 清空选中
      if (tableRef.value) {
        tableRef.value.clearSelection()
      }
    } else {
      ElMessage.error(`取消封锁失败：${response.data.msg || ''}`)
    }
  } catch (error) {
    ElMessage.error(`取消封锁失败：${error.message || ''}`)
  }
}

// 入仓
const handleInStock = () => {
  if (multipleSelection.value.length === 0) {
    ElMessage.warning('请先选择要入仓的材料')
    return
  }
  
  ElMessageBox.confirm(
    '确认将选中的材料标记为入仓吗?',
    '提示',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    // 确认后执行入仓
    executeInStock()
  }).catch(() => {
    // 取消操作
    ElMessage.info('已取消操作')
  })
}

// 执行入仓
const executeInStock = async () => {
  try {
    // 收集选中的行ID
    const ids = multipleSelection.value.map(row => row.id || row.prodNo).filter(id => id)
    
    if (ids.length === 0) {
      ElMessage.warning('选中的数据中没有有效的ID')
      return
    }
    
    // TODO: 根据实际API调整接口地址和参数格式
    const url = 'sto/OutRecord/inStock' // 需要根据实际API调整
    const param = {
      ids: JSON.stringify(ids),
      jsonList: JSON.stringify(multipleSelection.value)
    }
    
    const response = await proxy.$axios.post(url, param)
    
    if (response.data.code === 0 || response.data.code === '0') {
      ElMessage.success('入仓成功')
      // 刷新数据
      getTableData()
      getStatistics()
      // 清空选中
      if (tableRef.value) {
        tableRef.value.clearSelection()
      }
    } else {
      ElMessage.error(`入仓失败：${response.data.msg || ''}`)
    }
  } catch (error) {
    ElMessage.error(`入仓失败：${error.message || ''}`)
  }
}

const handleSizeChange = (val) => {
  pageSize.value = val
  getTableData()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  getTableData()
}

// 编辑功能
const handleEdit = (row) => {
  popupEditRef.value?.open(row)
}

const handleEditSuccess = () => {
  // 编辑成功后刷新数据
  getTableData()
  getStatistics()
}

const flagLabel = (val) => {
  if (val === '1' || val === 1) return '正常'
  if (val === '2' || val === 2) return '取消出库'
  return val ?? '-'
}
const flagTagType = (val) => {
  if (val === '1' || val === 1) return 'success'
  if (val === '2' || val === 2) return 'danger'
  return 'info'
}

const fetchWareOptions = () => {
  proxy.$axios.get('sto/Ware/options', {}).then((response) => {
    if (response.data.code === 0 || response.data.code === '0') {
      wareOptions.value = toOptions(response.data.data, 'label', 'value')
    }
  })
}

const fetchOwnerCompanyOptions = () => {
  proxy.$axios.get('sto/Customer/querySelect', {}).then((response) => {
    if (response.data.code === 0 || response.data.code === '0') {
      ownerCompanyOptions.value = toOptions(response.data.data, 'label', 'value')
    }
  })
}

const fetchCustomerOptions = () => {
  proxy.$axios.get('sto/Customer/querySelect', {}).then((response) => {
    if (response.data.code === 0 || response.data.code === '0') {
      customerCompanyOptions.value = toOptions(response.data.data, 'label', 'value')
    }
  })
}

const handleWareVisible = (visible) => {
  if (visible && wareOptions.value.length === 0) {
    fetchWareOptions()
  }
}

const handleOwnerVisible = (visible) => {
  if (visible && ownerCompanyOptions.value.length === 0) {
    fetchOwnerCompanyOptions()
  }
}

const handleCustomerVisible = (visible) => {
  if (visible && customerCompanyOptions.value.length === 0) {
    fetchCustomerOptions()
  }
}

onMounted(() => {
  fetchWareOptions()
  fetchOwnerCompanyOptions()
  fetchCustomerOptions()
  getTableData()
  getStatistics()
})
</script>

<style scoped>
.summary-card {
  margin-top: 10px;
}
.summary-item {
  display: flex;
  align-items: center;
  height: 40px;
}
.summary-label {
  color: #606266;
  margin-right: 6px;
  font-weight: 500;
}
.summary-value {
  font-size: 18px;
  font-weight: 600;
  color: #303133;
}
</style>
