<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="projectCode">
          <el-input v-model="queryParams.projectCode" placeholder="请输入项目编号" clearable @keyup.enter="handleQuery" class="!w-240px" />
        </el-form-item>
        <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="customerName">
          <el-input
            v-model="queryParams.customerName"
            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="materialName">
          <el-input v-model="queryParams.materialName" placeholder="请输入零件名称" clearable @keyup.enter="handleQuery" class="!w-240px" />
        </el-form-item>
        <el-form-item label="图号" prop="blueprintNo">
          <el-input v-model="queryParams.blueprintNo" placeholder="请输入图号" clearable @keyup.enter="handleQuery" class="!w-240px" />
        </el-form-item>
        <el-form-item label="工序" prop="procedureName">
          <el-input v-model="queryParams.procedureName" placeholder="请输入工序" clearable @keyup.enter="handleQuery" class="!w-240px" />
        </el-form-item>
        <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="status">
          <el-select v-model="queryParams.status" placeholder="请选择采购状态" clearable class="!w-240px">
            <el-option v-for="dict in getIntDictOptions(DICT_TYPE.HELI_PURCHASE_STATUS)" :key="dict.value" :label="dict.label" :value="dict.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="责任人" prop="ownerName">
          <el-input v-model="queryParams.ownerName" placeholder="请输入责任人" clearable @keyup.enter="handleQuery" class="!w-240px"/>
        </el-form-item>

        <el-form-item style="margin-left:30px">
          <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="handleExportDetail"
            :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: 18px" @click="singleSubmissions()" type="success"  size="large">订单生成</el-button>
        <el-button  style="margin-left: 18px" @click="routerToPurchaseOrderNo()" type="success"  size="large">零件采购订单管理</el-button>
      </template>
      <el-row>
        <el-col>
          <el-card class="hl-incard">
            <el-form  ref="multipleTable" :model="list"  v-loading="formLoading" label-width="0" >
              <el-table v-loading="loading" :data="list" :show-overflow-tooltip="true"  class="hl-table" @selection-change="handleSelectionChange">
                <el-table-column type="selection" width="55" />
                <el-table-column fixed label="序号" align="center" type="index" width="60" />
                <el-table-column label="子项目编码" align="center" prop="projectSubCode" min-width="180" />
                <el-table-column label="工序" align="center" prop="procedureName" min-width="100" />
                <el-table-column label="零件名称" align="center" prop="boomName" min-width="180" />
                <el-table-column label="材质" align="center" prop="composition" min-width="120" />
                <el-table-column label="采购数量" align="center" prop="purchaseAmount" min-width="120" />
                <el-table-column label="计划到货日期" align="center" prop="arriveTime" :formatter="dateFormatter1" min-width="120" />
                <el-table-column label="供应商" align="center" prop="supplierName" min-width="180" />
                <el-table-column label="技术要求" align="center" prop="description" min-width="180" />
                <el-table-column label="理论重量" align="center" prop="theWeight" min-width="100" />
                <el-table-column label="价格" align="center" prop="estimatedPrice" min-width="100" />
                <el-table-column label="订单状态" align="center" prop="orderStatus" min-width="100" >
                  <template #default="scope">
                    {{
                      getIntDictOptions(DICT_TYPE.HELI_PURCHASE_STATUS).find(
                          (dict) => dict.value === scope.row.orderStatus
                      )?.label || '未知状态'
                    }}
                  </template>
                </el-table-column>
                <el-table-column label="采购订单号" align="center" prop="purchaseNo" min-width="180" />
                <el-table-column label="责任人" align="center" prop="duEmpName" min-width="100" />
              </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 { useCommonStateWithOut } from '@/store/modules/common'
import UserSelect from "@/views/heli/materialplan/userSelectNew.vue";
import {inject, ref} from "vue";
import * as MaterialPlanApi from "@/api/heli/materialplan";
import * as PartPurchaseOrderApi from "@/api/heli/partpurchaseorder";
import {ElTable} from "element-plus";
import {useUserStore} from "@/store/modules/user";
import {dateFormatter1} from "@/utils/formatTime";
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用

