<!-- 库存明细选择组件 -->
<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="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="warehouseId">
          <el-select
            v-model="queryParams.warehouseId"
            clearable
            filterable
            placeholder="请选择仓库"
            class="!w-160px"
          >
            <el-option
              v-for="item in warehouseList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="业务单号" prop="bizNo">
          <el-input
            v-model="queryParams.bizNo"
            placeholder="请输入业务单号"
            clearable
            @keyup.enter="handleQuery"
            class="!w-160px"
          />
        </el-form-item>
        
        <!-- 质检过滤条件 -->
        <el-form-item label="RD值" prop="steviaRd">
          <el-select
            v-model="queryParams.steviaRd"
            clearable
            placeholder="请选择RD值"
            class="!w-120px"
          >
            <el-option label="85" :value="85" />
            <el-option label="90" :value="90" />
            <el-option label="95" :value="95" />
          </el-select>
        </el-form-item>
        <el-form-item label="PH值" prop="steviaPhValue">
          <el-select
            v-model="queryParams.steviaPhValue"
            clearable
            placeholder="请选择PH值"
            class="!w-120px"
          >
            <el-option label="6.0" :value="6.0" />
            <el-option label="6.5" :value="6.5" />
            <el-option label="7.0" :value="7.0" />
            <el-option label="7.5" :value="7.5" />
            <el-option label="8.0" :value="8.0" />
          </el-select>
        </el-form-item>
        <el-form-item label="RA值" prop="steviaRa">
          <el-select
            v-model="queryParams.steviaRa"
            clearable
            placeholder="请选择RA值"
            class="!w-120px"
          >
            <el-option label="85" :value="85" />
            <el-option label="90" :value="90" />
            <el-option label="95" :value="95" />
          </el-select>
        </el-form-item>
        <el-form-item label="STV值" prop="steviaStv">
          <el-select
            v-model="queryParams.steviaStv"
            clearable
            placeholder="请选择STV值"
            class="!w-120px"
          >
            <el-option label="1.0" :value="1.0" />
            <el-option label="2.0" :value="2.0" />
            <el-option label="3.0" :value="3.0" />
          </el-select>
        </el-form-item>
        <el-form-item label="RF值" prop="steviaRf">
          <el-select
            v-model="queryParams.steviaRf"
            clearable
            placeholder="请选择RF值"
            class="!w-120px"
          >
            <el-option label="0.5" :value="0.5" />
            <el-option label="1.0" :value="1.0" />
            <el-option label="1.5" :value="1.5" />
          </el-select>
        </el-form-item>
        <el-form-item label="RC值" prop="steviaRc">
          <el-select
            v-model="queryParams.steviaRc"
            clearable
            placeholder="请选择RC值"
            class="!w-120px"
          >
            <el-option label="0.5" :value="0.5" />
            <el-option label="1.0" :value="1.0" />
            <el-option label="1.5" :value="1.5" />
          </el-select>
        </el-form-item>
        <el-form-item label="DA值" prop="steviaDa">
          <el-select
            v-model="queryParams.steviaDa"
            clearable
            placeholder="请选择DA值"
            class="!w-120px"
          >
            <el-option label="0.5" :value="0.5" />
            <el-option label="1.0" :value="1.0" />
            <el-option label="1.5" :value="1.5" />
          </el-select>
        </el-form-item>
        <el-form-item label="RV值" prop="steviaRv">
          <el-select
            v-model="queryParams.steviaRv"
            clearable
            placeholder="请选择RV值"
            class="!w-120px"
          >
            <el-option label="0.5" :value="0.5" />
            <el-option label="1.0" :value="1.0" />
            <el-option label="1.5" :value="1.5" />
          </el-select>
        </el-form-item>
        <el-form-item label="RB值" prop="steviaRb">
          <el-select
            v-model="queryParams.steviaRb"
            clearable
            placeholder="请选择RB值"
            class="!w-120px"
          >
            <el-option label="0.5" :value="0.5" />
            <el-option label="1.0" :value="1.0" />
            <el-option label="1.5" :value="1.5" />
          </el-select>
        </el-form-item>
        <el-form-item label="SB值" prop="steviaSb">
          <el-select
            v-model="queryParams.steviaSb"
            clearable
            placeholder="请选择SB值"
            class="!w-120px"
          >
            <el-option label="0.5" :value="0.5" />
            <el-option label="1.0" :value="1.0" />
            <el-option label="1.5" :value="1.5" />
          </el-select>
        </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"
        @selection-change="handleSelectionChange"
        ref="tableRef"
      >
        <el-table-column width="30" label="选择" type="selection" :selectable="isSelectable" />
        <el-table-column label="产品名称" align="center" prop="productName" min-width="150" />
        <el-table-column label="仓库" align="center" prop="warehouseName" width="120" />
        <el-table-column label="业务单号" align="center" prop="bizNo" min-width="150" />
        <el-table-column label="数量" align="center" prop="count" :formatter="erpCountTableColumnFormatter" width="100" />
        <el-table-column label="创建时间" align="center" prop="createTime" :formatter="dateFormatter" width="150" />
        <el-table-column label="质检信息" align="center" width="120">
          <template #default="scope">
            <el-button 
              v-if="scope.row.bizItemId" 
              type="primary" 
              link 
              @click="viewQualityDetail(scope.row.bizItemId)"
            >
              查看质检
            </el-button>
            <span v-else class="text-gray-400">无质检信息</span>
          </template>
        </el-table-column>
        <el-table-column label="状态" align="center" width="100">
          <template #default="scope">
            <el-tag v-if="isAlreadySelected(scope.row)" type="success">已选择</el-tag>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <Pagination
        :total="total"
        v-model:page="queryParams.pageNo"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
      />
    </ContentWrap>
    <template #footer>
      <el-button :disabled="!selectionList.length" type="primary" @click="submitForm">
        确 定
      </el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
    
    <!-- 质检信息详情弹窗 -->
    <QualityDetailDialog ref="qualityDetailDialogRef" />
  </Dialog>
