<template>
  <!-- 手机端布局 -->
  <div v-if="isMobile" class="mobile-workorder-list">
    <!-- 顶部操作栏 -->
    <div class="mobile-header">
      <div class="mobile-header__search">
        <el-input
          v-model="queryParams.code"
          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="['mes:production-order:create']" />
      </div>
    </div>

    <!-- 快捷筛选 -->
    <div class="mobile-header__quick-filter">
      <div
        class="quick-filter-item"
        :class="{ active: quickFilterStatus === undefined }"
        @click="handleQuickFilter(undefined)"
      >全部</div>
      <div
        class="quick-filter-item"
        :class="{ active: quickFilterStatus === 2 }"
        @click="handleQuickFilter(2)"
      >已审核</div>
      <div
        class="quick-filter-item"
        :class="{ active: quickFilterStatus === 3 }"
        @click="handleQuickFilter(3)"
      >生产中</div>
      <div
        class="quick-filter-item"
        :class="{ active: quickFilterStatus === 4 }"
        @click="handleQuickFilter(4)"
      >已完成</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="row in list"
        :key="row.id"
        class="mobile-card"
        @click="handleCardClick(row)"
      >
        <div class="mobile-card__header">
          <span class="mobile-card__no">{{ row.code }}</span>
          <el-tag :type="getStatusType(row.status)" size="small">{{ getStatusText(row.status) }}</el-tag>
        </div>
        <div class="mobile-card__body">
          <div class="mobile-card__row">
            <span class="mobile-card__label">产品</span>
            <span class="mobile-card__value mobile-card__value--ellipsis">{{ row.productName }}</span>
          </div>
          <div class="mobile-card__row">
            <span class="mobile-card__label">产品编码</span>
            <span class="mobile-card__value">{{ row.productCode }}</span>
          </div>
          <div class="mobile-card__row">
            <span class="mobile-card__label">计划时间</span>
            <span class="mobile-card__value">{{ formatDateTime(row.planStartTime) }} ~ {{ formatDateTime(row.planEndTime) }}</span>
          </div>
          <div class="mobile-card__nums">
            <div class="mobile-card__num-item">
              <div class="mobile-card__num-val" style="color:#409eff">{{ row.planQuantity || 0 }}</div>
              <div class="mobile-card__num-label">计划数量</div>
            </div>
            <div class="mobile-card__num-item">
              <div class="mobile-card__num-val" style="color:#67c23a">{{ row.producedQuantity || 0 }}</div>
              <div class="mobile-card__num-label">已完成</div>
            </div>
            <div class="mobile-card__num-item">
              <div class="mobile-card__num-val" :style="{ color: row.producedQuantity >= row.planQuantity ? '#67c23a' : '#e6a23c' }">
                {{ row.planQuantity > 0 ? Math.round((row.producedQuantity || 0) / row.planQuantity * 100) : 0 }}%
              </div>
              <div class="mobile-card__num-label">完成率</div>
            </div>
          </div>
        </div>
        <div class="mobile-card__footer" @click.stop>
          <el-button size="small" @click="handleShowOperations(row.id, row.status)">详情</el-button>
          <el-button size="small" type="primary" @click="openForm('update', row.id)" v-if="row.status === 0">编辑</el-button>
          <el-button size="small" type="primary" @click="handleSubmit(row.id)" v-if="row.status === 0">提交</el-button>
          <el-button size="small" type="success" @click="handleStart(row.id)" v-if="row.status === 2">开始生产</el-button>
          <el-button size="small" type="success" @click="handleComplete(row)" v-if="row.status === 3">完成</el-button>
          <el-button size="small" type="danger" @click="handleDelete([row.id])" v-if="[0, 6].includes(row.status)">删除</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="60%">
      <el-form :model="queryParams" ref="queryFormRef" label-position="top">
        <el-form-item label="产品名称" prop="productName">
          <el-input v-model="queryParams.productName" placeholder="请输入产品名称" clearable style="width:100%" />
        </el-form-item>
        <el-form-item label="工单状态" prop="status">
          <el-select v-model="queryParams.status" placeholder="请选择状态" clearable multiple style="width:100%">
            <el-option label="草稿" :value="0" />
            <el-option label="待审核" :value="1" />
            <el-option label="已审核" :value="2" />
            <el-option label="生产中" :value="3" />
            <el-option label="已完成" :value="4" />
            <el-option label="已关闭" :value="5" />
            <el-option label="已取消" :value="6" />
            <el-option label="已入库" :value="7" />
          </el-select>
        </el-form-item>
        <el-form-item label="计划日期" prop="planTime">
          <el-date-picker v-model="queryParams.planTime" type="daterange" value-format="YYYY-MM-DD" start-placeholder="开始" end-placeholder="结束" 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>
  </div>

  <!-- PC端布局 -->
  <template v-else>
    <doc-alert title="【MES】生产工单管理" url="https://doc.iocoder.cn/mes/workorder/" />

    <ContentWrap>
      <!-- 搜索工作栏 -->
      <el-form
        class="-mb-15px"
        :model="queryParams"
        ref="queryFormRef"
        :inline="true"
        label-width="84px"
      >
        <el-form-item label="工单编号" prop="code">
          <el-input
            v-model="queryParams.code"
            placeholder="请输入工单编号"
            clearable
            @keyup.enter="handleQuery"
            class="!w-240px"
          />
        </el-form-item>
        <el-form-item label="产品名称" prop="productName">
          <el-input
            v-model="queryParams.productName"
            placeholder="请输入产品名称"
            clearable
            @keyup.enter="handleQuery"
            class="!w-240px"
          />
        </el-form-item>
        <el-form-item label="工单状态" prop="status">
          <el-select
            v-model="queryParams.status"
            placeholder="请选择状态"
            clearable
            multiple
            class="!w-240px"
          >
            <el-option label="草稿" :value="0" />
            <el-option label="待审核" :value="1" />
            <el-option label="已审核" :value="2" />
            <el-option label="生产中" :value="3" />
            <el-option label="已完成" :value="4" />
            <el-option label="已关闭" :value="5" />
            <el-option label="已取消" :value="6" />
            <el-option label="已入库" :value="7" />
          </el-select>
        </el-form-item>
        <el-form-item label="计划日期" prop="planTime">
          <el-date-picker
            v-model="queryParams.planTime"
            type="daterange"
            value-format="YYYY-MM-DD"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            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="['mes:production-order:create']"
          >
            <Icon icon="ep:plus" class="mr-5px" /> 新增
          </el-button>
          <el-button
            type="danger"
            plain
            @click="handleDelete(selectionList.map((item) => item.id))"
            v-hasPermi="['mes:production-order:delete']"
            :disabled="selectionList.length === 0"
          >
            <Icon icon="ep:delete" 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"
      @selection-change="handleSelectionChange"
      @row-click="handleRowClick"
    >
      <el-table-column type="selection" width="50" />
      <el-table-column label="批次信息" align="center" min-width="150">
        <template #default="{ row }">
          <div>{{ row.code }}</div>
          <div class="mt-5px">
            <el-tag :type="getStatusType(row.status)">{{ getStatusText(row.status) }}</el-tag>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="产品信息" align="center" min-width="150">
        <template #default="{ row }">
          <div>{{ row.productName }}</div>
          <div class="text-gray-400 text-sm">{{ row.productCode }}</div>
        </template>
      </el-table-column>
      <el-table-column label="生产数量" align="center" min-width="120">
        <template #default="{ row }">
          <div>计划：{{ row.planQuantity }}</div>
          <div class="mt-5px text-gray-400">完成：{{ row.producedQuantity || 0 }}</div>
        </template>
      </el-table-column>
      <el-table-column label="计划时间" align="center" min-width="200">
        <template #default="{ row }">
          <div>
            <el-tooltip
              :content="formatFullDateTime(row.planStartTime)"
              placement="top"
              :disabled="!row.planStartTime"
            >
              <span>开始：{{ formatDateTime(row.planStartTime) }}</span>
            </el-tooltip>
          </div>
          <div class="mt-5px">
            <el-tooltip
              :content="formatFullDateTime(row.planEndTime)"
              placement="top"
              :disabled="!row.planEndTime"
            >
              <span>结束：{{ formatDateTime(row.planEndTime) }}</span>
            </el-tooltip>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="实际时间" align="center" min-width="200">
        <template #default="{ row }">
          <div>
            <el-tooltip
              :content="formatFullDateTime(row.actualStartTime)"
              placement="top"
              :disabled="!row.actualStartTime"
            >
              <span
                >开始：{{
                  row.actualStartTime ? formatDateTime(row.actualStartTime) : '未开始'
                }}</span
              >
            </el-tooltip>
          </div>
          <div class="mt-5px">
            <el-tooltip
              :content="formatFullDateTime(row.actualEndTime)"
              placement="top"
              :disabled="!row.actualEndTime"
            >
              <span
                >结束：{{ row.actualEndTime ? formatDateTime(row.actualEndTime) : '未结束' }}</span
              >
            </el-tooltip>
          </div>
        </template>
      </el-table-column>
      <el-table-column
        label="备注"
        align="center"
        prop="remark"
        min-width="150"
        show-overflow-tooltip
      />
      <el-table-column label="操作" align="center" fixed="right" width="200">
        <template #default="scope">
          <el-tooltip content="编辑" placement="top">
            <el-button
              link
              type="primary"
              @click="openForm('update', scope.row.id)"
              v-hasPermi="['mes:production-order:update']"
              v-if="scope.row.status === 0"
            >
