<script setup lang="ts">
import { ref, watch } from 'vue';
import { NButton, NCard, NDrawer, NInput, NSpace, useMessage } from 'naive-ui';
import type { InputInst } from 'naive-ui';
import { fetchGetLyb_EditList } from '@/service/api/exploitation';
import { useTable, useTableOperate } from '@/hooks/common/table';
import { useAppStore } from '@/store/modules/app';
import LybSearch from '../../views/exploitation/lvyuebiao/modules/lvyuebiao-search.vue'; // 表格数据初始化
const message = useMessage();
const appStore = useAppStore();
const {
  columns,
  data,
  columnChecks,
  getData,
  getDataByPage,
  loading,
  mobilePagination,
  searchParams,
  resetSearchParams
} = useTable({
  apiFn: fetchGetLyb_EditList,
  showTotal: true,
  apiParams: {
    current: 1,
    size: 10,
    OrderLineNumber: null, // 订单+行号，作为主键
    PurchaseOrderNumber: null, // 采购订单号
    PurchaseOrderLineItem: null, // 采购订单行项目号
    PurchaseRequestNumber: null, // 采购申请号（可选）
    StockUnit: null, // 库存单位
    MaterialType: null, // 物资类型
    ProjectName: null, // 项目名称
    MaterialCode: null, // 物料编码
    MaterialName: null, // 物资名称
    OrderQuantity: null, // 订单数量
    MaterialUnit: null, // 物料单位
    SupplierName: null, // 供应商名称
    PlannedDeliveryDate: null, // 采购订单计划交货日期
    ERPSystemFactory: null, // ERP系统工厂
    ProjectCode: null, // 项目编码
    ContractUnitPrice: null, // 签约单价(不含税)
    ContractTotalPrice: null, // 签约总价(不含税)
    ProjectType: null, // 项目类型
    ProcurementMethod: null, // 采购方式
    MajorCategory: null, // 大类
    MiddleCategory: null, // 中类
    SubCategory: null, // 小类
    ExtraField1: null, // 扩展字段1，格式 "yyyy-MM-dd HH:mm:ss"
    ExtraField2: null, // 扩展字段2
    CreateTimeEnd: null, // 扩展字段2
    CreateTimeStart: null // 扩展字段2
  },
  columns: () => [
    {
      type: 'selection',
      align: 'center',
      width: 48
    },
    {
      key: 'index',
      title: '序号',
      width: 40,
      align: 'center'
    },
    {
      key: 'OrderLineNumber',
      title: '订单+行号',
      align: 'center',
      width: 100
    },
    {
      key: 'PurchaseOrderNumber',
      title: '采购订单号',
      align: 'center',
      width: 100
    },
    {
      key: 'PurchaseOrderLineItem',
      title: '采购订单行项目号',
      align: 'center',
      width: 100
    },
    {
      key: 'PurchaseRequestNumber',
      title: '采购申请号',
      align: 'center',
      width: 100
    },
    {
      key: 'StockUnit',
      title: '库存单位',
      align: 'center',
      width: 100
    },
    {
      key: 'MaterialType',
      title: '物资类型',
      align: 'center',
      width: 100
    },
    {
      key: 'ProjectName',
      title: '项目名称',
      align: 'center',
      width: 200
    },
    {
      key: 'MaterialCode',
      title: '物料编码',
      align: 'center',
      width: 100
    },
    {
      key: 'MaterialName',
      title: '物资名称',
      align: 'center',
      width: 200
    },
    {
      key: 'OrderQuantity',
      title: '订单数量',
      align: 'center',
      width: 100
    },
    {
      key: 'MaterialUnit',
      title: '物料单位',
      align: 'center',
      width: 100
    },
    {
      key: 'SupplierName',
      title: '供应商名称',
      align: 'center',
      width: 150
    },
    {
      key: 'PlannedDeliveryDate',
      title: '计划交货日期',
      align: 'center',
      width: 100
    },
    {
      key: 'ERPSystemFactory',
      title: 'ERP系统工厂',
      align: 'center',
      width: 100
    },
    {
      key: 'ProjectCode',
      title: '项目编码',
      align: 'center',
      width: 100
    },
    {
      key: 'ContractUnitPrice',
      title: '签约单价(不含税)',
      align: 'center',
      width: 100
    },
    {
      key: 'ContractTotalPrice',
      title: '签约总价(不含税)',
      align: 'center',
      width: 100
    },
    {
      key: 'ProjectType',
      title: '项目类型',
      align: 'center',
      width: 100
    },
    {
      key: 'ProcurementMethod',
      title: '采购方式',
      align: 'center',
      width: 100
    },
    {
      key: 'MajorCategory',
      title: '大类',
      align: 'center',
      width: 100
    },
    {
      key: 'MiddleCategory',
      title: '中类',
      align: 'center',
      width: 100
    },
    {
      key: 'SubCategory',
      title: '小类',
      align: 'center',
      width: 100
    },
    {
      key: 'ExtraField1',
      title: '导入时间',
      align: 'center',
      width: 150
    }
  ]
});

