<template>
  <el-card class="hl-card">
    <template #header>
      <span>标准件收货</span>
    </template>
    <ContentWrap class="borderxx">
      <!-- 搜索工作栏 -->
      <el-form class="-mb-15px" :model="queryParams" ref="queryFormRef" :inline="true" label-width="120px">
        <el-form-item label="项目名称" prop="projectName">
          <el-input
            v-model="queryParams.projectName" placeholder="项目名称" clearable @keyup.enter="handleQuery"
            class="!w-240px" />
        </el-form-item>
        <el-form-item label="子项目名称" prop="projectSubName">
          <el-input
            v-model="queryParams.projectSubName" placeholder="子项目名称" clearable @keyup.enter="handleQuery"
            class="!w-240px" />
        </el-form-item>
        <el-form-item label="零件名称" prop="boomName">
          <el-input
            v-model="queryParams.boomName" placeholder="零件名称" clearable @keyup.enter="handleQuery"
            class="!w-240px" />
        </el-form-item>
        <el-form-item label="项目编码" prop="projectCode">
          <el-input
            v-model="queryParams.projectCode" placeholder="项目编码" clearable @keyup.enter="handleQuery"
            class="!w-240px" />
        </el-form-item>

        <el-form-item label="订单状态" prop="receivingStatus">
          <el-select v-model="queryParams.receivingStatus" placeholder="下拉选择" clearable class="!w-240px">
            <el-option
              v-for="dict in getIntDictOptions(DICT_TYPE.HELI_PURCHASE_RECEIVING_STATUS)" :key="dict.value"
              :label="dict.label" :value="dict.value" />
          </el-select>
        </el-form-item>
        <el-form-item style="margin-left:50px">
          <el-button @click="handleQuery" type="primary">
            <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="success"
            plain
            @click="handleExport"
            :loading="exportLoading"
          >
            <Icon icon="ep:download" class="mr-5px" /> 导出
          </el-button>
        </el-form-item>
      </el-form>
    </ContentWrap>

    <!-- 列表 -->
    <el-card class="hl-card-info">
      <template #header>
        <div class="hl-card-info-icona"></div><span class="hl-card-info-text">订单明细</span>
        <el-button  style="margin-left: 20px" @click="standardPartsReceived" type="success"  size="large">收货</el-button>
        <el-button  style="margin-left: 20px"  type="primary" @click="jump" size="large">入库单管理</el-button>
      </template>
      <el-row>
        <el-col>
          <el-card class="hl-incard">
            <el-form ref="subFormRef" :model="list"  v-loading="formLoading" label-width="0" >
      <el-table
v-loading="loading" :data="list" :stripe="true" :show-overflow-tooltip="true" class="hl-table" ref="multipleTable" @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />

        <el-table-column fixed label="序号" type="index" align="center" width="60" />