<!--              <Icon icon="ep:edit" />-->
              编辑
            </el-button>
          </el-tooltip>
          <el-tooltip content="开始生产" placement="top">
            <el-button
              link
              type="primary"
              @click="handleStart(scope.row.id)"
              v-if="scope.row.status === 2"
              v-hasPermi="['mes:production-order:start']"
            >
<!--              <Icon icon="ep:video-play" />-->
              开始生产
            </el-button>
          </el-tooltip>
          <el-tooltip content="完成" placement="top">
            <el-button
              link
              type="success"
              @click="handleComplete(scope.row)"
              v-if="scope.row.status === 3"
              v-hasPermi="['mes:production-order:complete']"
            >
<!--              <Icon icon="ep:check" />-->
              完成
            </el-button>
          </el-tooltip>
          <el-tooltip content="取消" placement="top">
<!--            <el-button-->
<!--              link-->
<!--              type="danger"-->
<!--              @click="handleCancel(scope.row.id)"-->
<!--              v-if="[0, 1, 2].includes(scope.row.status)"-->
<!--              v-hasPermi="['mes:production-order:cancel']"-->
<!--            >-->
<!--&lt;!&ndash;              <Icon icon="ep:close" />&ndash;&gt;-->
<!--              取消-->
<!--            </el-button>-->
          </el-tooltip>
          <el-tooltip content="提交审核" placement="top">
            <el-button
              link
              type="primary"
              @click="handleSubmit(scope.row.id)"
              v-if="scope.row.status === 0"
              v-hasPermi="['mes:production-order:submit']"
            >