const { checkedRowKeys } = useTableOperate(data, getData);

const props = withDefaults(
  defineProps<{
    pallet: string;
    palletno: string | undefined;
    selectedOrders?: Api.Exploitation.NewPurchaseOrder[];
  }>(),
  {
    selectedOrders: () => []
  }
);

// 使用 ref 创建本地副本来处理 palletno 的值
const localPalletno = ref(props.palletno);

const emit = defineEmits<{
  (event: 'updateOrders', pallet: string, selectedOrders: Api.Exploitation.NewPurchaseOrder[]): void;
  (event: 'updatePalletno', pallet: string, palletno: string): void;
}>();

const showDrawer = ref(false);

const tempSelectedOrders = ref<Api.Exploitation.NewPurchaseOrder[]>([...props.selectedOrders]);
// 监听托盘编码变化
const confirmSelection = () => {
  checkedRowKeys.value.forEach(key => {
    // 根据 OrderLineNumber 对照行数据
    const rowData = data.value.find(row => String(row.OrderLineNumber) === key);
    if (!rowData) return; // 找不到匹配的数据，则跳过

    // 1. 检查是否已存在相同 OrderLineNumber，如存在直接跳过（并提示提醒）
    const alreadySelected = tempSelectedOrders.value.some(order => order.OrderLineNumber === rowData.OrderLineNumber);
    if (alreadySelected) {
      message.warning(`订单行号 ${rowData.OrderLineNumber} 已存在，不能重复添加。`, { duration: 5000 });
      return;
    }

    // 2. 当已有订单时，根据第一个订单的信息约束后续添加数据
    if (tempSelectedOrders.value.length > 0) {
      const firstOrder = tempSelectedOrders.value[0];
      const firstFieldsAreEmpty = !firstOrder.PurchaseOrderNumber && !firstOrder.PurchaseOrderLineItem;
      const newFieldsAreEmpty = !rowData.PurchaseOrderNumber && !rowData.PurchaseOrderLineItem;

      // 情况 1: 第一个订单为空，则后续数据必须保持为空
      if (firstFieldsAreEmpty && !newFieldsAreEmpty) {
        message.warning(`履约订单货物无法与自定义订单货物存放在一个托盘上`, { duration: 5000 });
        return;
      }
      // 情况 2: 第一个订单非空，则后续数据也必须非空
      if (!firstFieldsAreEmpty && newFieldsAreEmpty) {
        message.warning(`自定义订单货物无法与履约订单货物存放在一个托盘上`, { duration: 5000 });
        return;
      }
    }

    // 3. 构造新的订单数据，附加托盘编码，并将 RFIDCode 置空，然后添加到订单集合中
    const newRowData: Api.Exploitation.NewPurchaseOrder = {
      ...rowData,
      BinLocation: props.pallet,
      RFIDCode: null
    };
    tempSelectedOrders.value.push(newRowData);
  });

  // 触发事件更新订单列表，并关闭抽屉
  emit('updateOrders', props.pallet, [...tempSelectedOrders.value]);
  showDrawer.value = false;
};

const updatePalletno2 = (newValue: string) => {
  emit('updatePalletno', props.pallet, newValue);
};
// 移除订单
const removeOrder = (orderLineNumber: string) => {
  tempSelectedOrders.value = tempSelectedOrders.value.filter(o => o.OrderLineNumber !== orderLineNumber);
  emit('updateOrders', props.pallet, [...tempSelectedOrders.value]);
};
// 缓存最大值的对象
const maxCache = ref<Record<string, number>>({});

// 计算最大值，只在初始化时触发一次
const getMax = (id: string): number => {
  // 如果缓存中已经有最大值，直接返回缓存值
  if (maxCache.value[id] !== undefined) {
    return maxCache.value[id];
  }

  // 否则，计算并缓存最大值
  const item = tempSelectedOrders.value.find(x => x.OrderLineNumber === id);
  const max = item?.OrderQuantity ?? 9999;
  maxCache.value[id] = max; // 缓存最大值
  return max;
};

function AddClick() {
  showDrawer.value = true;
  checkedRowKeys.value = [];
}

