<script setup lang="ts">
import { defineEmits, h, onMounted, ref, watch } from 'vue';
import { NIcon } from 'naive-ui';
import { CheckmarkDoneCircleOutline as CheckIcon } from '@vicons/ionicons5';
import { fetchGetLybRemainderNumber, fetchGetTaskDetailItem } from '@/service/api/taskmg';
import inIcon from '@/assets/imgs/入库.png';
import outIcon from '@/assets/imgs/出库.png';
// ✅ 正确接收 props
const props = defineProps<{
  taskData: Api.PlanManage.TaskDetails;
}>();
const emit = defineEmits<{
  (e: 'submitted'): void;
}>();

const checkIcon = () => {
  return h(NIcon, null, {
    default: () => h(CheckIcon)
  });
};
const formatTaskStatus = (status: number | null) => {
  if (status === null) return '未知';
  switch (status) {
    case 0:
      return '待执行';
    case 1:
      return '执行中';
    case 2:
      return '已完成';
    case 3:
      return '异常';
    default:
      return '未知';
  }
};
const CloseTaskDetail = () => {
  emit('submitted'); // 通知父组件关闭
};

const formatTaskType = (type: number | null) => {
  if (type === null) return '未知';
  switch (type) {
    case 1:
      return '入库';
    case 2:
      return '出库';
    case 3:
      return '盘库';
    default:
      return '未知';
  }
};
const taskData_Chidl = ref<Api.PlanManage.TaskDetailItem[]>([]);
async function GetTaskDetailItem() {
  const datas = await fetchGetTaskDetailItem({ TaskNo: props.taskData.TaskID });
  taskData_Chidl.value = datas.data?.data ?? [];
}
// 使用一个 Map 或对象来存储每个 OrderLineNumber 对应的 lybNumber
const lybNumbers = ref<{ [key: string]: string }>({});
// 获取当前履约订单剩余数量
async function GetLybNumber(OrderLineNumber: string) {
  const datas = await fetchGetLybRemainderNumber({ TaskNo: OrderLineNumber });
  return datas.data?.data;
}

onMounted(async () => {
  if (props.taskData) {
    await GetTaskDetailItem();

    // 使用 Promise.all 并行处理异步请求
    const promises = taskData_Chidl.value.map(async item => {
      const lybNumber = await GetLybNumber(item.OrderLineNumber);
      if (lybNumber === undefined || lybNumber === null || lybNumber === 0) {
        // 如果是空、0 或 undefined，则赋空字符串
        lybNumbers.value[item.OrderLineNumber] = '当前履约订单已全部制定入库计划';
      } else {
        // 否则转换为字符串
        lybNumbers.value[item.OrderLineNumber] = `当前履约订单剩余 ${lybNumber} 未制定入库计划`;
      }
    });

    // 等待所有异步操作完成
    await Promise.all(promises);
  }
});

watch(
  () => props.taskData,
  newVal => {
    if (newVal) {
      GetTaskDetailItem();
    }
  },
  { immediate: false, deep: true }
);
</script>