</template>
<script setup lang="ts">
import { formatDate } from '@/utils/formatTime'
import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'
import { erpCountTableColumnFormatter } from '@/utils'
import { ProductApi, ProductVO } from '@/api/erp/product/product'
import { StockRecordApi, StockRecordVO } from '@/api/erp/stock/record'
import { WarehouseApi, WarehouseVO } from '@/api/erp/stock/warehouse'
import { ErpBizType } from '@/utils/constants'
import request from '@/config/axios'
import QualityDetailDialog from './QualityDetailDialog.vue'

defineOptions({ name: 'StockRecordListForm' })

const list = ref<StockRecordVO[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const loading = ref(false) // 列表的加载中
const dialogVisible = ref(false) // 弹窗的是否展示
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  productId: undefined,
  warehouseId: undefined,
  bizNo: undefined,
  bizType: 90, // 修正为生产入库类型 90
  // 质检过滤条件
  steviaRd: undefined,
  steviaPhValue: undefined,
  steviaRa: undefined,
  steviaStv: undefined,
  steviaRf: undefined,
  steviaRc: undefined,
  steviaDa: undefined,
  steviaRv: undefined,
  steviaRb: undefined,
  steviaSb: undefined
})
const queryFormRef = ref() // 搜索的表单
const productList = ref<ProductVO[]>([]) // 产品列表
const warehouseList = ref<WarehouseVO[]>([]) // 仓库列表
const tableRef = ref() // 表格引用
const qualityDetailDialogRef = ref() // 质检详情弹窗引用

// 已选择的库存明细ID
const selectedStockRecordIds = ref<number[]>([])
// 已经在表单中选择的库存明细ID
const existingStockRecordIds = ref<number[]>([])

/** 选中操作 */
const selectionList = ref<StockRecordVO[]>([])
const handleSelectionChange = (rows: StockRecordVO[]) => {
  selectionList.value = rows
}

/** 判断记录是否已经被选择过 */
const isAlreadySelected = (row: StockRecordVO) => {
  return existingStockRecordIds.value.includes(row.id)
}

/** 判断记录是否可选 */
const isSelectable = (row: StockRecordVO) => {
  // 已经选择过的记录不可再选
  return !isAlreadySelected(row)
}

/** 查看质检详情 */
const viewQualityDetail = (qualityId: number) => {
  qualityDetailDialogRef.value?.open(qualityId)
}

