import type { VbenFormApi, VbenFormSchema } from '#/adapter/form';
import type { VxeTableGridOptions } from '#/adapter/vxe-table';
import type { MesWmReturnSalesApi } from '#/api/mes/wm/returnsales';
import type { MesWmReturnSalesDetailApi } from '#/api/mes/wm/returnsales/detail';
import type { MesWmReturnSalesLineApi } from '#/api/mes/wm/returnsales/line';

import { h, markRaw } from 'vue';

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

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

import CrmCustomerSelect from '#/components/crm-customer-select.vue';
import { generateAutoCode } from '#/api/mes/md/autocode/record';
import { MdmItemSelect } from '#/views/basicData/mdm/components';
import { WmBatchSelect } from '#/views/wls/batch/components';
import { WmWarehouseSelect } from '#/views/wls/warehouse/components';

import {
  WmReturnSalesProductSalesLineSelect,
  WmReturnSalesProductSalesSelect,
} from './components';

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

/** 表单头部是否只读（上架、详情、执行退货态） */
function isHeaderReadonly(formType: FormType): boolean {
  return formType === 'detail' || formType === 'finish' || formType === 'stock';
}

/** 新增/修改的表单 */
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_RETURN_SALES_CODE,
                  );
                  await formApi?.setFieldValue('code', code);
                },
              },
              { default: () => '生成' },
            ),
    },
    {
      fieldName: 'name',
      label: '退货单名称',
      component: 'Input',
      componentProps: {
        placeholder: '请输入退货单名称',
      },
      rules: 'required',
    },
    {
      fieldName: 'productSalesId',
      label: '销售出库单',
      component: markRaw(WmReturnSalesProductSalesSelect),
      componentProps: {
        disabled: isHeaderReadonly(formType),
        // 选择出库单后自动带出客户
        onChange: async (
          productSales?: MesWmReturnSalesApi.ReturnableProductSales,
        ) => {
          await formApi?.setFieldValue('clientId', productSales?.clientId);
        },
      },
    },
    {
      fieldName: 'clientId',
      label: '客户',
      component: markRaw(CrmCustomerSelect),
      componentProps: {
        placeholder: '请选择客户',
      },
      rules: 'selectRequired',
    },
    {
      fieldName: 'returnDate',
      label: '退货日期',
      component: 'DatePicker',
      componentProps: {
        class: '!w-full',
        format: 'YYYY-MM-DD',
        placeholder: '请选择退货日期',
        valueFormat: 'YYYY-MM-DD',
      },
      rules: 'required',
    },
    {
      fieldName: 'returnReason',
      label: '退货原因',
      component: 'Textarea',
      formItemClass: 'col-span-3',
      componentProps: {
        placeholder: '请输入退货原因',
        rows: 2,
      },
      rules: 'required',
    },
    {
      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: '请选择客户',
      },
    },
    {
      fieldName: 'status',
      label: '单据状态',
      component: 'Select',
      componentProps: {
        allowClear: true,
        options: getDictOptions(DICT_TYPE.MES_WM_RETURN_SALES_STATUS, 'number'),
        placeholder: '请选择单据状态',
      },
    },
  ];
}

/** 列表的字段 */
export function useGridColumns(): VxeTableGridOptions<MesWmReturnSalesApi.ReturnSales>['columns'] {
  return [
    {
      field: 'code',
      title: '退货单编号',
      minWidth: 160,
      slots: { default: 'code' },
    },
    {
      field: 'name',
      title: '退货单名称',
      minWidth: 150,
    },
    {
      field: 'productSalesCode',
      title: '销售出库单号',
      minWidth: 160,
    },
    {
      field: 'clientCode',
      title: '客户编码',
      minWidth: 120,
    },
    {
      field: 'clientName',
      title: '客户名称',
      minWidth: 150,
    },
    {
      field: 'returnReason',
      title: '退货原因',
      minWidth: 150,
    },
    {
      field: 'returnDate',
      title: '退货日期',
      width: 180,
      formatter: 'formatDate',
    },
    {
      field: 'status',
      title: '单据状态',
      minWidth: 110,
      cellRender: {
        name: 'CellDict',
        props: { type: DICT_TYPE.MES_WM_RETURN_SALES_STATUS },
      },
    },
    {
      title: '操作',
      width: 240,
      fixed: 'right',
      slots: { default: 'actions' },
    },
  ];
}

/** 退货单行子表的字段 */
export function useLineGridColumns(
  editable: boolean,
  stockable: boolean,
): VxeTableGridOptions<MesWmReturnSalesLineApi.ReturnSalesLine>['columns'] {
  return [
    {
      type: 'expand',
      width: 48,
      slots: { content: 'detail' },
    },
    {
      field: 'itemCode',
      title: '物料编码',
      minWidth: 120,
    },
    {
      field: 'itemName',
      title: '物料名称',
      minWidth: 140,
    },
    {
      field: 'itemSpecification',
      title: '规格型号',
      minWidth: 120,
    },
    {
      field: 'itemUnit',
      title: '单位',
      width: 80,
    },
    {
      field: 'quantity',
      title: '退货数量',
      width: 100,
    },
    {
      field: 'batchCode',
      title: '批次号',
      minWidth: 120,
    },
    ...(editable || stockable
      ? [
          {
            title: '操作',
            width: 160,
            fixed: 'right',
            slots: { default: 'actions' },
          } as const,
        ]
      : []),
  ];
}

