<template>
  <BasicModal
    v-bind="$attrs"
    @register="registerModal"
    title="生成领料单"
    width="1000px"
    :confirmLoading="loading"
    @ok="handleOk"
    @cancel="handleCancel"
  >
    <!-- 可编辑表格 -->
    <BasicTable
      :dataSource="tableData"
      :columns="columns"
      :pagination="false"
      :scroll="{ y: 300 }"
      rowKey="id"
    />
  </BasicModal>
</template>

<script lang="ts" setup>
  import { ref, defineExpose } from 'vue';
  import { BasicModal, useModal } from '/@/components/Modal';
  import { BasicTable, BasicColumn } from '/@/components/Table';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { h } from 'vue';
  import { InputNumber } from 'ant-design-vue';
  import { defHttp } from '/@/utils/http/axios';
  const { Message } = useMessage();
  const [registerModal, { openModal, closeModal }] = useModal();
  const { createMessage } = useMessage();
  const emit = defineEmits(['success']); // ✅ 必须写

  /* 表格数据 */
  const tableData = ref<any[]>([]);

  /* 加载状态 */
  const loading = ref(false);

  /* 表格列定义 */
  const columns: BasicColumn[] = [
    { title: '物料编码', dataIndex: 'wlbh', width: 120 },
    { title: '物料名称', dataIndex: 'wlmc', width: 200 },
    { title: '备料数量', dataIndex: 'blsl', width: 200 },
    { title: '库存数量', dataIndex: 'kcl', width: 200 },
    {
      title: '领料数量',
      dataIndex: 'sl',
      width: 130,
      // 常驻输入框
      customRender: ({ record }) =>
        h(InputNumber, {
          value: 0,
          min: 0,
          max: 999999,
          size: 'small',
          style: { width: '100%' },
          // onChange: (val) => (record.sl = val),
        }),
    },
  ];

  /* 打开弹窗 - 父组件调用 */
  function open(rows: any[]) {
    tableData.value = rows.map((r) => ({ ...r, blsl: r.blsl || 0 }));
    openModal(true);
  }

  /* 确认 - 回传所有行（含改后的数量） */
  async function handleOk() {
    // 防止重复提交
    if (loading.value) return;

    // 简单校验：数量不能全 0
    const allZero = tableData.value.every((r) => r.blsl === 0);
    if (allZero) {
      createMessage.warning('请至少输入一行领料数量'); // ✅ 用 createMessage
      return;
    }

    // 校验库存数量是否足够
    const insufficientItem = tableData.value.find((r) => (r.kcl || 0) < (r.blsl || 0));
    if (insufficientItem) {
      createMessage.warning(`${insufficientItem.wlmc}库存数量不足`);
      return;
    }

    // 构建请求参数
    const requestData = tableData.value.map((item) => ({
      wlbm: item.wlbh, // 物料编码
      wlmc: item.wlmc, // 物料名称
      blsl: item.blsl || 0, // 备料数量
      kcl: item.kcl || 0, // 库存数量
      sl: item.sl || 0, // 领料数量
    }));

    loading.value = true;
    try {
      // 调用后端接口
      const response = await defHttp.post(
        {
          url: '/ckgl/scll',
          data: requestData,
        },
        {
          errorMessageMode: 'message',
        },
      );

      // 接口调用成功
      createMessage.success('领料单生成成功');
      emit('success', tableData.value); // 回传完整数组
      closeModal();
    } catch (error) {
      // 接口调用失败
      createMessage.error('领料单生成失败，请重试');
      console.error('接口调用失败:', error);
    } finally {
      loading.value = false;
    }
  }

  function handleCancel() {
    closeModal();
  }

  defineExpose({ open });
</script>
