import type { DefaultOptionType } from 'ant-design-vue/es/select';

import type { VbenFormApi, VbenFormSchema } from '#/adapter/form';
import type { VxeTableGridOptions } from '#/adapter/vxe-table';
import type { ResearchGuidelineApi } from '#/api/research/guideline';

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

import { markRaw } from 'vue';

import { getRangePickerDefaultProps } from '#/utils';

import { ResearchMemberSelect } from './components';

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

/** 课题申报书状态（对应字典 research_application_status） */
export const ApplicationStatus = {
  DRAFT: 0, // 草稿
  APPROVING: 15, // 审批中
  APPROVED: 20, // 已立项
  REJECTED: 35, // 已驳回
} as const;

/** 经费拨付状态（对应字典 research_fund_status） */
export const FundStatus = {
  PENDING: 0, // 待拨付
  APPROVING: 15, // 报销审批中
  PAID: 20, // 已拨付
  REJECTED: 30, // 已驳回
} as const;

/** 课题申报书表单配置 */
export function useFormSchema(
  formType: FormType,
  formApi?: VbenFormApi,
  guidelines: ResearchGuidelineApi.Guideline[] = [],
): VbenFormSchema[] {
  const guidelineOptions: DefaultOptionType[] = guidelines.map((item) => ({
    label: item.no ? `${item.no} ${item.title}` : item.title,
    value: item.id,
  }));

  const readonly = formType === 'detail';

  return [
    {
      fieldName: 'id',
      component: 'Input',
      dependencies: {
        triggerFields: [''],
        show: () => false,
      },
    },
    {
      fieldName: 'no',
      label: '申报编号',
      component: 'Input',
      componentProps: {
        placeholder: '申报编号由系统自动生成',
        disabled: true,
      },
      dependencies: {
        triggerFields: [''],
        show: () => formType !== 'create',
      },
    },
    {
      fieldName: 'status',
      label: '状态',
      component: 'Select',
      componentProps: {
        options: getDictOptions(DICT_TYPE.RESEARCH_APPLICATION_STATUS, 'number'),
        disabled: true,
      },
      dependencies: {
        triggerFields: [''],
        show: () => formType !== 'create',
      },
    },
    {
      fieldName: 'guidelineId',
      label: '所属课题指南',
      component: 'Select',
      componentProps: {
        options: guidelineOptions,
        placeholder: '请选择课题指南',
        allowClear: true,
        showSearch: true,
        optionFilterProp: 'label',
        disabled: readonly,
        class: '!w-full',
        onChange: (value: number) => {
          const guideline = guidelines.find((item) => item.id === value);
          formApi?.setFieldValue('category', guideline?.category);
        },
      },
      rules: 'selectRequired',
    },
    {
      fieldName: 'category',
      label: '课题类别',
      component: 'Select',
      componentProps: {
        options: getDictOptions(DICT_TYPE.RESEARCH_GUIDELINE_CATEGORY, 'number'),
        disabled: true,
        placeholder: '由所选课题指南自动带入',
      },
      help: '由所选课题指南自动带入，无需填写',
    },
    {
      fieldName: 'title',
      label: '课题名称',
      component: 'Input',
      componentProps: {
        placeholder: '请输入课题名称',
        maxlength: 255,
        disabled: readonly,
      },
      rules: 'required',
      formItemClass: 'col-span-2',
    },
    {
      fieldName: 'memberId',
      label: '申报人（会员）',
      component: markRaw(ResearchMemberSelect),
      componentProps: {
        placeholder: '请选择申报人，选择后自动带入单位、职称与联系方式',
        disabled: readonly,
        onChange: (member: Record<string, unknown> | undefined) => {
          if (!formApi) {
            return;
          }
          formApi.setFieldValue('applicantName', member?.name ?? '');
          formApi.setFieldValue('workUnit', member?.workUnit ?? '');
          formApi.setFieldValue('jobTitle', member?.title ?? '');
          formApi.setFieldValue('contactPhone', member?.contactPhone ?? '');
          formApi.setFieldValue('contactEmail', member?.contactEmail ?? '');
        },
      },
      help: '选择会员后自动带入姓名/单位/职称/联系电话/邮箱，仍可手工调整',
      formItemClass: 'col-span-2',
    },
    {
      fieldName: 'applicantName',
      label: '申报人姓名/单位名称',
      component: 'Input',
      componentProps: {
        placeholder: '请输入申报人姓名或单位名称',
        maxlength: 64,
        disabled: readonly,
      },
      rules: 'required',
    },
    {
      fieldName: 'workUnit',
      label: '工作单位',
      component: 'Input',
      componentProps: {
        placeholder: '请输入工作单位',
        maxlength: 128,
        disabled: readonly,
      },
    },
    {
      fieldName: 'jobTitle',
      label: '职称',
      component: 'Input',
      componentProps: {
        placeholder: '请输入职称',
        maxlength: 64,
        disabled: readonly,
      },
    },
    {
      fieldName: 'contactPhone',
      label: '联系电话',
      component: 'Input',
      componentProps: {
        placeholder: '请输入联系电话',
        maxlength: 20,
        disabled: readonly,
      },
    },
    {
      fieldName: 'contactEmail',
      label: '联系邮箱',
      component: 'Input',
      componentProps: {
        placeholder: '请输入联系邮箱',
        maxlength: 128,
        disabled: readonly,
      },
    },
    {
      fieldName: 'budgetAmount',
      label: '申请经费（元）',
      component: 'InputNumber',
      componentProps: {
        class: '!w-full',
        placeholder: '请输入申请经费',
        precision: 2,
        min: 0,
        formatter: erpPriceInputFormatter,
        disabled: readonly,
      },
    },
    {
      fieldName: 'teamMembers',
      label: '课题组成员',
      component: 'Textarea',
      componentProps: {
        placeholder: '每行一条，格式：姓名|单位|职称\n例如：李四|XX大学|副教授',
        autoSize: { minRows: 3, maxRows: 6 },
        disabled: readonly,
      },
      help: '每行一条，用竖线分隔：姓名|单位|职称',
      formItemClass: 'col-span-2',
    },
    {
      fieldName: 'planContent',
      label: '申报书正文',
      component: 'Textarea',
      componentProps: {
        placeholder:
          '请填写研究背景与意义、研究目标、研究方案与技术路线、预期成果与效益等内容',
        autoSize: { minRows: 8, maxRows: 16 },
        disabled: readonly,
      },
      formItemClass: 'col-span-2',
    },
    {
      fieldName: 'remark',
      label: '备注',
      component: 'Textarea',
      componentProps: {
        placeholder: '请输入备注',
        autoSize: { minRows: 2, maxRows: 3 },
        disabled: readonly,
      },
      formItemClass: 'col-span-2',
    },
    {
      fieldName: 'blobIds',
      label: '申报书附件',
      component: 'FileUpload',
      componentProps: {
        valueKey: 'id',
        maxNumber: 10,
        multiple: true,
        showDescription: !readonly,
        disabled: readonly,
      },
      formItemClass: 'col-span-2',
    },
  ];
}

