<script setup lang="ts">
import { defineEmits, h, ref } from 'vue';
import { NIcon, useMessage } from 'naive-ui';
import {
  AddCircleOutline as AddIcon,
  ArrowUndoCircle as CashIcon,
  CheckmarkDoneCircleOutline as CheckIcon,
  CloseSharp as CloseIcon
} from '@vicons/ionicons5';
import { fetchAddManageTask } from '@/service/api/taskmg';
import inIcon from '@/assets/imgs/入库.png';
import { useRouterPush } from '@/hooks/common/router';

const emit = defineEmits<{
  (e: 'submitted'): void;
}>();

const renderIcon = () => {
  return h(NIcon, null, {
    default: () => h(CashIcon)
  });
};
const addIcon = () => {
  return h(NIcon, null, {
    default: () => h(AddIcon)
  });
};
const renderIcon2 = () => {
  return h(NIcon, null, {
    default: () => h(CloseIcon)
  });
};
const checkIcon = () => {
  return h(NIcon, null, {
    default: () => h(CheckIcon)
  });
};
const message = useMessage();
const panels = ref(['入库计划001']);

// 每个面板存储一个对象，包含 palletno 和 selectedOrders
const ordersData = ref<
  Record<string, { palletno: string | undefined; selectedOrders: Api.Exploitation.NewPurchaseOrder[] }>
>({
  入库计划001: { palletno: '', selectedOrders: [] }
});

const value = ref('入库计划001');

const addPanel = () => {
  const newPanel = `入库计划00${panels.value.length + 1}`;
  panels.value.push(newPanel);
  ordersData.value[newPanel] = { palletno: '', selectedOrders: [] }; // 初始化新面板的数据
  value.value = newPanel; // 切换当前面板
};

const removePanel = () => {
  if (!value.value) return; // 确保有当前选中的托盘

  const panelToRemove = value.value;

  // 从 panels 中删除
  const index = panels.value.indexOf(panelToRemove);
  if (index !== -1) {
    panels.value.splice(index, 1);
  }

  // 从 ordersData 中删除
  Reflect.deleteProperty(ordersData.value, panelToRemove);

  // 如果当前选中的托盘已删除，切换到下一个面板
  if (panels.value.length > 0) {
    value.value = panels.value[panels.value.length - 1]; // 设置为最后一个托盘
  } else {
    value.value = ''; // 如果没有托盘，重置为默认值
  }
};

// const onUpdateOrders = (pallet: string, selected: Api.Exploitation.NewPurchaseOrder[]) => {
//   const allOtherOrders: string[] = [];

//   // 收集所有其他托盘已选中的 OrderLineNumber
//   for (const key in ordersData.value) {
//     if (key !== pallet) {
//       const orders = ordersData.value[key].selectedOrders || [];
//       orders.forEach(order => {
//         allOtherOrders.push(order.OrderLineNumber as string);
//       });
//     }
//   }
//   // 找出这次传入中和其他托盘冲突的订单号
//   const duplicateOrders = selected
//     .filter(item => allOtherOrders.includes(item.OrderLineNumber as string))
//     .map(item => item.OrderLineNumber);

//   if (duplicateOrders.length > 0) {
//     message.error(`订单序号 ${duplicateOrders.join(', ')} 已被其他托盘选择，请取消后再操作`, { duration: 5000 });
//   }

//   // 只保留未重复的订单
//   const filtered = selected.filter(item => !duplicateOrders.includes(item.OrderLineNumber));

//   // 更新当前托盘的数据（保留原来的 palletno）
//   if (ordersData.value[pallet]) {
//     ordersData.value[pallet].selectedOrders = filtered;
//   } else {
//     ordersData.value[pallet] = { palletno: '', selectedOrders: filtered };
//   }
// };
const onUpdateOrders = (pallet: string, selected: Api.Exploitation.NewPurchaseOrder[]) => {
  // 0. 验证 palletno 唯一（如果是新建托盘，且已存在同名托盘，报错并退出）
  const isNewPallet = !ordersData.value[pallet];
  if (isNewPallet && Object.keys(ordersData.value).includes(pallet)) {
    message.error(`托盘号 ${pallet} 已存在，请使用唯一的托盘号`, { duration: 5000 });
    return;
  }

  const orderUsedQuantityMap: Record<string, number> = {};

  // 1. 统计其他托盘上已选中的每个订单序号的数量
  for (const key in ordersData.value) {
    if (key !== pallet) {
      const orders = ordersData.value[key].selectedOrders || [];
      for (const order of orders) {
        const orderNo = order.OrderLineNumber as string;
        const qty = Number(order.OrderQuantity) || 0;
        orderUsedQuantityMap[orderNo] = (orderUsedQuantityMap[orderNo] || 0) + qty;
      }
    }
  }

  const filtered: Api.Exploitation.NewPurchaseOrder[] = [];
  const blockedOrders: string[] = [];

  // 2. 检查当前选择的订单是否被部分或完全占用
  for (const order of selected) {
    const orderNo = order.OrderLineNumber as string;
    const selectedQty = Number(order.OrderQuantity) || 0;
    const usedQty = orderUsedQuantityMap[orderNo] || 0;
    const remainingQty = selectedQty - usedQty;

    if (remainingQty > 0) {
      // 可以部分选择
      filtered.push({
        ...order,
        OrderQuantity: remainingQty
      });
    } else {
      // 完全被占用，不允许选择
      blockedOrders.push(orderNo);
    }
  }

  // 3. 如果有不能选择的订单，给出提示
  if (blockedOrders.length > 0) {
    message.error(`订单序号 ${blockedOrders.join(', ')} 数量已被其他托盘占用，请取消后再操作`, { duration: 5000 });
  }

  // 4. 更新当前托盘的数据
  if (ordersData.value[pallet]) {
    ordersData.value[pallet].selectedOrders = filtered;
  } else {
    ordersData.value[pallet] = { palletno: pallet, selectedOrders: filtered };
  }
};


