import type { VbenFormSchema } from '#/adapter/form';
import type { VxeTableGridOptions } from '#/adapter/vxe-table';
import type { MesProWorktimeApi } from '#/api/mes/pro/worktime';

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

import { z } from '#/adapter/form';
import { getProcessSimpleList } from '#/api/mes/pro/process';
import { getWorkstationPage } from '#/api/mes/md/workstation';

/** 计量方式 */
export const MEASURE_TYPE_OPTIONS = [
  { label: '按次', value: 1 },
  { label: '按个', value: 2 },
  { label: '按盘', value: 3 },
  { label: '按米折算', value: 4 },
];

export function getMeasureTypeLabel(measureType?: number) {
  return (
    MEASURE_TYPE_OPTIONS.find((item) => item.value === measureType)?.label ?? '-'
  );
}

/** 计薪方式：0-不计薪 1-按工序辅助小时工资 2-按本项单价 */
export const WAGE_MODE_OPTIONS = [
  { label: '不计薪', value: 0 },
  { label: '按工序辅助小时工资', value: 1 },
  { label: '按本项单价', value: 2 },
];

export function getWageModeLabel(wageMode?: number) {
  return (
    WAGE_MODE_OPTIONS.find((item) => item.value === wageMode)?.label ?? '不计薪'
  );
}

const loadProcessOptions = async () => {
  const list = await getProcessSimpleList();
  return (list ?? []).map((item) => ({
    label: item.name ?? '',
    value: item.id ?? 0,
  }));
};

const loadWorkstationOptions = async () => {
  const result = await getWorkstationPage({ pageNo: 1, pageSize: 500 });
  return (result?.list ?? []).map((item) => ({
    label: item.name ?? '',
    value: item.id ?? 0,
  }));
};

/** 新增/修改辅助工时项目 */
export function useFormSchema(): VbenFormSchema[] {
  return [
    {
      fieldName: 'id',
      component: 'Input',
      dependencies: { triggerFields: [''], show: () => false },
    },
    {
      fieldName: 'processId',
      label: '工序',
      component: 'ApiSelect',
      componentProps: {
        api: loadProcessOptions,
        labelField: 'label',
        valueField: 'value',
        placeholder: '请选择工序',
        showSearch: true,
        filterOption: true,
      },
      rules: 'selectRequired',
    },
    {
      fieldName: 'workstationId',
      label: '适用机台',
      component: 'ApiSelect',
      componentProps: {
        allowClear: true,
        api: loadWorkstationOptions,
        labelField: 'label',
        valueField: 'value',
        placeholder: '不选表示不限机台',
        showSearch: true,
        filterOption: true,
      },
    },
    {
      fieldName: 'itemCode',
      label: '项目编码',
      component: 'Input',
      componentProps: {
        maxLength: 64,
        placeholder: '如 AUX_REEL_CHANGE',
      },
      rules: z.string().min(1, '项目编码不能为空').max(64),
    },
    {
      fieldName: 'itemName',
      label: '项目名称',
      component: 'Input',
      componentProps: {
        maxLength: 100,
        placeholder: '如 上下放线盘',
      },
      rules: z.string().min(1, '项目名称不能为空').max(100),
    },
    {
      fieldName: 'measureType',
      label: '计量方式',
      component: 'Select',
      componentProps: {
        options: MEASURE_TYPE_OPTIONS,
        placeholder: '请选择计量方式',
      },
      rules: z.number().default(1),
    },
    {
      fieldName: 'wageMode',
      label: '计薪方式',
      component: 'Select',
      componentProps: {
        options: WAGE_MODE_OPTIONS,
        placeholder: '请选择辅助工时计薪方式',
      },
      rules: z.number().default(1),
    },
    {
      fieldName: 'wageRate',
      label: '计薪单价',
      component: 'InputNumber',
      dependencies: {
        triggerFields: ['wageMode'],
        show: (values) => values.wageMode === 2,
      },
      componentProps: {
        addonAfter: '元/小时',
        class: 'w-full',
        min: 0,
        precision: 4,
        placeholder: '本项辅助工时的小时工资',
      },
      rules: z.number().min(0).optional(),
    },
    {
      fieldName: 'durationMinutes',
      label: '单项分钟数',
      component: 'InputNumber',
      dependencies: {
        triggerFields: ['measureType'],
        show: (values) => values.measureType !== 4,
      },
      componentProps: {
        class: 'w-full',
        min: 0,
        precision: 2,
        placeholder: '单次/单个/单盘的耗时分钟数',
      },
      rules: z.number().min(0).optional(),
    },
    {
      fieldName: 'speedMPerMin',
      label: '折算速度',
      component: 'InputNumber',
      dependencies: {
        triggerFields: ['measureType'],
        show: (values) => values.measureType === 4,
      },
      componentProps: {
        class: 'w-full',
        addonAfter: '米/分',
        min: 0,
        precision: 2,
        placeholder: '按米折算时：时间 = 米数 ÷ 速度',
      },
      rules: z.number().min(0).optional(),
    },
    {
      fieldName: 'materialFrom',
      label: '原色/材料',
      component: 'Input',
      componentProps: {
        maxLength: 100,
        placeholder: '换色场景填写起始材料，如 PVC',
      },
    },
    {
      fieldName: 'materialTo',
      label: '目标色/材料',
      component: 'Input',
      componentProps: {
        maxLength: 100,
        placeholder: '换色场景填写目标材料，如 LSZH',
      },
    },
    {
      fieldName: 'status',
      label: '状态',
      component: 'RadioGroup',
      componentProps: {
        buttonStyle: 'solid',
        optionType: 'button',
        options: getDictOptions(DICT_TYPE.COMMON_STATUS, 'number'),
      },
      rules: z.number().default(CommonStatusEnum.ENABLE),
    },
    {
      fieldName: 'sort',
      label: '排序',
      component: 'InputNumber',
      componentProps: {
        class: 'w-full',
        min: 0,
        precision: 0,
      },
      rules: z.number().default(0),
    },
    {
      fieldName: 'remark',
      label: '备注',
      component: 'Textarea',
      formItemClass: 'col-span-2',
      componentProps: {
        maxLength: 250,
        placeholder: '请输入备注',
        rows: 2,
      },
    },
  ];
}

