import type { VbenFormApi, VbenFormSchema } from '#/adapter/form';
import type { VxeTableGridOptions } from '#/adapter/vxe-table';
import type { MesWmSalesNoticeApi } from '#/api/mes/wm/salesnotice';
import type { MesWmSalesNoticeLineApi } from '#/api/mes/wm/salesnotice/line';

import { h, markRaw } from 'vue';

import {
  DICT_TYPE,
  MesAutoCodeRuleCode,
  MesWmWarehouseTypeEnum,
} from '@vben/constants';

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

import { z } from '#/adapter/form';
import { generateAutoCode } from '#/api/mes/md/autocode/record';
import CrmCustomerSelect from '#/components/crm-customer-select.vue';
import {
  getStockSummaryByBatch,
  getStockSummaryByItem,
  type MesWmMaterialStockApi,
} from '#/api/mes/wm/materialstock';

/** 表单类型 */
export type FormType = 'create' | 'detail' | 'update';

/** 表单头部是否只读（详情态） */
function isHeaderReadonly(formType: FormType): boolean {
  return formType === 'detail';
}

/** 新增/修改的表单 */
export function useFormSchema(
  formType: FormType,
  formApi?: VbenFormApi,
): VbenFormSchema[] {
  return [
    {
      fieldName: 'id',
      component: 'Input',
      dependencies: {
        triggerFields: [''],
        show: () => false,
      },
    },
    {
      fieldName: 'status',
      component: 'Input',
      dependencies: {
        triggerFields: [''],
        show: () => false,
      },
    },
    {
      fieldName: 'code',
      label: '通知单编号',
      component: 'Input',
      componentProps: {
        placeholder: '请输入通知单编号',
      },
      rules: 'required',
      suffix: isHeaderReadonly(formType)
        ? undefined
        : () =>
            h(
              Button,
              {
                type: 'default',
                onClick: async () => {
                  const code = await generateAutoCode(
                    MesAutoCodeRuleCode.WM_SALES_NOTICE_CODE,
                  );
                  await formApi?.setFieldValue('code', code);
                },
              },
              { default: () => '生成' },
            ),
    },
    {
      fieldName: 'name',
      label: '通知单名称',
      component: 'Input',
      componentProps: {
        placeholder: '请输入通知单名称',
      },
      rules: 'required',
    },
    {
      fieldName: 'clientId',
      label: '客户',
      component: markRaw(CrmCustomerSelect),
      componentProps: {
        placeholder: '请选择客户',
      },
      rules: 'selectRequired',
    },
    {
      fieldName: 'salesDate',
      label: '发货日期',
      component: 'DatePicker',
      componentProps: {
        class: '!w-full',
        format: 'YYYY-MM-DD',
        placeholder: '请选择发货日期',
        valueFormat: 'YYYY-MM-DD',
      },
      rules: 'required',
    },
    {
      fieldName: 'recipientName',
      label: '收货人',
      component: 'Input',
      componentProps: {
        placeholder: '请输入收货人',
      },
    },
    {
      fieldName: 'recipientTelephone',
      label: '联系方式',
      component: 'Input',
      componentProps: {
        placeholder: '请输入联系方式',
      },
    },
    {
      fieldName: 'recipientAddress',
      label: '收货地址',
      component: 'Input',
      componentProps: {
        placeholder: '请输入收货地址',
      },
    },
    {
      fieldName: 'remark',
      label: '备注',
      component: 'Textarea',
      formItemClass: 'col-span-3',
      componentProps: {
        placeholder: '请输入备注',
        rows: 3,
      },
    },
  ];
}

/** 列表的搜索表单 */
export function useGridFormSchema(): VbenFormSchema[] {
  return [
    {
      fieldName: 'code',
      label: '通知单编号',
      component: 'Input',
      componentProps: {
        allowClear: true,
        placeholder: '请输入通知单编号',
      },
    },
    {
      fieldName: 'name',
      label: '通知单名称',
      component: 'Input',
      componentProps: {
        allowClear: true,
        placeholder: '请输入通知单名称',
      },
    },
    {
      fieldName: 'clientId',
      label: '客户',
      component: markRaw(CrmCustomerSelect),
      componentProps: {
        placeholder: '请选择客户',
      },
    },
  ];
}

/** 列表的字段 */
export function useGridColumns(): VxeTableGridOptions<MesWmSalesNoticeApi.SalesNotice>['columns'] {
  return [
    {
      field: 'code',
      title: '通知单编号',
      minWidth: 160,
      slots: { default: 'code' },
    },
    {
      field: 'name',
      title: '通知单名称',
      minWidth: 150,
    },
    {
      field: 'clientName',
      title: '客户名称',
      minWidth: 120,
    },
    {
      field: 'salesDate',
      title: '发货日期',
      width: 180,
      formatter: 'formatDate',
    },
    {
      field: 'recipientName',
      title: '收货人',
      minWidth: 100,
    },
    {
      field: 'recipientTelephone',
      title: '联系方式',
      minWidth: 120,
    },
    {
      field: 'recipientAddress',
      title: '收货地址',
      minWidth: 200,
    },
    {
      field: 'status',
      title: '单据状态',
      minWidth: 100,
      cellRender: {
        name: 'CellDict',
        props: { type: DICT_TYPE.MES_WM_SALES_NOTICE_STATUS },
      },
    },
    {
      field: 'outStatus',
      title: '出库状态',
      minWidth: 100,
      slots: { default: 'outStatus' },
    },
    {
      title: '操作',
      width: 200,
      fixed: 'right',
      slots: { default: 'actions' },
    },
  ];
}