<!--              <Icon icon="ep:upload" />-->
              提交
            </el-button>
          </el-tooltip>
<!--          <el-tooltip content="审核通过" placement="top">-->
<!--            <el-button-->
<!--              link-->
<!--              type="success"-->
<!--              @click="handleApprove(scope.row.id)"-->
<!--              v-if="scope.row.status === 1"-->
<!--              v-hasPermi="['mes:production-order:approve']"-->
<!--            >-->
<!--&lt;!&ndash;              <Icon icon="ep:circle-check" />&ndash;&gt;-->
<!--              审核-->
<!--            </el-button>-->
<!--          </el-tooltip>-->
<!--          <el-tooltip content="拒绝" placement="top">-->
<!--            <el-button-->
<!--              link-->
<!--              type="danger"-->
<!--              @click="handleReject(scope.row.id)"-->
<!--              v-if="scope.row.status === 1"-->
<!--              v-hasPermi="['mes:production-order:reject']"-->
<!--            >-->
<!--&lt;!&ndash;              <Icon icon="ep:circle-close" />&ndash;&gt;-->
<!--              拒绝-->
<!--            </el-button>-->
<!--          </el-tooltip>-->
<!--          <el-tooltip content="关闭" placement="top">-->
<!--            <el-button-->
<!--              link-->
<!--              type="danger"-->
<!--              @click="handleClose(scope.row.id)"-->
<!--              v-if="scope.row.status === 4"-->
<!--              v-hasPermi="['mes:production-order:close']"-->
<!--            >-->
<!--              <Icon icon="ep:switch" />-->
<!--            </el-button>-->
<!--          </el-tooltip>-->
          <!-- 入库功能已停用，按钮隐藏 -->
