<!-- 可关联的生产入库单列表 -->
<template>
  <Dialog
    title="选择生产入库（仅展示已审核）"
    v-model="dialogVisible"
    :appendToBody="true"
    :scroll="true"
    width="1080"
  >
    <ContentWrap>
      <!-- 搜索工作栏 -->
      <el-form
        class="-mb-15px"
        :model="queryParams"
        ref="queryFormRef"
        :inline="true"
        label-width="68px"
      >
        <el-form-item label="入库单号" prop="no">
          <el-input
            v-model="queryParams.no"
            placeholder="请输入入库单号"
            clearable
            @keyup.enter="handleQuery"
            class="!w-160px"
          />
        </el-form-item>
        <el-form-item label="产品" prop="productId">
          <el-select
            v-model="queryParams.productId"
            clearable
            filterable
            placeholder="请选择产品"
            class="!w-160px"
          >
            <el-option
              v-for="item in productList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="入库时间" prop="inTime">
          <el-date-picker
            v-model="queryParams.inTime"
            value-format="YYYY-MM-DD HH:mm:ss"
            type="daterange"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
            class="!w-160px"
          />
        </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-form-item>
      </el-form>
    </ContentWrap>

    <ContentWrap>
      <el-table
        v-loading="loading"
        :data="list"
        :show-overflow-tooltip="true"
        :stripe="true"
        @row-click="handleRowClick"
      >
        <el-table-column min-width="180" label="入库单号" align="center" prop="no" />
        <el-table-column label="仓库" align="center" prop="warehouseName" />
        <el-table-column label="产品信息" align="center" prop="productNames" min-width="200" />
        <el-table-column
          label="入库时间"
          align="center"
          prop="inTime"
          :formatter="dateFormatter"
          width="120px"
        />
        <el-table-column label="创建人" align="center" prop="creator" />
        <el-table-column
          label="合计数量"
          align="center"
          prop="totalCount"
          :formatter="erpCountTableColumnFormatter"
        />
        <el-table-column
          label="合计金额"
          align="center"
          prop="totalPrice"
          :formatter="erpPriceTableColumnFormatter"
        />
      </el-table>
      <!-- 分页 -->
      <Pagination
        :total="total"
        v-model:page="queryParams.pageNo"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
      />
    </ContentWrap>
    
    <!-- 选择产品明细弹窗 -->
    <Dialog
      v-model="itemDialogVisible"
      title="选择产品明细"
      width="800"
      :append-to-body="true"
      :destroy-on-close="true"
    >
      <el-table
        v-loading="itemLoading"
        :data="itemList"
        :show-overflow-tooltip="true"
        :stripe="true"
        @selection-change="handleItemSelectionChange"
      >
        <el-table-column width="30" label="选择" type="selection" />
        <el-table-column label="产品名称" align="center" prop="productName" min-width="150" />
        <el-table-column label="单位" align="center" prop="productUnitName" width="80" />
        <el-table-column label="数量" align="center" prop="count" :formatter="erpCountTableColumnFormatter" />
        <el-table-column label="单价" align="center" prop="productPrice" :formatter="erpPriceTableColumnFormatter" />
        <el-table-column label="金额" align="center" prop="totalPrice" :formatter="erpPriceTableColumnFormatter" />
      </el-table>
      <template #footer>
        <el-button :disabled="!selectedItems.length" type="primary" @click="confirmSelectItems">
          确 定
        </el-button>
        <el-button @click="itemDialogVisible = false">取 消</el-button>
      </template>
    </Dialog>
  </Dialog>
</template>
<script lang="ts" setup>
import { formatDate } from '@/utils/formatTime'
import { erpCountTableColumnFormatter, erpPriceTableColumnFormatter } from '@/utils'
import { ProductApi, ProductVO } from '@/api/erp/product/product'
import { ProductionInApi, ProductionInVO, ProductionInItemVO } from '@/api/erp/production/in'

defineOptions({ name: 'ProductionInEnableList' })

const list = ref<ProductionInVO[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const loading = ref(false) // 列表的加载中
const dialogVisible = ref(false) // 弹窗的是否展示
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  no: undefined,
  productId: undefined,
  inTime: [],
  status: 20 // 已审核状态
})
const queryFormRef = ref() // 搜索的表单
const productList = ref<ProductVO[]>([]) // 产品列表

// 明细相关
const itemDialogVisible = ref(false)
const itemLoading = ref(false)
const itemList = ref<ProductionInItemVO[]>([])
const selectedItems = ref<ProductionInItemVO[]>([])
const currentProductionIn = ref<ProductionInVO | null>(null)

// 处理行点击事件
const handleRowClick = async (row: ProductionInVO) => {
  currentProductionIn.value = row
  itemDialogVisible.value = true
  itemLoading.value = true
  try {
    if (row.id) {
      const data = await ProductionInApi.getProductionIn(row.id)
      itemList.value = data.items || []
    }
  } finally {
    itemLoading.value = false
  }
}

// 处理明细选择变化
const handleItemSelectionChange = (selection: ProductionInItemVO[]) => {
  selectedItems.value = selection
}

// 确认选择明细
const confirmSelectItems = () => {
  if (selectedItems.value.length === 0 || !currentProductionIn.value) {
    return
  }
  emits('success', selectedItems.value, currentProductionIn.value)
  itemDialogVisible.value = false
  dialogVisible.value = false
}

/** 打开弹窗 */
const open = async () => {
  dialogVisible.value = true
  await nextTick() // 等待，避免 queryFormRef 为空
  // 重置查询条件
  await resetQuery()
  // 加载产品列表
  productList.value = await ProductApi.getProductSimpleList()
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交选择 */
const emits = defineEmits<{
  (e: 'success', items: ProductionInItemVO[], productionIn: ProductionInVO): void
}>()

/** 加载列表  */
const getList = async () => {
  loading.value = true
  try {
    const data = await ProductionInApi.getProductionInPage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

// 日期格式化
const dateFormatter = (row, column, cellValue) => {
  return formatDate(cellValue)
}
</script> 