<!--        <el-table-column label="id" align="center" min-width="180" prop="id"  />-->

        <el-table-column label="子项目编码" align="center" min-width="180" prop="projectSubCode"  />
        <el-table-column label="物料编码" align="center" min-width="120" prop="matCode"  />
        <el-table-column label="标准件名称" align="center" min-width="150" prop="boomName"  />
        <el-table-column label="规格型号" align="center" min-width="120" prop="boomSpec"  />
        <el-table-column label="需求数量" align="center" min-width="100" prop="boomAmount"  />
        <el-table-column label="采购数量" align="center" min-width="100" prop="purchaseAmount"  />
        <el-table-column label="剩余数量" align="center" min-width="100" prop="purchaseRemAmount"  />
        <el-table-column prop="purchaseRemAmounts" min-width="180" align="center">
          <template #header><span class="hl-table_header">*</span>入库数量</template>
          <template #default="scope">
            <el-form-item :prop="`${scope.$index}.purchaseRemAmounts`"  class="mb-0px!">
              <el-input-number style="width: 100%" v-model="scope.row.purchaseRemAmounts" placeholder="入库数量"  :min="0" :precision="2"  />
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column min-width="200px" align="center" >
          <template #header>到货日期</template>
          <template #default="{ row, $index }">
            <el-form-item :prop="`${$index}.boomArriveDates`" class="mb-0px!" >
              <el-date-picker  class="!w-265px" v-model="row.boomArriveDates" type="date"  value-format="x" placeholder="到货日期" />
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column label="需求完成时间" align="center" prop="requireTime" :formatter="dateFormatter2" min-width="180" />
        <el-table-column label="计划到货日期" align="center" prop="arriveTime" :formatter="dateFormatter2" min-width="180" />
        <el-table-column label="供应商" align="center" min-width="180" prop="supplierName"  />
        <el-table-column label="价格" align="center" min-width="100" prop="estimatedPrice"  />
        <el-table-column label="订单状态" align="center" prop="receivingStatus"  min-width="100">
          <template #default="scope">
            <dict-tag :type="DICT_TYPE.HELI_PURCHASE_RECEIVING_STATUS" :value="scope.row.receivingStatus" />
          </template>
        </el-table-column>
        <el-table-column label="采购订单号" align="center" min-width="180" prop="purchaseNo"  />

        <el-table-column label="操作" align="center" fixed="right" min-width="110">
          <template #header>
            <span style="margin-right: 30%">操作</span>
          </template>
          <template #default="scope">
            <el-button link type="primary" @click="warehousing(scope.row.id)" v-if="scope.row.purchaseAmount>scope.row.boomAmount">
              采购入库
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <Pagination
:total="total" v-model:page="queryParams.pageNo" v-model:limit="queryParams.pageSize"
        @pagination="getList" />
            </el-form>
          </el-card>
        </el-col>
      </el-row>
    </el-card>
  </el-card>
</template>

<script setup lang="ts">
import { getIntDictOptions, DICT_TYPE } from '@/utils/dict'
import download from '@/utils/download'
import * as PurchaseOrderNoDetailApi from '@/api/heli/purchaseordernodetail'
import * as StorageinApi from '@/api/heli/storagein'
import { ElTable } from 'element-plus'
import {ref} from "vue";
import {dateFormatter2} from "@/utils/formatTime";
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
defineOptions({ name: 'PurchaseOrder' })
const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化
const router = useRouter()
const loading = ref(true) // 列表的加载中
const list = ref([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  id: undefined,
  ids: undefined,
  purchaseNo: undefined,
  supplierId: undefined,
  contractNo: undefined,
  purchaseType: undefined,
  projectMaterialPlanId: undefined,
  goodsType: 1,
  currencyType: undefined,
  taxRatio: undefined,
  estimatedPrice: undefined,
  actualPrice: undefined,
  status: undefined,
  submitUserId: undefined,
  submitTime: [],
  auditor: undefined,
  auditTime: [],
  description: undefined,
  creator: undefined,
  createTime: undefined,
  receivingStatus:1,
  projectName:undefined,
  projectSubName:undefined,
  supplierName:undefined,
  boomName:undefined,
  projectCode:undefined
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中
const multipleTable = ref<InstanceType<typeof ElTable>>()

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    queryParams.ids = undefined
    const data = await PurchaseOrderNoDetailApi.received(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}
const handleSelectionChange = (val) => {
  multipleTable.value=val

}
/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}
const jump = async () => {
  router.push({ path: '/inventory/storagein' })
}
/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}
const multipleSelection: any = ref([])



const warehousing = async (id) => {
  await StorageinApi.warehousing(id)
  message.success("采购入库成功")
  await getList()
}
const standardPartsReceived = async () => {
  const list = multipleTable.value|| []; // 安全获取数据

  // 1. 检查空数据
  if (!list || list.length==null) {
    message.error("提交明细不能为空，请确认");
    return;
  }
  for (let i = 0; i < list.length; i++) {
    if (list[i].purchaseRemAmounts==null||list[i].purchaseRemAmounts==0){
      message.error("标准件"+list[i].boomName+"入库数量为空或数量为0,请确认")
      return
    }
  }
  try {
    await StorageinApi.standardPartsReceived(list)
    formLoading.value = true
    message.success("收货成功")
    // 发送操作成功的事件
    getList()
    emit('success')
  } finally {
    formLoading.value = false
  }
}


/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await PurchaseOrderNoDetailApi.exportReceived(queryParams)
    download.excel(data, '标准件收货.xlsx')
  } catch {
  } finally {
    exportLoading.value = false
  }
}
/** 初始化 **/
onMounted( () => {
   getList()
})
</script>