/** 打开弹窗 */
const open = async (stockRecordIds?: number[]) => {
  dialogVisible.value = true
  await nextTick() // 等待，避免 queryFormRef 为空
  
  // 保存已选择的库存明细ID
  existingStockRecordIds.value = stockRecordIds || []
  
  // 清除查询条件，默认设置为生产入库类型
  queryParams.bizType = 90 // 生产入库类型
  queryParams.productId = undefined
  queryParams.warehouseId = undefined
  queryParams.bizNo = undefined
  // 清除质检过滤条件
  queryParams.steviaRd = undefined
  queryParams.steviaPhValue = undefined
  queryParams.steviaRa = undefined
  queryParams.steviaStv = undefined
  queryParams.steviaRf = undefined
  queryParams.steviaRc = undefined
  queryParams.steviaDa = undefined
  queryParams.steviaRv = undefined
  queryParams.steviaRb = undefined
  queryParams.steviaSb = undefined
  
  // 重置查询条件
  await resetQuery()
  
  // 加载产品列表
  productList.value = await ProductApi.getProductSimpleList()
  // 加载仓库列表
  warehouseList.value = await WarehouseApi.getWarehouseSimpleList()
  
  // 执行查询，获取所有类型的数据
  getList()
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交选择 */
const emits = defineEmits<{
  (e: 'success', value: StockRecordVO[]): void
}>()
const submitForm = () => {
  try {
    emits('success', selectionList.value)
  } finally {
    // 关闭弹窗
    dialogVisible.value = false
  }
}

/** 加载列表  */
const getList = async () => {
  loading.value = true
  try {
    console.log('查询参数:', JSON.stringify(queryParams)) // 使用JSON.stringify确保完整输出
    
    // 创建一个干净的查询参数对象，只包含必要的字段
    const cleanParams: any = {
      pageNo: queryParams.pageNo,
      pageSize: queryParams.pageSize,
      bizType: 90, // 强制设置为生产入库类型
      excludeAssociatedApproved: true // 排除已被已审核销售出库关联的记录
    }
    
    // 只添加有值的查询条件
    if (queryParams.productId) (cleanParams as any).productId = queryParams.productId
    if (queryParams.warehouseId) (cleanParams as any).warehouseId = queryParams.warehouseId
    if (queryParams.bizNo) (cleanParams as any).bizNo = queryParams.bizNo
    
    // 添加质检过滤条件
    if (queryParams.steviaRd) (cleanParams as any).steviaRd = queryParams.steviaRd
    if (queryParams.steviaPhValue) (cleanParams as any).steviaPhValue = queryParams.steviaPhValue
    if (queryParams.steviaRa) (cleanParams as any).steviaRa = queryParams.steviaRa
    if (queryParams.steviaStv) (cleanParams as any).steviaStv = queryParams.steviaStv
    if (queryParams.steviaRf) (cleanParams as any).steviaRf = queryParams.steviaRf
    if (queryParams.steviaRc) (cleanParams as any).steviaRc = queryParams.steviaRc
    if (queryParams.steviaDa) (cleanParams as any).steviaDa = queryParams.steviaDa
    if (queryParams.steviaRv) (cleanParams as any).steviaRv = queryParams.steviaRv
    if (queryParams.steviaRb) (cleanParams as any).steviaRb = queryParams.steviaRb
    if (queryParams.steviaSb) (cleanParams as any).steviaSb = queryParams.steviaSb
    
    console.log('清理后的查询参数:', JSON.stringify(cleanParams))
    
    try {
      // 使用API查询
      const data = await StockRecordApi.getStockRecordPage(cleanParams)
      console.log('查询结果:', JSON.stringify(data))
      
      // 补充可能缺失的字段
      if (data.list && data.list.length > 0) {
        data.list.forEach(item => {
          if (!item.productName && item.productId) {
            const product = productList.value.find(p => p.id === item.productId)
            if (product) {
              item.productName = product.name
            }
          }
          if (!item.warehouseName && item.warehouseId) {
            const warehouse = warehouseList.value.find(w => w.id === item.warehouseId)
            if (warehouse) {
              item.warehouseName = warehouse.name
            }
          }
        })
      }
      
      list.value = data.list || []
      total.value = data.total || 0
    } catch (apiError) {
      console.error('API查询出错:', apiError)
      list.value = []
      total.value = 0
    }
    
    // 设置已选择的行为选中状态
    nextTick(() => {
      // 清空已选择的行
      selectionList.value = []
      
      // 设置已选择的行为选中状态
      list.value.forEach(row => {
        if (existingStockRecordIds.value.includes(row.id)) {
          // 已经选择过的记录不再自动选中
          // tableRef.value?.toggleRowSelection(row, true)
        }
      })
    })
  } catch (error) {
    console.error('查询出错:', error)
    list.value = []
    total.value = 0
  } finally {
    loading.value = false
  }
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields()
  // 不再强制设置bizType
  handleQuery()
}

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

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

<style scoped>
.mx-2 {
  margin-left: 8px;
  margin-right: 8px;
}

.text-gray-400 {
  color: #9ca3af;
}
</style> 