/** 通知单行子表的字段 */
export function useLineGridColumns(
  editable: boolean,
): VxeTableGridOptions<MesWmSalesNoticeLineApi.SalesNoticeLine>['columns'] {
  return [
    {
      field: 'itemCode',
      title: '物料编码',
      minWidth: 120,
    },
    {
      field: 'itemName',
      title: '物料名称',
      minWidth: 140,
    },
    {
      field: 'specification',
      title: '规格型号',
      minWidth: 120,
    },
    {
      field: 'unitMeasureName',
      title: '单位',
      width: 80,
    },
    {
      field: 'quantity',
      title: '发货数量',
      width: 100,
    },
    {
      field: 'outCount',
      title: '已出库数量',
      width: 100,
      formatter: ({ cellValue }: { cellValue: number }) => (cellValue || 0).toFixed(2),
    },
    {
      field: 'outProgress',
      title: '出库进度',
      width: 120,
      cellRender: {
        name: 'CellText',
        props: {
          formatter: ({ row }: { row: MesWmSalesNoticeLineApi.SalesNoticeLine }) => {
            const quantity = row.quantity || 0;
            const outCount = row.outCount || 0;
            const percent = quantity > 0 ? Math.round((outCount / quantity) * 100) : 0;
            return `${outCount.toFixed(2)} / ${quantity.toFixed(2)} (${percent}%)`;
          },
        },
      },
    },
    {
      field: 'batchCode',
      title: '批次号',
      minWidth: 120,
    },
    {
      field: 'oqcCheckFlag',
      title: '是否检验',
      width: 90,
      cellRender: {
        name: 'CellDict',
        props: { type: DICT_TYPE.INFRA_BOOLEAN_STRING },
      },
    },
    {
      field: 'remark',
      title: '备注',
      minWidth: 120,
    },
    ...(editable
      ? [
          {
            title: '操作',
            width: 120,
            fixed: 'right',
            slots: { default: 'actions' },
          } as const,
        ]
      : []),
  ];
}

/** 正式库（合格库库存，stockState = 20）有库存的物料选项 */
export async function loadQualifiedStockItemOptions(): Promise<
  { label: string; value: number }[]
> {
  const list = await getStockSummaryByItem({
    stockState: 20,
    warehouseType: MesWmWarehouseTypeEnum.QUALIFIED,
  });
  return list.map((item: MesWmMaterialStockApi.MaterialStockSummary) => ({
    label: [item.itemName, item.itemCode, `库存 ${item.totalQuantity}`]
      .filter(Boolean)
      .join(' '),
    value: item.itemId as number,
  }));
}

/** 指定物料的正式库存批次选项 */
export async function loadQualifiedStockBatchOptions(
  itemId: number,
): Promise<{ label: string; value: number }[]> {
  const list = await getStockSummaryByBatch({
    stockState: 20,
    itemId,
    warehouseType: MesWmWarehouseTypeEnum.QUALIFIED,
  });
  return list.map((item: MesWmMaterialStockApi.MaterialStockSummary) => ({
    label: [item.batchCode, `库存 ${item.totalQuantity}`].filter(Boolean).join(' '),
    value: item.batchId as number,
  }));
}

/**
 * 可发货数量：所选物料/批次的正式库存（stockState = 20）汇总。
 *
 * 指定批次时精确到该批次，否则返回物料全部正式库存。
 */
export async function loadAvailableQuantity(
  itemId?: number,
  batchId?: number,
): Promise<number> {
  if (!itemId) {
    return 0;
  }
  if (batchId) {
    const list = await getStockSummaryByBatch({
    stockState: 20,
    itemId,
    warehouseType: MesWmWarehouseTypeEnum.QUALIFIED,
  });
    return list.find((item) => item.batchId === batchId)?.totalQuantity ?? 0;
  }
  const list = await getStockSummaryByItem({
    stockState: 20,
    itemId,
    warehouseType: MesWmWarehouseTypeEnum.QUALIFIED,
  });
  return list.find((item) => item.itemId === itemId)?.totalQuantity ?? 0;
}

/**
 * 通知单行新增/修改的表单。
 *
 * 物料、批次均从正式库库存（stockState = 20）中选择，
 * 批次选项随物料联动加载，可用库存不足由后端保存时校验。
 */
export function useLineFormSchema(): VbenFormSchema[] {
  return [
    {
      fieldName: 'itemId',
      label: '物料',
      component: 'Select',
      componentProps: {
        allowClear: true,
        filterOption: true,
        optionFilterProp: 'label',
        options: [],
        placeholder: '请选择物料（仅正式库库存）',
        showSearch: true,
      },
      rules: 'selectRequired',
    },
    {
      fieldName: 'batchId',
      label: '批次',
      component: 'Select',
      componentProps: {
        allowClear: true,
        filterOption: true,
        optionFilterProp: 'label',
        options: [],
        placeholder: '请选择批次（仅正式库库存）',
        showSearch: true,
      },
      rules: 'selectRequired',
    },
    {
      fieldName: 'quantity',
      label: '发货数量',
      component: 'InputNumber',
      componentProps: {
        class: '!w-full',
        min: 0.01,
        placeholder: '请输入发货数量（不可超过正式库存）',
        precision: 2,
      },
      rules: 'required',
    },
    {
      fieldName: 'availableQuantity',
      label: '可发货数量',
      component: 'Input',
      componentProps: {
        disabled: true,
        placeholder: '选择物料/批次后自动带出',
      },
    },
    {
      fieldName: 'oqcCheckFlag',
      label: '是否检验',
      component: 'Switch',
      rules: z.boolean().default(true),
    },
    {
      fieldName: 'remark',
      label: '备注',
      component: 'Textarea',
      formItemClass: 'col-span-3',
      componentProps: {
        placeholder: '请输入备注',
        rows: 3,
      },
    },
  ];
}