<template>
  <div class="min-h-500px flex-col-stretch gap-16px overflow-hidden lt-sm:overflow-auto">
    <NCard :bordered="false" size="small" class="card-wrapper">
      <NPageHeader>
        <template #title>
          <a class="asize">{{ formatTaskType(taskData.TaskType) }}任务作业明细</a>
        </template>
        <template #avatar>
          <NAvatar v-if="taskData.TaskType === 1" class="avatars" :src="inIcon" />
          <NAvatar v-if="taskData.TaskType === 2" class="avatars" :src="outIcon" />
        </template>
        <template #extra>
          <NSpace>
            <NButton strong :render-icon="checkIcon" size="medium" @click="CloseTaskDetail">返回</NButton>
          </NSpace>
        </template>
      </NPageHeader>
      <div>
        <p class="data-row">
          <span>
            <span class="task-quantity">任务ID:</span>
            {{ taskData.TaskID }}
          </span>
          <span>
            <span class="task-quantity">托盘号:</span>
            {{ taskData.PalletNo }}
          </span>
          <span>
            <span class="task-quantity">RFID编号:</span>
            {{ taskData.RFID }}
          </span>
          <span>
            <span class="task-quantity">起点位置:</span>
            {{ taskData.SourceLocation }}
          </span>
          <span>
            <span class="task-quantity">终点位置:</span>
            {{ taskData.TargetLocation }}
          </span>
        </p>

        <p class="data-row data-row2">
          <span>
            <span class="task-quantity">任务数量:</span>
            {{ taskData.TaskQty }}
          </span>
          <span>
            <span class="task-quantity">任务状态:</span>
            {{ formatTaskStatus(taskData.TaskStatus) }}
          </span>
          <span>
            <span class="task-quantity">任务类型:</span>
            {{ formatTaskType(taskData.TaskType) }}
          </span>
          <span>
            <span class="task-quantity">创建用户:</span>
            {{ taskData.CreateUser }}
          </span>
          <span>
            <span class="task-quantity">创建时间:</span>
            {{ taskData.CreateTime }}
          </span>
        </p>
      </div>
    </NCard>

    <NInfiniteScroll :distance="110">
      <NCard v-for="item in taskData_Chidl" :key="item.DetailID" class="item">
        <NPageHeader>
          <template #title>
            <div class="extra-container">
              <NAvatar v-if="taskData.TaskType === 1" class="avatars" :src="inIcon" />
              <a v-if="taskData.TaskType === 1">{{ lybNumbers[item.OrderLineNumber] }}</a>
              <a v-if="taskData.TaskType === 2">
                当前履约订单出库数量 : {{ taskData.TaskQty }} -- 回库数量 :
                {{ (item.OrderQuantity as number) - taskData.TaskQty }}
              </a>
            </div>
          </template>
        </NPageHeader>
        <div>
          <p class="data-row">
            <span>
              <span class="task-quantity">订单号+行号:</span>
              {{ item.OrderLineNumber }}
            </span>
            <span>
              <span class="task-quantity">采购订单号:</span>
              {{ item.PurchaseOrderNumber }}
            </span>
            <span>
              <span class="task-quantity">采购订单行项目号:</span>
              {{ item.PurchaseOrderLineItem }}
            </span>
            <span>
              <span class="task-quantity">采购申请号:</span>
              {{ item.PurchaseRequestNumber }}
            </span>
            <span>
              <span class="task-quantity">物资类型:</span>
              {{ item.MaterialType }}
            </span>
          </p>
          <p class="data-row">
            <span>
              <span class="task-quantity">项目名称:</span>
              {{ item.ProjectName }}
            </span>
            <span>
              <span class="task-quantity">物料编码:</span>
              {{ item.MaterialCode }}
            </span>
            <span>
              <span class="task-quantity">物资名称:</span>
              {{ item.MaterialName }}
            </span>
            <span v-if="taskData.TaskType === 1">
              <span class="task-quantity">订单数量:</span>
              {{ item.OrderQuantity }}
            </span>
            <span v-if="taskData.TaskType === 2">
              <span class="task-quantity">当前托盘库存数量:</span>
              {{ item.OrderQuantity }}
            </span>
            <span>
              <span class="task-quantity">物料单位:</span>
              {{ item.MaterialUnit }}
            </span>
          </p>
          <p class="data-row">
            <span>
              <span class="task-quantity">供应商名称:</span>
              {{ item.SupplierName }}
            </span>
            <span>
              <span class="task-quantity">采购订单计划交货日期:</span>
              {{ item.PlannedDeliveryDate }}
            </span>
            <span>
              <span class="task-quantity">ERP系统工厂:</span>
              {{ item.ERPSystemFactory }}
            </span>
            <span>
              <span class="task-quantity">项目编码:</span>
              {{ item.ProjectCode }}
            </span>
            <span>
              <span class="task-quantity">签约单价(不含税):</span>
              {{ item.ContractUnitPrice }}
            </span>
          </p>
          <p class="data-row">
            <span>
              <span class="task-quantity">签约总价(不含税):</span>
              {{ item.ContractTotalPrice }}
            </span>
            <span>
              <span class="task-quantity">项目类型:</span>
              {{ item.ProjectType }}
            </span>
            <span>
              <span class="task-quantity">采购方式:</span>
              {{ item.ProcurementMethod }}
            </span>
            <span>
              <span class="task-quantity">大类:</span>
              {{ item.MajorCategory }}
            </span>
            <span>
              <span class="task-quantity">中类:</span>
              {{ item.MiddleCategory }}
            </span>
          </p>
          <p class="data-row data-row2">
            <span>
              <span class="task-quantity">小类:</span>
              {{ item.SubCategory }}
            </span>
            <span>
              <span class="task-quantity">RFID条码:</span>
              {{ item.RFIDCode }}
            </span>
            <span>
              <span class="task-quantity">库存单位:</span>
              {{ item.StockUnit }}
            </span>
            <span></span>
            <span></span>
          </p>
        </div>
      </NCard>
    </NInfiniteScroll>
  </div>
</template>

<style scoped>
.data-row {
  display: flex;
  gap: 10px; /* 控制间距 */
  margin-top: 2vh;
}
.data-row span {
  flex: 1 1 20%; /* 平分宽度，给每个 span 设置相同的宽度，确保每个 span 占 20% */
  box-sizing: border-box;
}
.task-quantity {
  color: #868686;
  margin-right: 10px;
}
.data-row2 {
  margin-bottom: 1vh;
}
.avatars {
  background-color: transparent;
}
.item {
  margin-bottom: 10px;
}
.extra-container {
  display: flex;
  align-items: center; /* 垂直居中对齐 */
  gap: 10px; /* 控制间距，可以根据需要调整 */
}
.extra-container a {
  font-size: 18px; /* 根据需要调整文字大小 */
  font-weight: bold; /* 设置为粗体 */
}

.asize {
  font-size: 18px; /* 根据需要调整文字大小 */
  font-weight: bold; /* 设置为粗体 */
}
</style>
