import type { VbenFormSchema } from '#/adapter/form';
import type { VxeTableGridOptions } from '#/adapter/vxe-table';
import type { MesWmMaterialStockApi } from '#/api/mes/wm/materialstock';

import { markRaw } from 'vue';

import { MdItemSelect } from '#/views/mes/md/item/components';
import { WmWarehouseSelect } from '../warehouse/components';

export type SummaryDimension = 'item' | 'batch' | 'warehouse';

export const SUMMARY_DIMENSION_OPTIONS: {
  label: string;
  value: SummaryDimension;
}[] = [
  { label: '按品种汇总', value: 'item' },
  { label: '按批次汇总', value: 'batch' },
  { label: '按仓库汇总', value: 'warehouse' },
];

/** 汇总查询表单 */
export function useGridFormSchema(): VbenFormSchema[] {
  return [
    {
      fieldName: 'itemId',
      label: '品种',
      component: markRaw(MdItemSelect),
      componentProps: {
        placeholder: '请选择品种',
      },
    },
    {
      fieldName: 'batchCode',
      label: '批次号',
      component: 'Input',
      componentProps: {
        allowClear: true,
        placeholder: '请输入批次号',
      },
    },
    {
      fieldName: 'warehouseId',
      label: '仓库',
      component: markRaw(WmWarehouseSelect),
      componentProps: {
        placeholder: '请选择仓库',
      },
    },
    {
      fieldName: 'stockState',
      label: '库存状态',
      component: 'Select',
      componentProps: {
        allowClear: true,
        options: [
          { label: '暂存库（待质检）', value: 10 },
          { label: '合格库（正式库存）', value: 20 },
          { label: '已出库（销售扣减）', value: 30 },
        ],
        placeholder: '请选择库存状态',
      },
    },
  ];
}

/** 汇总列表字段 */
export function useGridColumns(
  dimension: SummaryDimension,
): VxeTableGridOptions<MesWmMaterialStockApi.MaterialStockSummary>['columns'] {
  const base: VxeTableGridOptions<MesWmMaterialStockApi.MaterialStockSummary>['columns'] = [
    {
      field: 'stockState',
      title: '库存状态',
      width: 110,
      cellRender: {
        name: 'CellTag',
        props: {
          options: [
            { label: '暂存库', value: 10, color: 'orange' },
            { label: '合格库', value: 20, color: 'green' },
            { label: '已出库', value: 30, color: 'default' },
          ],
        },
      },
    },
    {
      field: 'totalQuantity',
      title: '汇总数量',
      width: 120,
    },
  ];
  if (dimension === 'item') {
    return [
      {
        field: 'itemCode',
        title: '品种编码',
        minWidth: 120,
      },
      {
        field: 'itemName',
        title: '品种名称',
        minWidth: 140,
      },
      ...base,
    ];
  }
  if (dimension === 'batch') {
    return [
      {
        field: 'itemName',
        title: '品种名称',
        minWidth: 140,
      },
      {
        field: 'batchCode',
        title: '批次号',
        minWidth: 160,
      },
      ...base,
    ];
  }
  return [
    {
      field: 'warehouseName',
      title: '仓库名称',
      minWidth: 140,
    },
    ...base,
  ];
}