const updatePalletno = (pallet: string, newPalletno: string) => {
  if (ordersData.value[pallet]) {
    ordersData.value[pallet].palletno = newPalletno;
  }
};
const showModalRef = ref(false);

const { routerPushByKey } = useRouterPush();
// 提交数据
function getdata() {
  showModalRef.value = true;
}

// 数据校验 函数
function validateOrdersData(data: Api.PlanManage.OrdersData): boolean {
  for (const [key, values] of Object.entries(data)) {
    if (!values.palletno) {
      message.warning(`计划 ${key} 的 托盘编码 不能为空` as string, { duration: 5000 });
      return false;
    }
    if (!values.selectedOrders || values.selectedOrders.length === 0) {
      message.warning(`计划 ${key} 必须至少选择一条订单`, { duration: 5000 });
      return false;
    }

    if ((values.selectedOrders as Api.Exploitation.NewPurchaseOrder[]).some(order => !order.RFIDCode)) {
      message.warning(`计划 ${key} 中的某些订单缺少 RFID编码` as string, { duration: 5000 });
      return false;
    }
  }
  return true;
}

const showPlanning = () => {
  emit('submitted'); // 通知父组件关闭
};

// 仅保存
async function onNegativeClick() {
  showModalRef.value = false;
  if (validateOrdersData(ordersData.value)) {
    const response = await fetchAddManageTask({ ordersData: ordersData.value, isImmediate: false });
    if (response.data?.Status === 1) {
      message.info(response.data?.msg, { duration: 5000 });
      emit('submitted'); // 通知父组件关闭
      routerPushByKey('planmg_todowork');
    } else {
      message.warning(response.data?.msg as string, { duration: 5000 });
    }
  }
}
// 保存并执行任务
async function onPositiveClick() {
  showModalRef.value = false;

  if (validateOrdersData(ordersData.value)) {
    const response = await fetchAddManageTask({ ordersData: ordersData.value, isImmediate: true });
    if (response.data?.Status === 1) {
      message.info(response.data?.msg, { duration: 5000 });
      emit('submitted'); // 通知父组件关闭
      routerPushByKey('planmg_todowork');
    } else {
      message.warning(response.data?.msg as string, { duration: 5000 });
    }
  }
}
</script>

<template>
  <div class="min-h-500px flex-col-stretch gap-16px overflow-hidden lt-sm:overflow-auto">
    <NCard>
      <NPageHeader subtitle="制定入库任务计划">
        <template #title>
          <a>入库任务</a>
        </template>
        <template #avatar>
          <NAvatar class="avatars" :src="inIcon" />
        </template>
        <template #extra>
          <NSpace>
            <NButton strong :render-icon="renderIcon" @click="showPlanning">返回</NButton>
          </NSpace>
        </template>
      </NPageHeader>
    </NCard>
    <NCard class="amin">
      <div class="amin_div">
        <NButton strong :render-icon="addIcon" @click="addPanel">新增托盘</NButton>
        <NPopconfirm :show-icon="false" @positive-click="removePanel">
          <template #trigger>
            <NButton strong :render-icon="renderIcon2">删除当前托盘</NButton>
          </template>
          确认删除当前托盘？
        </NPopconfirm>
        <NButton strong :render-icon="checkIcon" color="#286f4f" @click="getdata">保存任务</NButton>
        <NModal
          v-model:show="showModalRef"
          :mask-closable="false"
          preset="dialog"
          title="确认"
          content=" 是否保存并执行任务？"
          positive-text="保存并执行"
          negative-text="仅保存"
          @positive-click="onPositiveClick"
          @negative-click="onNegativeClick"
        ></NModal>
      </div>
      <NTabs v-model:value="value" addable type="line" placement="left" animated>
        <NTabPane v-for="panel in panels" :key="panel" :name="panel" :tab="panel">
          <OrderSelection
            :pallet="panel"
            :selected-orders="ordersData[panel]?.selectedOrders || []"
            :palletno="ordersData[panel]?.palletno"
            @update-orders="onUpdateOrders"
            @update-palletno="updatePalletno"
          />
        </NTabPane>
      </NTabs>
    </NCard>
  </div>
</template>

<style scoped>
.amin {
  height: 100%;
}
.amin_div {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  margin-bottom: 2vh;
}
.avatars {
  background-color: transparent;
}
</style>
