// index.vue

<script setup lang="tsx">
import { h, ref } from 'vue'; // 注意此处应该是 vue 而不是 process
import { useRoute } from 'vue-router';
import { NImage, NInputNumber } from 'naive-ui';
import type { DataTableCreateSummary, DataTableRowKey } from 'naive-ui';
import { fetchGetNomalOrderInfo } from '@/service/api/delivery/normal-orde';
import { confirmSplit, deleteTempSubOrder, manualSplit } from '@/service/api/delivery/split-order-detail';
import { localStg } from '@/utils/storage';
import { useModal } from '@/components/zt/Modal/hooks/useModal';
interface OrderItem {
  skuId: number | undefined;
  prodCount: number;
}
const isSubmit = ref(false);

const list = ref<{ orderItems: Api.delivery.OrderItemElement[]; subOrders: Api.delivery.OrderItemElement[] }>({
  orderItems: [],
  subOrders: []
});
const list1 = ref<Api.delivery.OrderItemElement[]>([]);
const route = useRoute();
const checkedRowKeysRef = ref<Api.delivery.OrderItemElement[]>([]);
const orderItemsList = ref<OrderItem[]>([]);
const loading = ref(true);

const columns: NaiveUI.TableColumn<Api.delivery.OrderItemElement>[] = [
  {
    title: '商品',
    key: 'goods',
    width: 300,
    render: row => {
      const goodsNodes = [
        h(NImage, { src: row.pic, width: 40, height: 40 }),
        h('div', { class: 'ml-2 ' }, [
          h('div', { class: 'text-12px font-semibold' }, row.skuName),
          h('div', { class: 'text-10px text-gray' }, `规格：${row.spec || '--'}`)
        ])
      ];
      return h('div', { class: 'flex items-center' }, goodsNodes);
    }
  },
  {
    title: 'sku重量',
    key: 'weight', // 注意这里 key 应该唯一，不应重复使用 price
    width: 100,
    align: 'center',
    render(row) {
      return <div>{row.weight / 1000}kg</div>;
    }
  },
  {
    title: '购买数量',
    key: 'prodCount',
    width: 100,
    align: 'center'
  },
  {
    title: '已拆单数量',
    key: 'splitCount',
    width: 100,
    align: 'center'
  },
  {
    title: '可拆单数量',
    key: 'availableSplitCount',
    width: 100,
    align: 'center',
    render(row) {
      const availableSplitCount = (row.prodCount ?? 0) - (row.splitCount ?? 0);
      return <div class={availableSplitCount ? 'text-red' : ''}>{availableSplitCount}</div>;
      // return (<div class={(row.prodCount - row.splitCount)&&'text-red'}>{row.prodCount - row.splitCount}</div>)
    }
  }
];
const columns1: NaiveUI.TableColumn<Api.delivery.OrderItemElement>[] = [
  {
    type: 'selection'
  },
  {
    title: '商品',
    key: 'goods',
    width: 300,
    render: row => {
      const goodsNodes = [
        h(NImage, { src: row.pic, width: 40, height: 40 }),
        h('div', { class: 'ml-2 ' }, [
          h('div', { class: 'text-12px font-semibold' }, row.skuName),
          h('div', { class: 'text-10px text-gray' }, `规格：${row.spec || '--'}`)
        ])
      ];
      return h('div', { class: 'flex items-center' }, goodsNodes);
    }
  },
  {
    title: 'sku重量',
    key: 'weight', // 注意这里 key 应该唯一，不应重复使用 price
    width: 100,
    align: 'center',
    render(row) {
      return <div>{row.weight / 1000}kg</div>;
    }
  },
  {
    title: '可拆单数量',
    key: 'canSplitCount',
    width: 100,
    align: 'center'
  },
  {
    title: '拆单数量',
    key: 'splitCount',
    width: 100,
    align: 'center',
    render(row, index) {
      return h(NInputNumber, {
        value: row.splitCount,
        precision: 0,
        min: 0,
        max: row.canSplitCount,
        onUpdateValue(v) {
          list1.value[index].splitCount = v;
          // list1.value.orderItems[index].canSplitCount -= v as number
        }
      });
    }
  }
];

const childColumns: NaiveUI.TableColumn<Api.delivery.OrderItemElement>[] = [
  {
    title: '商品',
    key: 'goods',
    width: 300,
    render: row => {
      const goodsNodes = [
        h(NImage, { src: row.pic, width: 40, height: 40 }),
        h('div', { class: 'ml-2 ' }, [
          h('div', { class: 'text-12px font-semibold' }, row.skuName),
          h('div', { class: 'text-10px text-gray' }, `规格：${row.spec || '--'}`)
        ])
      ];
      return h('div', { class: 'flex items-center' }, goodsNodes);
    }
  },
  {
    title: 'sku重量',
    key: 'price', // 注意这里 key 应该唯一，不应重复使用 price
    width: 100,
    align: 'center',
    render(row) {
      return <div>{row.weight / 1000}kg</div>;
    }
  },
  {
    title: '数量',
    key: 'prodCount',
    width: 100,
    align: 'center'
  }
];

