import type { VbenFormSchema } from '#/adapter/form';
import type { VxeTableGridOptions } from '#/adapter/vxe-table';
import type { QcReportInstanceApi } from '#/api/mes/qc/report/instance';
import type { QcReportTemplateApi } from '#/api/mes/qc/report/template';
import type { SystemUserApi } from '#/api/system/user';

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

import { getTemplatePage } from '#/api/mes/qc/report/template';
import { getSimpleUserList } from '#/api/system/user';
import { getRangePickerDefaultProps } from '#/utils';

/**
 * 业务单据类型 → 展示名。
 * <p>
 * 后端把 businessType 定义成自由字符串（没有枚举约束），这里只把已知的四种质检单翻成中文，
 * 认不出的一律原样显示——比猜错成另一种单据要诚实。
 */
const BUSINESS_TYPE_LABEL: Record<string, string> = {
  mes_qc_iqc: '来料检验',
  mes_qc_ipqc: '过程检验',
  mes_qc_oqc: '出货检验',
  mes_qc_rqc: '退货检验',
};

export function businessTypeLabel(value?: string): string {
  if (!value) {
    return '';
  }
  return BUSINESS_TYPE_LABEL[value] ?? value;
}

/** 关联数据：实例表只存了模板编号与创建人编号，名称都要另查一次 */
let templateList: QcReportTemplateApi.Template[] = [];
getTemplatePage({ pageNo: 1, pageSize: 100 }).then(
  (data) => (templateList = data.list ?? []),
);

let userList: SystemUserApi.User[] = [];
getSimpleUserList().then((data) => (userList = data));

/** 列表的搜索表单 */
export function useGridFormSchema(): VbenFormSchema[] {
  return [
    {
      fieldName: 'reportNo',
      label: '报告编号',
      component: 'Input',
      componentProps: {
        allowClear: true,
        placeholder: '请输入报告编号',
      },
    },
    {
      fieldName: 'businessType',
      label: '业务类型',
      component: 'Select',
      componentProps: {
        allowClear: true,
        options: Object.entries(BUSINESS_TYPE_LABEL).map(([value, label]) => ({
          label,
          value,
        })),
        placeholder: '请选择业务类型',
      },
    },
    {
      fieldName: 'businessId',
      label: '业务单据',
      component: 'Input',
      componentProps: {
        allowClear: true,
        placeholder: '请输入业务单据编号（精确匹配）',
      },
    },
    {
      fieldName: 'status',
      label: '报告状态',
      component: 'Select',
      componentProps: {
        allowClear: true,
        options: getDictOptions(DICT_TYPE.QC_REPORT_INSTANCE_STATUS, 'number'),
        placeholder: '请选择报告状态',
      },
    },
    {
      fieldName: 'createTime',
      label: '生成时间',
      component: 'RangePicker',
      componentProps: {
        ...getRangePickerDefaultProps(),
        allowClear: true,
      },
    },
  ];
}

/** 列表的字段 */
export function useGridColumns(): VxeTableGridOptions<QcReportInstanceApi.Instance>['columns'] {
  return [
    {
      field: 'reportNo',
      title: '报告编号',
      width: 180,
    },
    {
      field: 'templateId',
      title: '报告模板',
      minWidth: 200,
      formatter: ({ row }) =>
        templateList.find((item) => item.id === row.templateId)?.templateName ??
        `模板 #${row.templateId}`,
    },
    {
      field: 'templateVersion',
      title: '版本',
      width: 100,
      slots: { default: 'templateVersion' },
    },
    {
      field: 'businessType',
      title: '业务类型',
      width: 120,
      formatter: ({ row }) => businessTypeLabel(row.businessType),
    },
    {
      field: 'businessId',
      title: '业务单据',
      width: 180,
      formatter: ({ row }) => row.businessId || '—',
    },
    {
      field: 'status',
      title: '状态',
      width: 110,
      cellRender: {
        name: 'CellDict',
        props: { type: DICT_TYPE.QC_REPORT_INSTANCE_STATUS },
      },
    },
    {
      field: 'creator',
      title: '生成人',
      width: 120,
      formatter: ({ row }) =>
        userList.find((user) => String(user.id) === String(row.creator))
          ?.nickname ??
        row.creator ??
        '—',
    },
    {
      field: 'createTime',
      title: '生成时间',
      width: 180,
      formatter: 'formatDateTime',
    },
    {
      title: '操作',
      width: 200,
      fixed: 'right',
      slots: { default: 'actions' },
    },
  ];
}
