import type { PageParam } from '@vben/request';

import type { VbenFormApi, VbenFormSchema } from '#/adapter/form';
import type { VxeTableGridOptions } from '#/adapter/vxe-table';
import type { MesProWorkOrderApi } from '#/api/mes/pro/workorder';
import type { MesQcRetentionSampleApi } from '#/api/mes/qc/retention-sample';

import { markRaw } from 'vue';

import dayjs from 'dayjs';

import { message } from 'ant-design-vue';

import { getSaleOrder, getSaleOrderPage } from '#/api/erp/sale/order';
import { getMpsPage } from '#/api/mes/pro/mps';
import { getSimpleUserList } from '#/api/system/user';
import { getDateRangePickerDefaultProps } from '#/utils';
import { ErpSaleOrderSelect } from '#/views/erp/sale/order/components';
import { MdItemSelect } from '#/views/mes/md/item/components';
import { ProWorkOrderSelect } from '#/views/mes/pro/workorder/components';

/** 留样保存时长（月），与后端默认值保持一致 */
const RETENTION_MONTHS = 6;

/** 校验销售订单是否真实存在，返回存在的订单编号 */
async function resolveExistingSaleOrderId(id: number) {
  const saleOrder = await getSaleOrder(id);
  return saleOrder?.id;
}

/** 选择工单后带出产品、批次与销售订单 */
async function handleWorkOrderChange(
  item: MesProWorkOrderApi.WorkOrder | undefined,
  formApi?: VbenFormApi,
) {
  if (!formApi) {
    return;
  }
  await formApi.setFieldValue('productName', item?.productName ?? undefined);
  await formApi.setFieldValue('batchCode', item?.batchCode ?? undefined);
  let saleOrderId: number | undefined;
  // 1. 客户订单来源工单：按来源单号自动匹配销售订单
  if (item?.orderSourceType === 1 && item.orderSourceCode) {
    const params: PageParam & { no?: string } = {
      no: item.orderSourceCode,
      pageNo: 1,
      pageSize: 1,
    };
    const page = await getSaleOrderPage(params);
    saleOrderId = page.list?.[0]?.id;
  }
  // 2. MPS 下发工单：以 MPS 记录的销售订单为准（合并下发可能对应多张）
  if (item?.id) {
    try {
      const page = await getMpsPage({
        pageNo: 1,
        pageSize: 20,
        workOrderId: item.id,
      });
      const mpsSaleOrders = new Map<number, string>();
      for (const mps of page.list ?? []) {
        if (mps.saleOrderId) {
          mpsSaleOrders.set(
            mps.saleOrderId,
            mps.saleOrderNo || `ID=${mps.saleOrderId}`,
          );
        }
      }
      if (mpsSaleOrders.size === 1) {
        const firstMpsSaleOrder = [...mpsSaleOrders.entries()][0];
        if (firstMpsSaleOrder) {
          const [mpsSaleOrderId, mpsSaleOrderNo] = firstMpsSaleOrder;
          const existingId = await resolveExistingSaleOrderId(mpsSaleOrderId);
          if (existingId) {
            saleOrderId = existingId;
          } else {
            saleOrderId = undefined;
            message.warning(
              `该工单由 MPS 下发，但 MPS 记录的销售订单【${mpsSaleOrderNo}】（ID=${mpsSaleOrderId}）在系统中不存在，请先修正 MPS 数据后再登记留样`,
            );
          }
        }
      } else if (mpsSaleOrders.size > 1) {
        saleOrderId = undefined;
        message.warning(
          `该工单由 ${mpsSaleOrders.size} 张销售订单合并下发，请选择本次留样对应的销售订单`,
        );
      }
    } catch {
      // MPS 查询失败（如无查询权限）时不阻断工单选择，保存时由后端兜底校验
    }
  }
  await formApi.setFieldValue('saleOrderId', saleOrderId);
}

/** 留样日期变更时同步到期日期 */
function syncExpiryDate(value: string, formApi?: VbenFormApi) {
  if (!formApi) {
    return;
  }
  void formApi.setFieldValue(
    'expiryDate',
    value ? dayjs(value).add(RETENTION_MONTHS, 'month').format('YYYY-MM-DD') : undefined,
  );
}