/** 退货单行新增/修改的表单 */
export function useLineFormSchema(
  options: { clientId?: number; productSalesId?: number } = {},
  formApi?: VbenFormApi,
): VbenFormSchema[] {
  const { clientId, productSalesId } = options;
  const hasProductSales = !!productSalesId; // 关联了销售出库单时，物料/批次由出库行带入
  return [
    {
      fieldName: 'productSalesLineId',
      label: '出库行',
      component: markRaw(WmReturnSalesProductSalesLineSelect),
      componentProps: {
        // 选择出库行后自动带入物料、批次与可退数量
        onChange: async (
          line?: MesWmReturnSalesApi.ReturnableProductSalesLine,
        ) => {
          await formApi?.setValues({
            batchCode: line?.batchCode,
            itemId: line?.itemId,
            quantity: line?.returnableQuantity,
            returnableQuantity: line?.returnableQuantity,
          });
        },
        productSalesId,
      },
      rules: hasProductSales ? 'selectRequired' : undefined,
      dependencies: {
        triggerFields: [''],
        if: () => hasProductSales,
      },
    },
    {
      fieldName: 'itemId',
      label: '物料',
      component: markRaw(MdmItemSelect),
      componentProps: {
        placeholder: '请选择物料',
      },
      rules: 'selectRequired',
      dependencies: {
        triggerFields: ['productSalesLineId'],
        componentProps: (values) => ({
          disabled: hasProductSales || !!values.productSalesLineId,
          placeholder: '请选择物料',
        }),
      },
    },
    {
      fieldName: 'batchId',
      label: '批次',
      component: markRaw(WmBatchSelect),
      componentProps: {
        clientId,
        disabled: true,
        placeholder: '请选择批次',
      },
      dependencies: {
        triggerFields: ['itemId'],
        if: () => !hasProductSales,
        componentProps: (values) => ({
          clientId,
          disabled: true,
          itemId: values.itemId,
          placeholder: '请选择批次',
        }),
      },
    },
    {
      fieldName: 'batchCode',
      label: '批次号',
      component: 'Input',
      componentProps: {
        disabled: true,
        placeholder: '由出库行带入',
      },
      dependencies: {
        triggerFields: [''],
        if: () => hasProductSales,
      },
    },
    {
      fieldName: 'returnableQuantity',
      label: '可退数量',
      component: 'Input',
      componentProps: {
        disabled: true,
        placeholder: '选择出库行后自动带出',
      },
      dependencies: {
        triggerFields: [''],
        if: () => hasProductSales,
      },
    },
    {
      fieldName: 'quantity',
      label: '退货数量',
      component: 'InputNumber',
      componentProps: {
        class: '!w-full',
        min: 0,
        placeholder: '请输入退货数量',
        precision: 2,
      },
      rules: 'required',
      dependencies: {
        triggerFields: ['returnableQuantity'],
        componentProps: (values) => ({
          max: hasProductSales
            ? (values.returnableQuantity as number | undefined)
            : undefined,
        }),
      },
    },
    {
      fieldName: 'remark',
      label: '备注',
      component: 'Textarea',
      formItemClass: 'col-span-3',
      componentProps: {
        placeholder: '请输入备注',
        rows: 3,
      },
    },
  ];
}

/** 上架明细子表的字段 */
export function useDetailGridColumns(
  stockable: boolean,
): VxeTableGridOptions<MesWmReturnSalesDetailApi.ReturnSalesDetail>['columns'] {
  return [
    {
      field: 'batchCode',
      title: '批次号',
      minWidth: 120,
    },
    {
      field: 'warehouseName',
      title: '仓库名称',
      minWidth: 100,
    },
    {
      field: 'quantity',
      title: '数量',
      width: 100,
    },
    ...(stockable
      ? [
          {
            title: '操作',
            width: 120,
            fixed: 'right',
            slots: { default: 'actions' },
          } as const,
        ]
      : []),
  ];
}

/** 上架明细新增/修改的表单 */
export function useDetailFormSchema(formApi?: VbenFormApi): VbenFormSchema[] {
  return [
    {
      fieldName: 'itemId',
      label: '物料',
      component: markRaw(MdmItemSelect),
      componentProps: {
        disabled: true,
      },
    },
    {
      fieldName: 'warehouseId',
      label: '入库仓库',
      component: markRaw(WmWarehouseSelect),
      componentProps: {
        placeholder: '请选择仓库',
      },
      rules: 'selectRequired',
    },
    {
      fieldName: 'batchCode',
      label: '批次号',
      component: 'Input',
      componentProps: {
        disabled: true,
        placeholder: '由退货行带入',
      },
    },
    {
      fieldName: 'quantity',
      label: '数量',
      component: 'InputNumber',
      componentProps: {
        class: '!w-full',
        min: 0,
        placeholder: '请输入数量',
        precision: 2,
      },
      rules: 'required',
    },
  ];
}
