<template>
  <!-- 移动端布局 -->
  <div v-if="isMobile" class="mobile-weigh">
    <!-- 顶部操作栏 -->
    <div class="mobile-header">
      <div class="mobile-header__search">
        <el-input v-model="queryParams.supplierName" placeholder="搜索交售农户" clearable @keyup.enter="handleQuery" :prefix-icon="Search" />
      </div>
      <div class="mobile-header__actions">
        <el-button :icon="Filter" circle @click="filterVisible = true" />
        <el-button type="primary" :icon="Plus" circle @click="openForm('create')" v-hasPermi="['erp:weigh:create']" />
      </div>
    </div>

    <!-- 卡片列表 -->
    <div class="mobile-list" v-loading="loading">
      <div v-if="list.length === 0 && !loading" class="mobile-empty">
        <el-empty description="暂无过磅记录" />
      </div>
      <div v-for="item in list" :key="item.id" class="mobile-card" @click="handleCardClick(item)">
        <div class="mobile-card__header">
          <span class="mobile-card__no">{{ item.no || '-' }}</span>
          <el-tag :type="item.inStatus === 1 ? 'success' : 'info'" size="small">
            {{ item.inStatus === 1 ? '已入库' : '未入库' }}
          </el-tag>
        </div>
        <div class="mobile-card__body">
          <div class="mobile-card__row">
            <span class="mobile-card__label">原料</span>
            <span class="mobile-card__value">{{ item.productName || '-' }}</span>
          </div>
          <div class="mobile-card__row">
            <span class="mobile-card__label">交售农户</span>
            <span class="mobile-card__value">{{ item.supplierName || '-' }}</span>
          </div>
          <div class="mobile-card__row">
            <span class="mobile-card__label">车号</span>
            <span class="mobile-card__value">{{ item.vehicleNumber || '-' }}</span>
          </div>
          <div class="mobile-card__row">
            <span class="mobile-card__label">承运司机</span>
            <span class="mobile-card__value">{{ item.driver || '-' }}</span>
          </div>
          <div class="mobile-card__row">
            <span class="mobile-card__label">创建时间</span>
            <span class="mobile-card__value">{{ formatDateTime(item.createTime) }}</span>
          </div>
          <div class="mobile-card__nums">
            <div class="mobile-card__num-item">
              <div class="mobile-card__num-val">{{ item.grossWeight ?? '-' }}</div>
              <div class="mobile-card__num-label">毛重kg</div>
            </div>
            <div class="mobile-card__num-item">
              <div class="mobile-card__num-val">{{ item.tareWeight ?? '-' }}</div>
              <div class="mobile-card__num-label">皮重kg</div>
            </div>
            <div class="mobile-card__num-item">
              <div class="mobile-card__num-val" style="color:#409eff">{{ item.netWeight ?? '-' }}</div>
              <div class="mobile-card__num-label">净重kg</div>
            </div>
            <div class="mobile-card__num-item">
              <div class="mobile-card__num-val" style="color:#e6a23c">{{ item.plannedWeight ?? '-' }}</div>
              <div class="mobile-card__num-label">计划kg</div>
            </div>
          </div>
        </div>
        <div class="mobile-card__footer">
          <el-button size="small" type="primary" @click.stop="openForm('update', item.id)" v-hasPermi="['erp:weigh:update']" v-if="item.inStatus !== 1">编辑</el-button>
          <el-button size="small" @click.stop="openDetailDialog(item)" v-if="item.inStatus !== 0">详情</el-button>
          <el-button size="small" type="success" @click.stop="openWarehouseDialog(item)" v-hasPermi="['erp:weigh:inbound']" v-if="item.inStatus !== 1">入库</el-button>
          <el-button size="small" type="danger" @click.stop="handleDelete(item.id)" v-hasPermi="['erp:weigh:delete']" v-if="item.inStatus !== 1">删除</el-button>
        </div>
      </div>
    </div>

    <!-- 分页 -->
    <div class="mobile-pagination" v-if="total > 0">
      <Pagination :total="total" v-model:page="queryParams.pageNo" v-model:limit="queryParams.pageSize" :page-sizes="[10, 20]" layout="total, prev, pager, next" :pager-count="5" @pagination="getList" />
    </div>

    <!-- 筛选抽屉 -->
    <el-drawer v-model="filterVisible" title="筛选条件" direction="btt" size="50%">
      <el-form :model="queryParams" ref="queryFormRef" label-position="top">
        <el-form-item label="车号" prop="vehicleNumber">
          <el-input v-model="queryParams.vehicleNumber" placeholder="请输入车号" clearable />
        </el-form-item>
        <el-form-item label="管理员" prop="administrator">
          <el-input v-model="queryParams.administrator" placeholder="请输入管理员姓名" clearable />
        </el-form-item>
        <el-form-item label="创建时间" prop="createTime">
          <el-date-picker v-model="queryParams.createTime" type="daterange" value-format="YYYY-MM-DD HH:mm:ss" start-placeholder="开始" end-placeholder="结束" :default-time="[new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 1, 1, 23, 59, 59)]" style="width:100%" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="resetQuery">重置</el-button>
        <el-button type="primary" @click="handleFilterConfirm">确认筛选</el-button>
      </template>
    </el-drawer>

    <!-- 表单弹窗：添加/修改 -->
    <WeighForm ref="formRef" @success="getList" />

    <!-- 入库：选择仓库弹窗 -->
    <el-dialog v-model="warehouseDialogVisible" title="选择入库仓库" width="90%">
      <div style="margin-bottom:12px;font-size:13px;color:#606266">
        <div>原料：{{ currentWeigh?.productName || '-' }}</div>
        <div>入库数量(kg)：{{ currentWeigh?.plannedWeight ?? '-' }}</div>
      </div>
      <el-form label-position="top">
        <el-form-item label="仓库">
          <el-select v-model="selectedWarehouseId" placeholder="请选择仓库" style="width:100%" :loading="warehouseLoading">
            <el-option v-for="w in warehouseOptions" :key="w.id" :label="w.name" :value="w.id" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="warehouseDialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="inboundLoading" @click="confirmInbound">确认</el-button>
      </template>
    </el-dialog>

    <!-- 详情弹窗 -->
    <el-dialog v-model="detailDialogVisible" title="过磅单详情" width="95%" fullscreen>
      <el-tabs>
        <el-tab-pane label="基本信息">
          <el-descriptions :column="1" border>
            <el-descriptions-item label="编号">{{ detailData?.no || '-' }}</el-descriptions-item>
            <el-descriptions-item label="原料">{{ detailData?.productName || '-' }}</el-descriptions-item>
            <el-descriptions-item label="毛重(kg)">{{ detailData?.grossWeight || '-' }}</el-descriptions-item>
            <el-descriptions-item label="皮重(kg)">{{ detailData?.tareWeight || '-' }}</el-descriptions-item>
            <el-descriptions-item label="净重(kg)">{{ detailData?.netWeight || '-' }}</el-descriptions-item>
            <el-descriptions-item label="扣杂率(%)">{{ detailData?.impurityRate || '-' }}</el-descriptions-item>
            <el-descriptions-item label="计划重量(kg)">{{ detailData?.plannedWeight || '-' }}</el-descriptions-item>
            <el-descriptions-item label="交售农户">{{ detailData?.supplierName || '-' }}</el-descriptions-item>
            <el-descriptions-item label="身份证号">{{ detailData?.idCardNumber || '-' }}</el-descriptions-item>
            <el-descriptions-item label="车号">{{ detailData?.vehicleNumber || '-' }}</el-descriptions-item>
            <el-descriptions-item label="承运司机">{{ detailData?.driver || '-' }}</el-descriptions-item>
            <el-descriptions-item label="管理员">{{ detailData?.administrator || '-' }}</el-descriptions-item>
            <el-descriptions-item label="司磅员">{{ detailData?.weigher || '-' }}</el-descriptions-item>
            <el-descriptions-item label="产地证明号">{{ detailData?.originCertificateNumber || '-' }}</el-descriptions-item>
            <el-descriptions-item label="入库状态"><el-tag :type="(detailData?.inStatus === 1) ? 'success' : 'info'">{{ (detailData?.inStatus === 1) ? '已入库' : '未入库' }}</el-tag></el-descriptions-item>
            <el-descriptions-item label="创建时间">{{ detailData?.createTime ? formatDateTime(detailData.createTime) : '-' }}</el-descriptions-item>
            <el-descriptions-item label="备注">{{ detailData?.remark || '-' }}</el-descriptions-item>
          </el-descriptions>
        </el-tab-pane>
        <el-tab-pane label="检查信息">
          <el-descriptions :column="1" border>
            <el-descriptions-item label="取样日期">{{ detailData?.sampleDate ? formatDateTime(detailData.sampleDate) : '-' }}</el-descriptions-item>
            <el-descriptions-item label="取样地点">{{ detailData?.sampleLocation || '-' }}</el-descriptions-item>
            <el-descriptions-item label="代表性重量(kg)">{{ detailData?.representativeWeight || '-' }}</el-descriptions-item>
            <el-descriptions-item label="样品重量(kg)">{{ detailData?.sampleWeight || '-' }}</el-descriptions-item>
            <el-descriptions-item label="杂质重量(kg)">{{ detailData?.impurityWeight || '-' }}</el-descriptions-item>
            <el-descriptions-item label="沙石重量(kg)">{{ detailData?.sandWeight || '-' }}</el-descriptions-item>
            <el-descriptions-item label="感官评价">{{ detailData?.sensoryEvaluation || '-' }}</el-descriptions-item>
            <el-descriptions-item label="合格率(%)">{{ detailData?.qualificationRate || '-' }}</el-descriptions-item>
            <el-descriptions-item label="水分含量(%)">{{ detailData?.moistureContent || '-' }}</el-descriptions-item>
            <el-descriptions-item label="糖分含量(%)">{{ detailData?.sugarContent || '-' }}</el-descriptions-item>
            <el-descriptions-item label="RA值">{{ detailData?.raValue || '-' }}</el-descriptions-item>
            <el-descriptions-item label="STV值">{{ detailData?.stvValue || '-' }}</el-descriptions-item>
            <el-descriptions-item label="检验员">{{ detailData?.labTechnician || '-' }}</el-descriptions-item>
            <el-descriptions-item label="检验备注">{{ detailData?.inspectionRemark || '-' }}</el-descriptions-item>
          </el-descriptions>
        </el-tab-pane>
      </el-tabs>
      <template #footer>
        <el-button @click="detailDialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>

  <!-- PC端布局 -->
  <div v-else>
    <ContentWrap>
      <!-- 搜索工作栏 -->
      <el-form
        class="-mb-15px"
        :model="queryParams"
        ref="queryFormRef"
        :inline="true"
        label-width="68px"
      >
        <el-form-item label="交售农户" prop="supplierName">
          <el-input
            v-model="queryParams.supplierName"
            placeholder="请输入交售农户"
            clearable
            @keyup.enter="handleQuery"
            class="!w-240px"
          />
        </el-form-item>
        <el-form-item label="车号" prop="vehicleNumber">
          <el-input
            v-model="queryParams.vehicleNumber"
            placeholder="请输入车号"
            clearable
            @keyup.enter="handleQuery"
            class="!w-240px"
          />
        </el-form-item>
        <el-form-item label="管理员" prop="administrator">
          <el-input
            v-model="queryParams.administrator"
            placeholder="请输入管理员姓名"
            clearable
            @keyup.enter="handleQuery"
            class="!w-240px"
          />
        </el-form-item>
        <el-form-item label="创建时间" prop="createTime">
          <el-date-picker
            v-model="queryParams.createTime"
            type="daterange"
            value-format="YYYY-MM-DD HH:mm:ss"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            :default-time="[new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 1, 1, 23, 59, 59)]"
            class="!w-240px"
          />
        </el-form-item>
        <el-form-item>
          <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
          <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>
          <el-button
            type="primary"
            plain
            @click="openForm('create')"
            v-hasPermi="['erp:weigh:create']"
          >
            <Icon icon="ep:plus" class="mr-5px" /> 新增
          </el-button>
          <el-button
            type="success"
            plain
            @click="handleExport"
            :loading="exportLoading"
            v-hasPermi="['erp:weigh:export']"
          >
            <Icon icon="ep:download" class="mr-5px" /> 导出
          </el-button>
        </el-form-item>
      </el-form>
    </ContentWrap>

    <!-- 列表 -->
    <ContentWrap>
      <el-table v-loading="loading" :data="list" :stripe="true" :show-overflow-tooltip="true" @row-click="handleRowClick">
        <el-table-column label="编号" align="center" prop="no" width="150px"/>
        <el-table-column label="原料" align="center" prop="productName" />
        <el-table-column label="毛重(kg)" align="center" prop="grossWeight" />
        <el-table-column label="皮重(kg)" align="center" prop="tareWeight" />
        <el-table-column label="净重(kg)" align="center" prop="netWeight" />
        <el-table-column label="扣杂率(%)" align="center" prop="impurityRate" />
        <el-table-column label="计划重量(kg)" align="center" prop="plannedWeight" width="140"/>
        <el-table-column label="剩余重量(kg)" align="center" prop="remainingWeight" width="140"/>
        <el-table-column label="承运司机" align="center" prop="driver" />
        <el-table-column label="管理员" align="center" prop="administrator" />
        <el-table-column label="司磅员" align="center" prop="weigher" />
        <el-table-column label="入库状态" align="center">
          <template #default="scope">
            <el-tag :type="(scope.row.inStatus === 1) ? 'success' : 'info'">
              {{ (scope.row.inStatus === 1) ? '已入库' : '未入库' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" align="center" prop="createTime" width="170" sortable>
          <template #default="scope">
            {{ formatDateTime(scope.row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="220px">
          <template #default="scope">
            <el-button
              v-if="scope.row.inStatus !== 1"
              link
              type="primary"
              @click.stop="openForm('update', scope.row.id)"
              v-hasPermi="['erp:weigh:update']"
            >
              编辑
            </el-button>
            <el-button
              v-if="scope.row.inStatus !== 0"
              link
              type="primary"
              @click.stop="openDetailDialog(scope.row)"
            >
              详情
            </el-button>
            <el-button
              v-if="scope.row.inStatus !== 1"
              link
              type="success"
              @click.stop="openWarehouseDialog(scope.row)"
              v-hasPermi="['erp:weigh:inbound']"
            >
              入库
            </el-button>
            <el-button
              v-if="scope.row.inStatus !== 1"
              link
              type="danger"
              @click.stop="handleDelete(scope.row.id)"
              v-hasPermi="['erp:weigh:delete']"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <Pagination
        :total="total"
        v-model:page="queryParams.pageNo"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
      />
    </ContentWrap>

    <!-- 表单弹窗：添加/修改 -->
    <WeighForm ref="formRef" @success="getList" />

    <!-- 入库：选择仓库弹窗 -->
    <el-dialog v-model="warehouseDialogVisible" title="选择入库仓库" width="500px">
      <div style="margin-bottom:12px;font-size:14px;color:#606266">
        <div>原料：{{ currentWeigh?.productName || '-' }}</div>
        <div>入库数量(kg)：{{ currentWeigh?.plannedWeight ?? '-' }}</div>
      </div>
      <el-form label-width="80px">
        <el-form-item label="仓库">
          <el-select v-model="selectedWarehouseId" placeholder="请选择仓库" style="width:100%" :loading="warehouseLoading">
            <el-option v-for="w in warehouseOptions" :key="w.id" :label="w.name" :value="w.id" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="warehouseDialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="inboundLoading" @click="confirmInbound">确认</el-button>
      </template>
    </el-dialog>

    <!-- 详情弹窗 -->
    <el-dialog v-model="detailDialogVisible" title="过磅单详情" width="800px">
      <el-tabs>
        <el-tab-pane label="基本信息">
          <el-descriptions :column="2" border>
            <el-descriptions-item label="编号">{{ detailData?.no || '-' }}</el-descriptions-item>
            <el-descriptions-item label="原料">{{ detailData?.productName || '-' }}</el-descriptions-item>
            <el-descriptions-item label="毛重(kg)">{{ detailData?.grossWeight || '-' }}</el-descriptions-item>
            <el-descriptions-item label="皮重(kg)">{{ detailData?.tareWeight || '-' }}</el-descriptions-item>
            <el-descriptions-item label="净重(kg)">{{ detailData?.netWeight || '-' }}</el-descriptions-item>
            <el-descriptions-item label="扣杂率(%)">{{ detailData?.impurityRate || '-' }}</el-descriptions-item>
            <el-descriptions-item label="计划重量(kg)">{{ detailData?.plannedWeight || '-' }}</el-descriptions-item>
            <el-descriptions-item label="交售农户">{{ detailData?.supplierName || '-' }}</el-descriptions-item>
            <el-descriptions-item label="身份证号">{{ detailData?.idCardNumber || '-' }}</el-descriptions-item>
            <el-descriptions-item label="车号">{{ detailData?.vehicleNumber || '-' }}</el-descriptions-item>
            <el-descriptions-item label="承运司机">{{ detailData?.driver || '-' }}</el-descriptions-item>
            <el-descriptions-item label="管理员">{{ detailData?.administrator || '-' }}</el-descriptions-item>
            <el-descriptions-item label="司磅员">{{ detailData?.weigher || '-' }}</el-descriptions-item>
            <el-descriptions-item label="产地证明号">{{ detailData?.originCertificateNumber || '-' }}</el-descriptions-item>
            <el-descriptions-item label="入库状态"><el-tag :type="(detailData?.inStatus === 1) ? 'success' : 'info'">{{ (detailData?.inStatus === 1) ? '已入库' : '未入库' }}</el-tag></el-descriptions-item>
            <el-descriptions-item label="创建时间">{{ detailData?.createTime ? formatDateTime(detailData.createTime) : '-' }}</el-descriptions-item>
            <el-descriptions-item label="备注" :span="2">{{ detailData?.remark || '-' }}</el-descriptions-item>
          </el-descriptions>
        </el-tab-pane>
        <el-tab-pane label="检查信息">
          <el-descriptions :column="2" border>
            <el-descriptions-item label="取样日期">{{ detailData?.sampleDate ? formatDateTime(detailData.sampleDate) : '-' }}</el-descriptions-item>
            <el-descriptions-item label="取样地点">{{ detailData?.sampleLocation || '-' }}</el-descriptions-item>
            <el-descriptions-item label="代表性重量(kg)">{{ detailData?.representativeWeight || '-' }}</el-descriptions-item>
            <el-descriptions-item label="样品重量(kg)">{{ detailData?.sampleWeight || '-' }}</el-descriptions-item>
            <el-descriptions-item label="杂质重量(kg)">{{ detailData?.impurityWeight || '-' }}</el-descriptions-item>
            <el-descriptions-item label="沙石重量(kg)">{{ detailData?.sandWeight || '-' }}</el-descriptions-item>
            <el-descriptions-item label="感官评价">{{ detailData?.sensoryEvaluation || '-' }}</el-descriptions-item>
            <el-descriptions-item label="合格率(%)">{{ detailData?.qualificationRate || '-' }}</el-descriptions-item>
            <el-descriptions-item label="水分含量(%)">{{ detailData?.moistureContent || '-' }}</el-descriptions-item>
            <el-descriptions-item label="糖分含量(%)">{{ detailData?.sugarContent || '-' }}</el-descriptions-item>
            <el-descriptions-item label="RA值">{{ detailData?.raValue || '-' }}</el-descriptions-item>
            <el-descriptions-item label="STV值">{{ detailData?.stvValue || '-' }}</el-descriptions-item>
            <el-descriptions-item label="检验员">{{ detailData?.labTechnician || '-' }}</el-descriptions-item>
            <el-descriptions-item label="检验备注">{{ detailData?.inspectionRemark || '-' }}</el-descriptions-item>
          </el-descriptions>
        </el-tab-pane>
      </el-tabs>
      <template #footer>
        <el-button @click="detailDialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { computed } from 'vue'
import { Search, Filter, Plus } from '@element-plus/icons-vue'
import { DICT_TYPE } from '@/utils/dict'
import { formatDate } from '@/utils/formatTime'
import download from '@/utils/download'
import WeighForm from './WeighForm.vue'
import { onMounted, ref, reactive } from 'vue'
import { useI18n } from '@/hooks/web/useI18n'
import { useMessage } from '@/hooks/web/useMessage'
import { WeighApi } from '@/api/erp/purchase/weigh'
import { WarehouseApi } from '@/api/erp/stock/warehouse'
import { useWindowSize } from '@vueuse/core'

const { width } = useWindowSize()
const isMobile = computed(() => width.value < 768)

// 定义过磅单数据结构
interface WeighVO {
  id: number
  productName: string
  no?: string
  productId?: number
  supplierName: string
  idCardNumber: string
  vehicleNumber: string
  grossWeight: number
  tareWeight: number
  netWeight: number
  impurityRate: number
  plannedWeight: number
  driver: string
  administrator: string
  weigher: string
  originCertificateNumber: string
  createTime: string
  inStatus: number
  sampleDate?: string
  sampleLocation?: string
  representativeWeight?: number
  sampleWeight?: number
  impurityWeight?: number
  sandWeight?: number
  sensoryEvaluation?: string
  qualificationRate?: string
  moistureContent?: string
  sugarContent?: string
  raValue?: string
  stvValue?: string
  labTechnician?: string
  inspectionRemark?: string
  remark?: string
  fileUrl?: string
}

// 定义查询参数类型
interface QueryParams {
  pageNo: number
  pageSize: number
  supplierName?: string
  vehicleNumber?: string
  administrator?: string
  createTime?: string[]
  beginCreateTime?: string
  endCreateTime?: string
}

/** ERP 过磅单 列表 */
defineOptions({ name: 'ErpWeigh' })

const message = useMessage()
const { t } = useI18n()

const loading = ref(true)
const total = ref(0)
const list = ref<WeighVO[]>([])
const filterVisible = ref(false)
const queryParams = reactive<QueryParams>({
  pageNo: 1,
  pageSize: 10,
  supplierName: undefined,
  vehicleNumber: undefined,
  administrator: undefined,
  createTime: undefined
})
const queryFormRef = ref()
const exportLoading = ref(false)
const formRef = ref()

// 入库弹窗相关
const warehouseDialogVisible = ref(false)
const warehouseOptions = ref<{ id: number; name: string }[]>([])
const selectedWarehouseId = ref<number | undefined>(undefined)
const warehouseLoading = ref(false)
const inboundLoading = ref(false)
const currentWeigh = ref<WeighVO | null>(null)

// 详情弹窗相关
const detailDialogVisible = ref(false)
const detailData = ref<WeighVO | null>(null)

const formatDateTime = (date: string) => {
  if (!date) return ''
  return formatDate(new Date(date))
}

const handleCardClick = (row: WeighVO) => {
  if (row.inStatus === 1) {
    openDetailDialog(row)
  } else {
    openForm('update', row.id)
  }
}

const openDetailDialog = (row: WeighVO) => {
  detailData.value = row
  detailDialogVisible.value = true
  WeighApi.getWeigh(row.id).then(response => {
    detailData.value = response
  }).catch(() => {
    message.error('获取详情数据失败')
  })
}

const openWarehouseDialog = async (row: WeighVO) => {
  if (row.inStatus === 1) {
    message.warning('该过磅单已入库，无法重复入库')
    return
  }
  currentWeigh.value = row
  selectedWarehouseId.value = undefined
  warehouseDialogVisible.value = true
  warehouseLoading.value = true
  try {
    const list = await WarehouseApi.getWarehouseSimpleList()
    warehouseOptions.value = Array.isArray(list) ? list : []
  } finally {
    warehouseLoading.value = false
  }
}

const confirmInbound = async () => {
  if (!currentWeigh.value) return
  if (!currentWeigh.value.productId) {
    message.error('该过磅单缺少产品信息，无法入库')
    return
  }
  const count = Number(currentWeigh.value.plannedWeight || 0)
  if (!count || count <= 0) {
    message.error('入库数量无效')
    return
  }
  if (!selectedWarehouseId.value) {
    message.warning('请选择仓库')
    return
  }
  inboundLoading.value = true
  try {
    await WeighApi.inbound({
      weighId: currentWeigh.value.id,
      warehouseId: selectedWarehouseId.value,
      count: count
    })
    message.success('入库成功')
    const target = list.value.find(item => item.id === currentWeigh.value!.id)
    if (target) target.inStatus = 1
    warehouseDialogVisible.value = false
    await getList()
  } catch (e) {
    message.error('入库失败')
  } finally {
    inboundLoading.value = false
  }
}

const getList = async () => {
  loading.value = true
  try {
    const params: QueryParams = { ...queryParams }
    if (params.createTime && params.createTime.length === 2) {
      params.beginCreateTime = params.createTime[0]
      params.endCreateTime = params.createTime[1]
      delete params.createTime
    }
    const data = await WeighApi.getWeighPage(params)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

const resetQuery = () => {
  queryFormRef.value?.resetFields()
  handleQuery()
}

const handleFilterConfirm = () => {
  filterVisible.value = false
  handleQuery()
}

const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}

const handleDelete = async (id: number) => {
  try {
    await message.delConfirm()
    await WeighApi.deleteWeigh(id)
    message.success(t('common.delSuccess'))
    await getList()
  } catch {}
}

const handleExport = async () => {
  try {
    await message.exportConfirm()
    exportLoading.value = true
    const data = await WeighApi.exportWeigh(queryParams)
    download.excel(data, 'ERP 过磅单.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

/** 行点击操作 */
const handleRowClick = (row: WeighVO, column: any, event: MouseEvent) => {
  const target = event.target as HTMLElement
  if (target.tagName === 'BUTTON' || target.tagName === 'A' || target.tagName === 'I' || target.tagName === 'svg' || target.closest('button') || target.closest('a') || target.closest('.el-button') || target.closest('.el-checkbox')) {
    return
  }
  if (row.inStatus === 1) {
    openDetailDialog(row)
  } else {
    openForm('update', row.id)
  }
}

onMounted(() => {
  getList()
})
</script>

<style lang="scss" scoped>
.mobile-weigh {
  padding: 12px;
  background: #f5f5f5;
  min-height: 100vh;
}
.mobile-header {
  display: flex; gap: 8px; align-items: center; margin-bottom: 12px;
  &__search { flex: 1; }
  &__actions { display: flex; gap: 4px; flex-shrink: 0; }
}
.mobile-list { display: flex; flex-direction: column; gap: 10px; }
.mobile-empty { padding: 40px 0; }
.mobile-card {
  background: #fff; border-radius: 10px; padding: 14px; box-shadow: 0 1px 4px rgba(0,0,0,0.06);
  &__header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 10px; }
  &__no { font-weight: 600; font-size: 15px; color: #303133; }
  &__body { font-size: 13px; }
  &__row { display: flex; justify-content: space-between; padding: 3px 0; }
  &__label { color: #909399; flex-shrink: 0; margin-right: 12px; }
  &__value { color: #606266; text-align: right; }
  &__nums { display: flex; justify-content: space-around; margin-top: 10px; padding: 10px 0; border-top: 1px solid #f0f0f0; border-bottom: 1px solid #f0f0f0; }
  &__num-item { text-align: center; }
  &__num-val { font-size: 15px; font-weight: 600; color: #303133; }
  &__num-label { font-size: 11px; color: #909399; margin-top: 2px; }
  &__footer { display: flex; flex-wrap: wrap; gap: 6px; margin-top: 10px; }
}
.mobile-pagination {
  margin-top: 12px; display: flex; justify-content: center;
  :deep(.el-pagination) { flex-wrap: wrap; justify-content: center; }
}
</style>