<!--          <el-tooltip content="入库" placement="top">-->
<!--            <el-button-->
<!--              link-->
<!--              type="success"-->
<!--              @click="handleProductionIn(scope.row)"-->
<!--              v-if="false && scope.row.status === 4"-->
<!--              v-hasPermi="['erp:production-in:create']"-->
<!--            >-->
<!--              <Icon icon="ep:box" />-->
<!--            </el-button>-->
<!--          </el-tooltip>-->
          <el-tooltip content="删除" placement="top">
            <el-button
              link
              type="danger"
              @click="handleDelete([scope.row.id])"
              v-if="[0, 6].includes(scope.row.status)"
              v-hasPermi="['mes:production-order:delete']"
            >
<!--              <Icon icon="ep:delete" />-->
              删除
            </el-button>
          </el-tooltip>
          <el-tooltip content="工序执行" placement="top">
            <el-button
              link
              type="primary"
              @click="handleShowOperations(scope.row.id, scope.row.status)"
              v-hasPermi="['mes:production-order:operations']"
            >
<!--              <Icon icon="ep:list" />-->
              详情
            </el-button>
          </el-tooltip>
        </template>
      </el-table-column>
      </el-table>
      <!-- 分页 -->
      <Pagination
        :total="total"
        v-model:page="queryParams.pageNo"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
      />
    </ContentWrap>
  </template>

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

  <!-- 工序执行弹窗 -->
  <OperationExecutionDialog ref="operationExecutionRef" />

  <!-- 生产入库弹窗 -->
  <el-dialog v-model="inboundDialogVisible" title="生产入库" width="520px" append-to-body>
    <el-form label-width="120px">
      <el-form-item label="选择仓库">
        <el-select
          v-model="selectedWarehouseId"
          placeholder="请选择或输入仓库编号"
          filterable
          allow-create
          default-first-option
          clearable
          class="!w-320px"
        >
          <el-option
            v-for="w in warehouseOptions"
            :key="w.id"
            :label="w.name + '（' + w.id + '）'"
            :value="w.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="产品条码">
        <span>{{
          (currentInboundRow &&
            (currentInboundRow.productCode ||
              currentInboundRow.productBarCode ||
              currentInboundRow.barCode)) ||
          '-'
        }}</span>
      </el-form-item>
      <el-form-item label="入库数量">
        <span>{{
          (currentInboundRow &&
            (currentInboundRow.producedQuantity || currentInboundRow.planQuantity)) ||
          0
        }}</span>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="inboundDialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="inboundSubmitting" @click="confirmInbound"
          >确定</el-button
        >
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Filter, Plus } from '@element-plus/icons-vue'
import { Icon } from '@/components/Icon'
import WorkOrderForm from './WorkOrderForm.vue'
import OperationExecutionDialog from './components/OperationExecutionDialog.vue'
import { WarehouseApi } from '@/api/erp/stock/warehouse'
import {
  YVHgetWorkOrderPage,
  YVHdeleteWorkOrder,
  YVHstartWorkOrder,
  YVHcompleteWorkOrder,
  YVHcancelWorkOrder,
  YVHsubmitWorkOrder,
  YVHapproveWorkOrder,
  YVHrejectWorkOrder,
  YVHcloseWorkOrder
} from '@/api/mes/production/workorder'
import { YVHgetWorkOrderOperationList } from '@/api/mes/production/order-operation'
import request from '@/config/axios'
import { useWindowSize } from '@vueuse/core'

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

// 手机端筛选相关
const filterVisible = ref(false)
const quickFilterStatus = ref<number | undefined>(undefined)

// 隐藏旧的 ERP 入库逻辑，改为调用 MES 入库（按产品条码）接口

const loading = ref(true)
const total = ref(0)
const list = ref<any[]>([])
const queryFormRef = ref()
const formRef = ref()
const operationExecutionRef = ref()
const selectionList = ref<any[]>([])
// 入库弹窗相关
const inboundDialogVisible = ref(false)
const inboundSubmitting = ref(false)
const warehouseOptions = ref<Array<{ id: number; name: string }>>([])
const selectedWarehouseId = ref<string | number | undefined>(undefined)
const currentInboundRow = ref<any>(null)