/** 列表搜索表单 */
export function useGridFormSchema(): VbenFormSchema[] {
  return [
    {
      fieldName: 'no',
      label: '申报编号',
      component: 'Input',
      componentProps: {
        placeholder: '请输入申报编号',
        allowClear: true,
      },
    },
    {
      fieldName: 'title',
      label: '课题名称',
      component: 'Input',
      componentProps: {
        placeholder: '请输入课题名称',
        allowClear: true,
      },
    },
    {
      fieldName: 'category',
      label: '课题类别',
      component: 'Select',
      componentProps: {
        options: getDictOptions(DICT_TYPE.RESEARCH_GUIDELINE_CATEGORY, 'number'),
        placeholder: '请选择课题类别',
        allowClear: true,
      },
    },
    {
      fieldName: 'status',
      label: '状态',
      component: 'Select',
      componentProps: {
        options: getDictOptions(DICT_TYPE.RESEARCH_APPLICATION_STATUS, 'number'),
        placeholder: '请选择状态',
        allowClear: true,
      },
    },
    {
      fieldName: 'createTime',
      label: '创建时间',
      component: 'RangePicker',
      componentProps: {
        ...getRangePickerDefaultProps(),
        allowClear: true,
      },
    },
  ];
}

/** 列表列配置 */
export function useGridColumns(): VxeTableGridOptions['columns'] {
  return [
    {
      type: 'checkbox',
      width: 50,
      fixed: 'left',
    },
    {
      field: 'no',
      title: '申报编号',
      width: 180,
      fixed: 'left',
    },
    {
      field: 'title',
      title: '课题名称',
      minWidth: 220,
    },
    {
      field: 'guidelineTitle',
      title: '所属课题指南',
      minWidth: 180,
    },
    {
      field: 'category',
      title: '课题类别',
      minWidth: 100,
      cellRender: {
        name: 'CellDict',
        props: { type: DICT_TYPE.RESEARCH_GUIDELINE_CATEGORY },
      },
    },
    {
      field: 'applicantName',
      title: '申报人',
      minWidth: 120,
    },
    {
      field: 'workUnit',
      title: '工作单位',
      minWidth: 160,
    },
    {
      field: 'budgetAmount',
      title: '申请经费（元）',
      minWidth: 130,
      formatter: 'formatAmount2',
    },
    {
      field: 'reviewAvgScore',
      title: '评审均分',
      minWidth: 100,
      formatter: ({ cellValue }) =>
        cellValue === null || cellValue === undefined
          ? '-'
          : Number(cellValue).toFixed(2),
    },
    {
      field: 'reviewPass',
      title: '评审结论',
      minWidth: 110,
      slots: { default: 'reviewPass' },
    },
    {
      field: 'researchNo',
      title: '立项编号',
      width: 180,
    },
    {
      field: 'status',
      title: '状态',
      minWidth: 95,
      cellRender: {
        name: 'CellDict',
        props: { type: DICT_TYPE.RESEARCH_APPLICATION_STATUS },
      },
    },
    {
      field: 'hasAttachment',
      title: '附件',
      minWidth: 80,
      slots: { default: 'hasAttachment' },
    },
    {
      field: 'creatorName',
      title: '创建人',
      minWidth: 100,
    },
    {
      field: 'createTime',
      title: '创建时间',
      width: 165,
      formatter: 'formatDateTime',
    },
    {
      title: '操作',
      width: 330,
      fixed: 'right',
      slots: { default: 'actions' },
    },
  ];
}