const columns2: NaiveUI.TableColumn<Api.delivery.OrderItemElement>[] = [
  {
    title: '商品',
    key: 'goods',
    render: row => {
      const goodsNodes = [
        h(NImage, { src: row.pic, width: 80, height: 80 }),
        h('div', { class: 'ml-2 ' }, [
          h('div', { class: 'text-15px font-semibold' }, row.skuName),
          h('div', { class: 'text-gray' }, `规格：${row.spec || '--'}`)
        ])
      ];
      return h('div', { class: 'flex items-center' }, goodsNodes);
    }
  },
  {
    title: 'sku重量',
    key: 'price', // 注意这里 key 应该唯一，不应重复使用 price
    width: 200,
    align: 'center',
    render(row) {
      return <div>{row.weight / 1000}kg</div>;
    }
  },
  {
    title: '数量',
    key: 'splitCount',
    width: 200,
    align: 'center'
  }
];
const [registerModalPrice, { openModal, setSubLoading, closeModal }] = useModal({
  title: '选择拆单商品',
  width: 1200,
  height: 700
});
// h(
//   'div',
//   {
//     class: ' flex gap-2 items-center ' // div 的样式（内边距、边框、弹性布局）
//   },
//   [
//     h(
//       'div',
//       { style: { color: 'red', whiteSpace: 'nowrap' } },
//       `子订单商品的总重量：${(pageData as unknown as Api.delivery.OrderItemElement[]).reduce(
//         (prevValue, row) => prevValue + row.weight,
//         0
//       ) / 1000}kg`
//     ),
//     'kg'
//           ),
//   h('div', { style: { color: 'red', whiteSpace: 'nowrap' } }, `总数量：${pageData.length}`)
//         ]
//       )
const summary: DataTableCreateSummary = pageData => {
  return {
    splitCount: {
      value: (
        <div class={'flex items-center gap-2'}>
          <div style="{ color: 'red', whiteSpace: 'nowrap' }">{`子订单商品的总重量：${
            (pageData as unknown as Api.delivery.OrderItemElement[]).reduce(
              (prevValue, row) => prevValue + row.weight,
              0
            ) / 1000
          }kg`}</div>
          <div style="{ color: 'red', whiteSpace: 'nowrap' }">{`总数量：${pageData.length}`}</div>
        </div>
      ),
      colSpan: 1
    }
  };
};
console.log(route.query.orderNumber);

async function getData() {
  try {
    loading.value = true;
    const result = await fetchGetNomalOrderInfo('FD2001476085560250368');
    // const result = await fetchGetNomalOrderInfo((route.query.orderNumber as string) || '');
    loading.value = false;
    if (result && result.data) {
      const orderItems = result.data.orderItems ?? [];
      const subOrders = result.data.subOrders ?? [];
      list.value.orderItems = orderItems;
      list.value.subOrders = subOrders;
    } else {
      console.error('接口无有效数据返回');
    }
  } catch (err) {
    loading.value = false;
    console.error('获取订单详情失败:', err);
  }
}
getData();
function handleAdd() {
  list1.value = list.value.orderItems;
  list1.value.forEach(i => {
    i.canSplitCount = i.prodCount ?? 0 - i.splitCount;
    i.splitCount = 0;
  });
  openModal();
}
// function close() {}
async function save() {
  isSubmit.value = true;
  await confirmSplit({ orderNumber: route.query.orderNumber as string, splitUserId: localStg.get('lastLoginUserId') });
  isSubmit.value = false;
  window.$message?.success('保存成功');
}
function refresh() {}

function handleCheck(_: DataTableRowKey[], row: Api.delivery.OrderItemElement[]) {
  checkedRowKeysRef.value = row;
  orderItemsList.value = checkedRowKeysRef.value.map(i => {
    return {
      skuId: i.skuId,
      prodCount: i.splitCount
    };
  });
  console.log('选中了', checkedRowKeysRef.value, row);
}

async function addSubmit() {
  setSubLoading(true);
  await manualSplit({
    orderNumber: route.query.orderNumber as string,
    orderItems: orderItemsList.value,
    splitUserId: localStg.get('lastLoginUserId')
  });
  setSubLoading(false);
  getData();
  closeModal();
}
async function handleDel(orderNumber: string) {
  await deleteTempSubOrder(orderNumber);
  closeModal();
}
</script>

<template>
  <div>
    <NCard title="1 父订单商品" size="medium" :bordered="false">
      <NDataTable :columns="columns" :loading="loading" :data="list.orderItems ?? []" :bordered="false" />
    </NCard>

    <NCard title="2 拆单与子订单" size="medium" :bordered="false">
      <NCard title="拆单" size="small" :bordered="false">
        <NButton @click="handleAdd">选择拆单商品</NButton>
      </NCard>
      <NCard
        v-for="(subOrder, index) in list.subOrders ?? []"
        :key="index"
        :title="'子订单（' + (index + 1) + '）'"
        size="small"
        :bordered="false"
      >
        <template #header>
          <NButton size="small" quaternary type="primary" @click="handleDel(subOrder.orderNumber as string)">
            删除该子订单
          </NButton>
        </template>
        <NDataTable :columns="childColumns" :data="subOrder.orderItems" :bordered="false" />
      </NCard>
      <template #footer>
        <NSpace justify="center">
          <!-- <NButton  @click="close">关闭</NButton> -->
          <NButton type="primary" :loading="isSubmit" @click="save">保存</NButton>
        </NSpace>
      </template>
    </NCard>

    <BasicModal @register="registerModalPrice" @after-leave="refresh" @ok="addSubmit">
      <LayoutTable>
        <NCard title="待拆单商品" size="small" :bordered="false">
          <NDataTable
            :columns="columns1"
            :data="list1"
            :max-height="450"
            :row-key="row => row.orderItemId"
            :bordered="false"
            @update:checked-row-keys="handleCheck"
          />
        </NCard>
        <NCard title="子订单商品" size="small" :bordered="false">
          <NDataTable
            :columns="columns2"
            :data="checkedRowKeysRef"
            :summary="summary"
            :max-height="450"
            :bordered="false"
          />
        </NCard>
      </LayoutTable>
    </BasicModal>
  </div>
</template>

<style scoped></style>