// 1. 定义 rfidRefs：用于保存所有 RFID 输入框组件实例的引用数组
const rfidRefs = ref<Array<InputInst | null>>([]); // 每个元素是 NInput 组件实例

// 2. 定义 palletRef：用于保存托盘编码输入框的组件实例引用
const palletRef = ref<InputInst | null>(null);

// 3. 定义按回车事件处理函数
function onEnterRFID(index: number) {
  // 如果不是最后一个 RFID 输入框，则聚焦下一个
  if (index < tempSelectedOrders.value.length - 1) {
    const nextInput = rfidRefs.value[index + 1];
    nextInput?.focus(); // 调用 NInput 实例的 focus() 方法聚焦下一个输入框
  } else {
    // 如果已经是最后一个，则聚焦托盘编码输入框
    palletRef.value?.focus();
  }
}

watch(
  () => props.selectedOrders,
  newVal => {
    // 同步 tempSelectedOrders 和 checkedRowKeys
    tempSelectedOrders.value = [...newVal];
    checkedRowKeys.value = newVal.map(item => String(item.OrderLineNumber));
  },
  { immediate: true }
);
</script>

<template>
  <div class="min-h-500px flex-col-stretch gap-16px overflow-hidden lt-sm:overflow-auto">
    <NSpace vertical>
      <NCard>
        <NSpace justify="space-between" align="center">
          <span class="label-text">{{ pallet }} - 选择履约订单</span>
          <NButton ghost @click="AddClick">+</NButton>
        </NSpace>
      </NCard>

      <NSpace vertical>
        <NCard v-for="(item, index) in tempSelectedOrders" :key="item.OrderLineNumber as string">
          <NSpace justify="space-between">
            <p class="NSpace_p">
              订单+行号：
              <span class="NSpace_span">{{ item.OrderLineNumber }}</span>
              -- 物资名称：
              <span class="NSpace_span">{{ item.MaterialName }}</span>
              -- 项目名称：
              <span class="NSpace_span">{{ item.ProjectName }}</span>
            </p>
            <NButton size="small" @click="removeOrder(item.OrderLineNumber as string)">移除</NButton>
          </NSpace>

          <NSpace align="center">
            <span class="label-text">任务数量:</span>
            <NInputNumber
              v-model:value="item.OrderQuantity"
              min="0"
              :max="getMax(item.OrderLineNumber as string)"
              placeholder="任务数量"
            />
            <!-- <NInput v-model:value="item.RFIDCode" placeholder="RFID编号" /> -->
            <NInput
              ref="rfidRefs"
              v-model:value="item.RFIDCode"
              placeholder="RFID编号"
              @keydown.enter.prevent="onEnterRFID(index)"
            />
          </NSpace>
        </NCard>
      </NSpace>
      <NCard>
        <!--
 <NInput
          v-model:value="localPalletno"
          class="NSpace_NInput"
          placeholder="托盘编码："
          @update:value="updatePalletno2"
        />
-->
        <NInput
          ref="palletRef"
          v-model:value="localPalletno"
          class="NSpace_NInput"
          placeholder="托盘编码："
          @update:value="updatePalletno2"
        />
      </NCard>
      <NDrawer v-model:show="showDrawer" title="选择履约单" placement="bottom" :default-height="850">
        <div>
          <LybSearch v-model:model="searchParams" @reset="resetSearchParams" @search="getDataByPage" />
          <NCard title="履约表信息" :bordered="false" size="small" class="sm:flex-1-hidden card-wrapper">
            <template #header-extra>
              <TableHeaderOperationintask
                v-model:columns="columnChecks"
                :disabled-delete="checkedRowKeys.length === 0"
                :loading="loading"
                @refresh="getData"
                @add="confirmSelection"
              />
            </template>
            <NDataTable
              v-model:checked-row-keys="checkedRowKeys"
              :columns="columns"
              :data="data"
              size="small"
              :flex-height="!appStore.isMobile"
              :scroll-x="3500"
              :loading="loading"
              remote
              :row-key="row => row.OrderLineNumber"
              :pagination="mobilePagination"
              class="amin sm:h-full"
            />
          </NCard>
        </div>
      </NDrawer>
    </NSpace>
  </div>
</template>

<style scoped>
.amin {
  height: 730px;
}
.NSpace_span {
  color: rgb(145, 145, 145);
}
.NSpace_p {
  margin-bottom: 20px;
}
.label-text {
  white-space: nowrap;
  display: inline-block;
  min-width: 70px;
}
.NSpace_NInput {
  white-space: nowrap;
  display: inline-block;
  width: 50%;
}
</style>