defineOptions({ name: 'PartPurchaseOrder' })
const userStore = useUserStore()
const username = userStore.getUser.nickname
const reload: any = inject('reload')
const commonStore = useCommonStateWithOut()
const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化
const router = useRouter()
const multipleTable = ref<InstanceType<typeof ElTable>>()
const multipleSelection = ref([])
const loading = ref(true) // 列表的加载中
const list = ref([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  code: undefined,
  planCode: undefined,
  projectCode: undefined,
  projectSubCode: undefined,
  customerName: undefined,
  projectName: undefined,
  projectSubName: undefined,
  version: undefined,
  bomStatus: undefined,
  remark: undefined,
  status: 1,
  createTime: [],
  ownerName:username,
  materialName:undefined,
  projectMaterialPlanNo:undefined,
  supplierName:undefined,
  blueprintNo:undefined,
  procedureName:undefined
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await PartPurchaseOrderApi.getPartPage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}
/** 导出按钮操作 */
const handleExportDetail = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await MaterialPlanApi.exportPart(queryParams)
    download.excel(data, '零件物料需求计划.xlsx')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

const handleSelectionChange = (val) => {
  // multipleTable.value.clearSelection()
  multipleTable.value=val

}
/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}
const handleSelectedUser = (currentIndex, newValue: any) => {
  list.value[currentIndex].duEmpId = newValue?.id
}
const singleSubmission= (val) =>{
  multipleTable.value=[]
  multipleTable.value.push(val)
  submitForm();
}
const routerToPurchaseOrderNo=()=>{
  router.push({ path: '/purchase/purchaseorderno'});
}
const singleSubmissions=()=>{
  submitForm();
}
const submitForm = async () => {
  try {
    console.log("开始提交"); // 调试点1：确认函数是否触发

    const list = multipleTable.value|| []; // 安全获取数据
    console.log("明细数据:", list);
    console.log(list.length)
    // 1. 检查空数据
    if (!list || list.length==null) {
      message.error("提交明细不能为空，请确认");
      return;
    }

    // 2. 检查供应商一致性
    const firstSupplierId = list[0].supplierId;
    console.log(firstSupplierId)
    list.forEach((item, index) => {
      console.log(`第${index}个:`, item.supplierId, '类型:', typeof item.supplierId, '相等:', item.supplierId === firstSupplierId);
    });
    if (list.some(item => item.supplierId !== firstSupplierId)) {
      message.error("零件采购订单不属于同一个供应商，请确认");
      return;
    }

    // // 3. 校验每个零件
    for (const item of list) {
      if (item.orderStatus==2) {
        message.error(`工序${item.procedureName}中零件 ${item.boomName} 已生成采购订单,请确认`);
        return;
      }

    }

    // 4. 添加加载状态（Element Plus 兼容处理）
    formLoading.value = true;

    // 5. 提交数据（添加超时处理）
    const res = await Promise.race([
      PartPurchaseOrderApi.submitForm(list),
      new Promise((_, reject) =>
        setTimeout(() => reject(new Error("请求超时")), 30000)
      )
    ]);

    message.success("提交成功");
    // getList(); // 确保刷新完成
    emit('success');


  } catch (error) {
    console.error("提交失败:", error);
    // message.error(`操作失败: ${error.message || "未知错误"}`);
  } finally {
    formLoading.value = false;
    getList(); // 确保刷新完成
  }
}
const withdraw = async () => {
  if (queryParams.projectMaterialPlanNo==null){
    message.error("物料需求单号为空,不允许撤回")
    return

  }
  await MaterialPlanApi.withdraw(queryParams.projectMaterialPlanNo)
  message.success("撤回成功")
  // 发送操作成功的事件
  getList()
  emit('success')

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

/** 初始化 **/
onMounted(() => {
  getList()
})
</script>
<style>
/* 占位样式 */
</style>