const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  code: undefined,
  productName: undefined,
  status: [] as number[],
  planTime: [] as string[]
})

const getStatusType = (status: number) => {
  switch (status) {
    case 0: // 草稿
      return 'warning' // 橙色
    case 1: // 待审核
      return 'primary' // 蓝色
    case 2: // 已审核
      return 'success' // 绿色
    case 3: // 生产中
      return 'warning' // 浅蓝色
    case 4: // 已完成
      return 'success' // 绿色
    case 5: // 已关闭
      return 'danger' // 红色
    case 6: // 已取消
      return 'warning' // 橙色
    case 7: // 已入库
      return 'success' // 绿色
    default:
      return 'info'
  }
}

const getStatusText = (status: number) => {
  switch (status) {
    case 0:
      return '草稿'
    case 1:
      return '待审核'
    case 2:
      return '已审核'
    case 3:
      return '生产中'
    case 4:
      return '已完成'
    case 5:
      return '已关闭'
    case 6:
      return '已取消'
    case 7:
      return '已入库'
    default:
      return '未知'
  }
}

const getList = async () => {
  loading.value = true
  try {
    // 处理时间范围参数
    const params = {
      ...queryParams,
      planTime: queryParams.planTime
        ? queryParams.planTime.map((date: string, index: number) => {
            // 开始时间设置为当天 00:00:00，结束时间设置为当天 23:59:59
            return index === 0 ? `${date} 00:00:00` : `${date} 23:59:59`
          })
        : undefined
    }
    const res = await YVHgetWorkOrderPage(params)
    list.value = res.list
    total.value = res.total
  } finally {
    loading.value = false
  }
}

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

const resetQuery = () => {
  queryFormRef.value?.resetFields()
  queryParams.code = undefined
  queryParams.productName = undefined
  queryParams.status = []
  queryParams.planTime = []
  quickFilterStatus.value = undefined
  handleQuery()
}

/** 快捷筛选 */
const handleQuickFilter = (status: number | undefined) => {
  quickFilterStatus.value = status
  queryParams.status = status !== undefined ? [status] : []
  queryParams.pageNo = 1
  getList()
}

/** 筛选确认 */
const handleFilterConfirm = () => {
  filterVisible.value = false
  handleQuery()
}

/** 卡片点击 */
const handleCardClick = (row: any) => {
  handleShowOperations(row.id, row.status)
}

const openForm = (type: 'create' | 'update', id?: number) => {
  formRef.value.open(type, id)
}

const handleDelete = async (ids: number[]) => {
  if (!ids || ids.length === 0) return
  try {
    await ElMessageBox.confirm('确定要删除选中的工单吗？', '提示', { type: 'warning' })
    for (const id of ids) {
      await YVHdeleteWorkOrder(id)
    }
    ElMessage.success('删除成功')
    getList()
    selectionList.value = selectionList.value.filter((item) => !ids.includes(item.id))
  } catch {}
}

const handleStart = async (id: number) => {
  try {
    await ElMessageBox.confirm('确定要开始生产该工单吗？', '提示', { type: 'warning' })
    await YVHstartWorkOrder({ id })
    ElMessage.success('操作成功')
    getList()
  } catch {}
}

const handleComplete = async (row: any) => {
  try {
    const result = await ElMessageBox.prompt('请输入实际完成数量', '完成工单', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      inputType: 'number',
      inputValue: '',
      inputValidator: (value) => {
        if (value === undefined || value === null || String(value).trim() === '') {
          return '实际完成数量不能为空'
        }
        const num = Number(value)
        // if (!Number.isFinite(num) || !Number.isInteger(num)) {
        //   return '请输入整数'
        // }
        if (num < 0) {
          return '实际完成数量不能小于 0'
        }
        return true
      }
    })
    const producedQuantity = Number(result.value)
    await YVHcompleteWorkOrder({ id: row.id, producedQuantity })
    ElMessage.success('操作成功')
    getList()
  } catch {}
}

const handleCancel = async (id: number) => {
  try {
    await ElMessageBox.confirm('确定要取消该工单吗？', '提示', { type: 'warning' })
    await YVHcancelWorkOrder({ id })
    ElMessage.success('操作成功')
    getList()
  } catch {}
}