/** 数值空值占位（VXE 列 formatter） */
function dashIfEmpty({ cellValue }: { cellValue: unknown }) {
  return cellValue === null || cellValue === undefined ? '-' : String(cellValue);
}

/** 专家评审明细列（评审面板 / 审批详情共用） */
export function useReviewColumns(
  showActions = false,
): VxeTableGridOptions['columns'] {
  const columns: VxeTableGridOptions['columns'] = [
    { type: 'seq', title: '序号', width: 55, fixed: 'left' },
    { field: 'evaluatorName', title: '专家姓名', minWidth: 100 },
    { field: 'evaluatorUnit', title: '专家单位', minWidth: 160 },
    { field: 'evaluatorTitle', title: '专家职称', minWidth: 100 },
    {
      field: 'topicScore',
      title: '选题价值（0.3）',
      minWidth: 120,
      formatter: dashIfEmpty,
    },
    {
      field: 'planScore',
      title: '方案可行性（0.3）',
      minWidth: 130,
      formatter: dashIfEmpty,
    },
    {
      field: 'teamScore',
      title: '团队基础（0.2）',
      minWidth: 120,
      formatter: dashIfEmpty,
    },
    {
      field: 'resultScore',
      title: '预期成果（0.2）',
      minWidth: 120,
      formatter: dashIfEmpty,
    },
    {
      field: 'compositeScore',
      title: '加权合计',
      minWidth: 110,
      formatter: dashIfEmpty,
    },
    {
      field: 'ranking',
      title: '排名',
      width: 70,
      formatter: dashIfEmpty,
    },
    {
      field: 'conclusion',
      title: '评审结论',
      minWidth: 110,
      cellRender: {
        name: 'CellDict',
        props: { type: DICT_TYPE.RESEARCH_REVIEW_CONCLUSION },
      },
    },
    { field: 'opinion', title: '评审意见', minWidth: 200 },
    { field: 'creatorName', title: '录入人', minWidth: 100 },
    {
      field: 'createTime',
      title: '录入时间',
      width: 165,
      formatter: 'formatDateTime',
    },
  ];
  if (showActions) {
    columns.push({
      title: '操作',
      width: 130,
      fixed: 'right',
      slots: { default: 'actions' },
    });
  }
  return columns;
}

/** 经费拨付记录列（拨付面板 / 审批详情共用） */
export function useFundColumns(
  showActions = false,
): VxeTableGridOptions['columns'] {
  const columns: VxeTableGridOptions['columns'] = [
    { type: 'seq', title: '序号', width: 55 },
    { field: 'batchName', title: '拨付批次', minWidth: 130 },
    {
      field: 'amount',
      title: '拨付金额（元）',
      minWidth: 130,
      formatter: 'formatAmount2',
    },
    {
      field: 'payDate',
      title: '拨付日期',
      width: 120,
      formatter: dashIfEmpty,
    },
    { field: 'payee', title: '收款单位/账户名', minWidth: 180 },
    {
      field: 'status',
      title: '拨付状态',
      minWidth: 110,
      cellRender: {
        name: 'CellDict',
        props: { type: DICT_TYPE.RESEARCH_FUND_STATUS },
      },
    },
    {
      field: 'reimbursementNo',
      title: '财务报销单号',
      minWidth: 160,
      formatter: dashIfEmpty,
    },
    {
      field: 'rejectReason',
      title: '驳回原因',
      minWidth: 200,
      formatter: dashIfEmpty,
    },
    {
      field: 'hasAttachment',
      title: '拨付凭证',
      minWidth: 100,
      slots: { default: 'hasAttachment' },
    },
    { field: 'creatorName', title: '登记人', minWidth: 100 },
    {
      field: 'createTime',
      title: '登记时间',
      width: 165,
      formatter: 'formatDateTime',
    },
  ];
  if (showActions) {
    columns.push({
      title: '操作',
      width: 130,
      fixed: 'right',
      slots: { default: 'actions' },
    });
  }
  return columns;
}