/** 列表搜索 */
export function useGridFormSchema(): VbenFormSchema[] {
  return [
    {
      fieldName: 'processId',
      label: '工序',
      component: 'ApiSelect',
      componentProps: {
        allowClear: true,
        api: loadProcessOptions,
        labelField: 'label',
        valueField: 'value',
        placeholder: '请选择工序',
        showSearch: true,
        filterOption: true,
      },
    },
    {
      fieldName: 'itemName',
      label: '项目名称',
      component: 'Input',
      componentProps: {
        allowClear: true,
        placeholder: '请输入项目名称',
      },
    },
    {
      fieldName: 'status',
      label: '状态',
      component: 'Select',
      componentProps: {
        allowClear: true,
        options: getDictOptions(DICT_TYPE.COMMON_STATUS, 'number'),
        placeholder: '请选择状态',
      },
    },
  ];
}

/** 列表字段 */
export function useGridColumns(): VxeTableGridOptions<MesProWorktimeApi.AuxItem>['columns'] {
  return [
    { field: 'processName', title: '工序', minWidth: 150 },
    {
      field: 'workstationName',
      title: '适用机台',
      minWidth: 150,
      formatter: ({ cellValue }) => cellValue || '不限机台',
    },
    { field: 'itemName', title: '辅助项目', minWidth: 160 },
    { field: 'itemCode', title: '项目编码', minWidth: 150 },
    {
      field: 'measureType',
      title: '计量方式',
      width: 110,
      formatter: ({ cellValue }) => getMeasureTypeLabel(cellValue),
    },
    {
      field: 'wageMode',
      title: '计薪方式',
      width: 150,
      formatter: ({ cellValue }) => getWageModeLabel(cellValue),
    },
    {
      field: 'wageRate',
      title: '计薪单价',
      width: 120,
      formatter: ({ cellValue, row }) =>
        row.wageMode === 2 && cellValue != null ? `${cellValue} 元/小时` : '-',
    },
    { field: 'durationMinutes', title: '单项分钟数', width: 110 },
    {
      field: 'speedMPerMin',
      title: '折算速度(m/分)',
      width: 130,
      formatter: ({ cellValue }) => cellValue || '-',
    },
    {
      field: 'materialFrom',
      title: '换色材料',
      minWidth: 160,
      formatter: ({ row }) =>
        row.materialFrom || row.materialTo
          ? `${row.materialFrom || '-'} → ${row.materialTo || '-'}`
          : '-',
    },
    {
      field: 'status',
      title: '状态',
      width: 90,
      cellRender: {
        name: 'CellDict',
        props: { type: DICT_TYPE.COMMON_STATUS },
      },
    },
    { field: 'sort', title: '排序', width: 80 },
    {
      title: '操作',
      width: 160,
      fixed: 'right',
      slots: { default: 'actions' },
    },
  ];
}