const handleSubmit = async (id: number) => {
  try {
    await ElMessageBox.confirm('确定要提交该工单审核吗？', '提示', { type: 'warning' })
    await YVHsubmitWorkOrder({ id })
    ElMessage.success('提交成功')
    getList()
  } catch {}
}

const handleApprove = async (id: number) => {
  try {
    await ElMessageBox.confirm('确定要审核通过该工单吗？', '提示', { type: 'warning' })
    await YVHapproveWorkOrder({ id })
    ElMessage.success('审核通过')
    getList()
  } catch {}
}

const handleReject = async (id: number) => {
  try {
    await ElMessageBox.confirm('确定要拒绝该工单吗？', '提示', { type: 'warning' })
    await YVHrejectWorkOrder({ id })
    ElMessage.success('已拒绝')
    getList()
  } catch {}
}

const handleClose = async (id: number) => {
  try {
    await ElMessageBox.confirm('确定要关闭该工单吗？', '提示', { type: 'warning' })
    await YVHcloseWorkOrder({ id })
    ElMessage.success('已关闭')
    getList()
  } catch {}
}

const handleProductionIn = async (row: any) => {
  try {
    currentInboundRow.value = row
    selectedWarehouseId.value = undefined
    // 加载仓库下拉
    const list = await WarehouseApi.getWarehouseSimpleList()
    warehouseOptions.value = Array.isArray(list) ? list : list?.data || []
    inboundDialogVisible.value = true
  } catch (error) {
    console.error('加载仓库列表失败:', error)
    // 即使加载失败，也允许用户手动输入
    inboundDialogVisible.value = true
  }
}

const confirmInbound = async () => {
  if (!currentInboundRow.value) return
  // 优先选择下拉的仓库ID，否则使用手动输入
  const chosenId = selectedWarehouseId.value
  const warehouseId = Number(chosenId)
  if (!Number.isInteger(warehouseId) || warehouseId <= 0) {
    ElMessage.error('请选择或输入合法的仓库编号')
    return
  }
  const barCode =
    currentInboundRow.value.productCode ||
    currentInboundRow.value.productBarCode ||
    currentInboundRow.value.barCode
  if (!barCode) {
    ElMessage.error('缺少产品条码，无法入库')
    return
  }
  const count = currentInboundRow.value.producedQuantity || currentInboundRow.value.planQuantity
  inboundSubmitting.value = true
  try {
    await request.post({
      url: '/mes/stock/inbound',
      data: {
        barCode,
        warehouseId,
        count,
        workOrderId: currentInboundRow.value.id
      }
    })
    ElMessage.success('入库成功')
    inboundDialogVisible.value = false
  } catch (error) {
    console.error('入库失败:', error)
    ElMessage.error('入库失败')
  } finally {
    inboundSubmitting.value = false
  }
}

const handleShowOperations = async (id: number, status: number) => {
  console.log('显示工序执行弹窗，工单ID:', id, '工单状态:', status)
  if (operationExecutionRef.value) {
    operationExecutionRef.value.open(id, status)
  } else {
    console.error('operationExecutionRef 未定义')
    ElMessage.error('无法打开工序执行弹窗')
  }
}

const handleSelectionChange = (selection: any[]) => {
  selectionList.value = selection
}

/** 行点击操作 */
const handleRowClick = (row: any, 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.status === 0) {
    openForm('update', row.id)
  } else {
    handleShowOperations(row.id, row.status)
  }
}

const formatDateTime = (time: string) => {
  if (!time) return ''
  return time.split('T')[0]
}

const formatFullDateTime = (time: string) => {
  if (!time) return ''
  return time.replace('T', ' ')
}

getList()
</script>

<style lang="scss" scoped>
.mobile-workorder-list {
  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-header__quick-filter {
  display: flex;
  gap: 12px;
  margin: 8px 0;
  justify-content: flex-start;

  .quick-filter-item {
    padding: 4px 12px;
    font-size: 14px;
    border-radius: 20px;
    cursor: pointer;
    color: #909399;
    background: transparent;
    transition: all 0.2s;

    &.active {
      color: #fff;
      background: #409eff;
    }
  }
}

.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;
    &--ellipsis { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; max-width: 200px; }
  }
  &__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>