/** 新增/修改的表单 */
export function useFormSchema(
  formType: 'create' | 'update',
  formApi?: VbenFormApi,
): VbenFormSchema[] {
  return [
    {
      fieldName: 'id',
      component: 'Input',
      dependencies: {
        triggerFields: [''],
        show: () => false,
      },
    },
    {
      fieldName: 'workOrderId',
      label: '生产工单',
      component: markRaw(ProWorkOrderSelect),
      componentProps: {
        disabled: formType === 'update',
        excludeStatuses: [3],
        placeholder: '请选择生产工单',
        onChange: (item: MesProWorkOrderApi.WorkOrder | undefined) =>
          handleWorkOrderChange(item, formApi),
      },
      rules: 'selectRequired',
    },
    {
      fieldName: 'productName',
      label: '产品名称',
      component: 'Input',
      componentProps: {
        disabled: true,
        placeholder: '选择工单后自动带出',
      },
      dependencies: {
        triggerFields: ['workOrderId'],
        show: (values) => !!values.workOrderId,
      },
    },
    {
      fieldName: 'batchCode',
      label: '生产批次号',
      component: 'Input',
      componentProps: {
        disabled: true,
        placeholder: '选择工单后自动带出',
      },
      dependencies: {
        triggerFields: ['workOrderId'],
        show: (values) => !!values.workOrderId,
      },
    },
    {
      fieldName: 'saleOrderId',
      label: '销售订单',
      component: markRaw(ErpSaleOrderSelect),
      componentProps: {
        placeholder: '库存备货工单可不选；客户订单工单将自动匹配',
      },
    },
    {
      fieldName: 'sampleQuantity',
      label: '留样数量',
      component: 'InputNumber',
      componentProps: {
        class: '!w-full',
        min: 1,
        placeholder: '请输入留样数量',
        precision: 0,
      },
      rules: 'required',
    },
    {
      fieldName: 'sampleDate',
      label: '留样日期',
      component: 'DatePicker',
      componentProps: {
        class: '!w-full',
        format: 'YYYY-MM-DD',
        placeholder: '请选择留样日期',
        valueFormat: 'YYYY-MM-DD',
        onChange: (value: string) => syncExpiryDate(value, formApi),
      },
      rules: 'required',
    },
    {
      fieldName: 'expiryDate',
      label: '留样到期日期',
      component: 'DatePicker',
      componentProps: {
        class: '!w-full',
        disabled: true,
        format: 'YYYY-MM-DD',
        valueFormat: 'YYYY-MM-DD',
      },
      help: `按留样日期 + ${RETENTION_MONTHS} 个月自动计算`,
    },
    {
      fieldName: 'keeperUserId',
      label: '留样人',
      component: 'ApiSelect',
      componentProps: {
        allowClear: true,
        api: getSimpleUserList,
        labelField: 'nickname',
        placeholder: '不选则默认为当前登录用户',
        showSearch: true,
        optionFilterProp: 'label',
        valueField: 'id',
      },
    },
    {
      fieldName: 'remark',
      label: '备注',
      component: 'Textarea',
      formItemClass: 'col-span-2',
      componentProps: {
        placeholder: '请输入备注',
        rows: 3,
      },
    },
  ];
}

/** 列表的搜索表单 */
export function useGridFormSchema(): VbenFormSchema[] {
  return [
    {
      fieldName: 'code',
      label: '留样编号',
      component: 'Input',
      componentProps: {
        allowClear: true,
        placeholder: '请输入留样编号',
      },
    },
    {
      fieldName: 'workOrderCode',
      label: '生产工单编号',
      component: 'Input',
      componentProps: {
        allowClear: true,
        placeholder: '请输入生产工单编号',
      },
    },
    {
      fieldName: 'saleOrderNo',
      label: '销售订单号',
      component: 'Input',
      componentProps: {
        allowClear: true,
        placeholder: '请输入销售订单号',
      },
    },
    {
      fieldName: 'productId',
      label: '产品',
      component: markRaw(MdItemSelect),
      componentProps: {
        placeholder: '请选择产品',
      },
    },
    {
      fieldName: 'batchCode',
      label: '生产批次号',
      component: 'Input',
      componentProps: {
        allowClear: true,
        placeholder: '请输入生产批次号',
      },
    },
    {
      fieldName: 'sampleDate',
      label: '留样日期',
      component: 'RangePicker',
      componentProps: {
        ...getDateRangePickerDefaultProps(),
      },
    },
    {
      fieldName: 'expiryDate',
      label: '到期日期',
      component: 'RangePicker',
      componentProps: {
        ...getDateRangePickerDefaultProps(),
      },
    },
  ];
}

/** 列表的字段 */
export function useGridColumns(): VxeTableGridOptions<MesQcRetentionSampleApi.RetentionSample>['columns'] {
  return [
    {
      field: 'code',
      title: '留样编号',
      width: 160,
    },
    {
      field: 'workOrderCode',
      title: '生产工单编号',
      width: 150,
    },
    {
      field: 'saleOrderNo',
      title: '销售订单号',
      width: 150,
    },
    {
      field: 'productCode',
      title: '产品编码',
      width: 130,
    },
    {
      field: 'productName',
      title: '产品名称',
      minWidth: 160,
    },
    {
      field: 'batchCode',
      title: '生产批次号',
      width: 140,
    },
    {
      field: 'sampleQuantity',
      title: '留样数量',
      width: 100,
    },
    {
      field: 'sampleDate',
      title: '留样日期',
      width: 120,
      formatter: 'formatDate',
    },
    {
      field: 'expiryDate',
      title: '到期日期',
      width: 120,
      formatter: 'formatDate',
    },
    {
      title: '留样状态',
      width: 100,
      slots: { default: 'expiryStatus' },
    },
    {
      field: 'keeperNickname',
      title: '留样人',
      width: 100,
    },
    {
      field: 'createTime',
      title: '创建时间',
      width: 180,
      formatter: 'formatDate',
    },
    {
      title: '操作',
      width: 160,
      fixed: 'right',
      slots: { default: 'actions' },
    },
  ];
}
