/*
 * 策略注册表（扩展版，含列增强）
 */
import React from 'react';
import { ProColumns } from '@ant-design/pro-components';
import {
  unitPersonnelCostCalc,
  patientCostCalc,
  medicalMaterialCostCalc,
  chargeItemCostCalc,
  diseaseCostCalculation,
  DRG_DIPCostCalc,
  clinicalPathway,
  medicalOrderItem,
  incomeCollection,
  costShare,
  beforeCollectionSearch,
  afterCollectionSearch,
  beforeCostShareSearch,
  afterCostShareSearch,
  departmentCostCalculate,
  wholeHospCostCalculate,
  projectShareParamsCalc,
  costShareReportTable,
  departmentOperatingReport,
  wholeHospOperatingReport,
  deptDirectMedicalCost,
  deptFullDirectCost,
  clinicalDeptMedicalCost,
  clinicalDeptFullCost,
} from './columns';
import {
  unitPersonnelCostCalcFilterConf,
  patientCostCalcFilterConf,
  medicalMaterialCostCalcFilterConf,
  chargeItemCostCalcFilterConf,
  diseaseCostCalculationFilterConf,
  DRG_DIPCostCalcFilterConf,
  clinicalPathwayFilterConf,
  medicalOrderItemFilterConf,
  beforeCollectionSearchFilterConf,
  afterCollectionSearchFilterConf,
  beforeCostShareSearchFilterConf,
  afterCostShareSearchFilterConf,
  projectShareParamsCalcFilterConf,
  projectCostCalcFilterConf,
  PatientItemCalcFilterConf,
  standardItemCostCalcFilterConf,
  patientStandItemCostCalcFilterConf,
  standItemShareCostCalcFilterConf,
  departmentCostCalculateFilterConf,
  deptDirectMedicalCostFilterConf,
  deptFullDirectCostFilterConf,
  clinicalDeptMedicalCostFilterConf,
  clinicalDeptFullCostFilterConf,
  medicalServiceCostDetailFilterConf,
  hospitalServiceProjectCostFilterConf,
} from './config';
import { getParamsDataBySysId } from '@/services/getDic';

export interface CalcPageStrategy {
  key: string;
  buildColumns: () => ProColumns[];
  filterConf: any[];
  scrollX: number;
  showCalcButton: boolean;
  enhanceColumns?: (columns: ProColumns[], ctx: any) => ProColumns[];
  resolveButtons?: (ctx: any) => { [k: string]: boolean };
  tablePropsBuilder?: (ctx: any) => any;
  onMount?: (ctx: any) => Promise<void> | void;
}

const STRATEGIES: Record<string, CalcPageStrategy> = {
  unitPersonnelCostCalc: {
    key: 'unitPersonnelCostCalc',
    buildColumns: () => unitPersonnelCostCalc,
    filterConf: unitPersonnelCostCalcFilterConf,
    scrollX: 1000,
    showCalcButton: true,
  },
  patientCostCalc: {
    key: 'patientCostCalc',
    buildColumns: () => patientCostCalc,
    filterConf: patientCostCalcFilterConf,
    scrollX: 1500,
    showCalcButton: true,
  },
  medicalMaterialCostCalc: {
    key: 'medicalMaterialCostCalc',
    buildColumns: () => medicalMaterialCostCalc,
    filterConf: medicalMaterialCostCalcFilterConf,
    scrollX: 1200,
    showCalcButton: true,
  },
  chargeItemCostCalc: {
    key: 'chargeItemCostCalc',
    buildColumns: () => chargeItemCostCalc,
    filterConf: chargeItemCostCalcFilterConf,
    scrollX: 1500,
    showCalcButton: true,
  },
  diseaseCostCalculation: {
    key: 'diseaseCostCalculation',
    buildColumns: () => diseaseCostCalculation,
    filterConf: diseaseCostCalculationFilterConf,
    scrollX: 1500,
    showCalcButton: true,
  },
  DRG_DIPCostCalc: {
    key: 'DRG_DIPCostCalc',
    buildColumns: () => DRG_DIPCostCalc,
    filterConf: DRG_DIPCostCalcFilterConf,
    scrollX: 1500,
    showCalcButton: true,
  },
  clinicalPathway: {
    key: 'clinicalPathway',
    buildColumns: () => clinicalPathway,
    filterConf: clinicalPathwayFilterConf,
    scrollX: 1500,
    showCalcButton: true,
  },
  medicalOrderItem: {
    key: 'medicalOrderItem',
    buildColumns: () => medicalOrderItem,
    filterConf: medicalOrderItemFilterConf,
    scrollX: 1500,
    showCalcButton: true,
  },
  beforeCollectionSearch: {
    key: 'beforeCollectionSearch',
    buildColumns: () => beforeCollectionSearch,
    filterConf: beforeCollectionSearchFilterConf,
    scrollX: 1500,
    showCalcButton: false,
  },
  afterCollectionSearch: {
    key: 'afterCollectionSearch',
    buildColumns: () => afterCollectionSearch,
    filterConf: afterCollectionSearchFilterConf,
    scrollX: 1300,
    showCalcButton: false,
  },
  incomeCollection: {
    key: 'incomeCollection',
    buildColumns: () => incomeCollection,
    filterConf: [],
    scrollX: 600,
    showCalcButton: false,
    enhanceColumns: (cols, ctx) => {
      const { onIncomeAction } = ctx;
      return [
        ...cols,
        {
          title: '操作',
          dataIndex: 'option',
          width: 90,
          render: (_: any, record: any) => (
            <a
              style={{ fontSize: 14 }}
              onClick={() => onIncomeAction(record.isCollection, record)}
            >
              {record.isCollection ? '撤销归集' : '开始归集'}
            </a>
          ),
        } as ProColumns,
      ];
    },
  },
  costShare: {
    key: 'costShare',
    buildColumns: () => costShare,
    filterConf: [],
    scrollX: 600,
    showCalcButton: false,
    enhanceColumns: (cols, ctx) => {
      const { Popconfirm, onShareAction } = ctx;
      return [
        ...cols,
        {
          title: '操作',
          align: 'right',
          dataIndex: 'option',
          width: '15%',
          render: (_: any, record: any) =>
            !record.isAllocation ? (
              <a
                style={{ fontSize: 14 }}
                onClick={() => onShareAction(record.isAllocation, record)}
              >
                {record.isAllocation ? '撤销' : '分摊'}
              </a>
            ) : (
              [
                <Popconfirm
                  title={`是否确认撤销？`}
                  key="del"
                  onConfirm={() => onShareAction(record.isAllocation, record)}
                >
                  <a style={{ fontSize: 14 }}>
                    {record.isAllocation ? '撤销' : '分摊'}
                  </a>
                </Popconfirm>,
              ]
            ),
        } as ProColumns,
      ];
    },
  },
  beforeCostShareSearch: {
    key: 'beforeCostShareSearch',
    buildColumns: () => beforeCostShareSearch,
    filterConf: beforeCostShareSearchFilterConf,
    scrollX: 1300,
    showCalcButton: false,
  },
  afterCostShareSearch: {
    key: 'afterCostShareSearch',
    buildColumns: () => afterCostShareSearch,
    filterConf: afterCostShareSearchFilterConf,
    scrollX: 1000,
    showCalcButton: false,
  },
  departmentCostCalculate: {
    key: 'departmentCostCalculate',
    buildColumns: () => departmentCostCalculate,
    filterConf: departmentCostCalculateFilterConf,
    scrollX: 1200,
    showCalcButton: true,
  },
  wholeHospCostCalculate: {
    key: 'wholeHospCostCalculate',
    buildColumns: () => wholeHospCostCalculate,
    filterConf: [],
    scrollX: 1200,
    showCalcButton: true,
    onMount: async (ctx: any) => {
      try {
        const raw = localStorage.getItem('currentSelectedTab');
        const parsed = raw ? JSON.parse(raw) : null;
        const systemId = parsed?.systemId;
        if (!systemId) return;
        const resp = await getParamsDataBySysId(
          systemId,
          '1851077044079824896',
        );
        const showPercent = resp && resp.value == '1';
        if (!showPercent && Array.isArray(ctx?.columns)) {
          const filtered = (ctx.columns as ProColumns[]).filter(
            (c: any) => c?.title !== '占比',
          );
          ctx.setColumns && ctx.setColumns(filtered);
        }
      } catch {}
    },
  },
  costShareReportTable: {
    key: 'costShareReportTable',
    buildColumns: () => costShareReportTable,
    filterConf: [],
    scrollX: 1200,
    showCalcButton: false,
    enhanceColumns: (cols, ctx) => {
      const { downloadTemplateReq } = ctx;
      return [
        ...cols,
        {
          title: '操作',
          dataIndex: 'option',
          width: '15%',
          render: (_: any, record: any) => [
            <a
              style={{ fontSize: 14 }}
              onClick={async () => {
                const { year, month, shareLevel, shareLevelId } = record;
                await downloadTemplateReq(
                  '/costAccount/excel/getShareReportTemplate',
                  { year, month, levelSort: shareLevel, shareLevelId },
                ).catch(() => {});
              }}
            >
              下载
            </a>,
          ],
        } as ProColumns,
      ];
    },
  },
  departmentOperatingReport: {
    key: 'departmentOperatingReport',
    buildColumns: () => departmentOperatingReport,
    filterConf: [],
    scrollX: 1000,
    showCalcButton: false,
    enhanceColumns: (cols) => [
      ...cols,
      {
        title: '操作',
        dataIndex: 'option',
        width: 100,
        render: (_: any, record: any) => [
          <a
            style={{ fontSize: 14 }}
            onClick={async () => window.open(record.fileUrl || '')}
          >
            下载
          </a>,
        ],
      } as ProColumns,
    ],
  },
  wholeHospOperatingReport: {
    key: 'wholeHospOperatingReport',
    buildColumns: () => wholeHospOperatingReport,
    filterConf: [],
    scrollX: 1000,
    showCalcButton: false,
    enhanceColumns: (cols) => [
      ...cols,
      {
        title: '操作',
        dataIndex: 'option',
        width: 100,
        render: (_: any, record: any) => [
          <a
            style={{ fontSize: 14 }}
            onClick={async () => window.open(record.fileUrl || '')}
          >
            下载
          </a>,
        ],
      } as ProColumns,
    ],
  },
  projectShareParamsCalc: {
    key: 'projectShareParamsCalc',
    buildColumns: () => projectShareParamsCalc,
    filterConf: projectShareParamsCalcFilterConf,
    scrollX: 1600,
    showCalcButton: true,
  },
  standardItemCostCalc: {
    key: 'standardItemCostCalc',
    buildColumns: () => [],
    filterConf: standardItemCostCalcFilterConf,
    scrollX: 1500,
    showCalcButton: true,
  },
  patientStandItemCostCalc: {
    key: 'patientStandItemCostCalc',
    buildColumns: () => [],
    filterConf: patientStandItemCostCalcFilterConf,
    scrollX: 1500,
    showCalcButton: true,
  },
  standItemShareCostCalc: {
    key: 'standItemShareCostCalc',
    buildColumns: () => [],
    filterConf: standItemShareCostCalcFilterConf,
    scrollX: 1500,
    showCalcButton: true,
  },
  patientItemCalc: {
    key: 'patientItemCalc',
    buildColumns: () => [],
    filterConf: PatientItemCalcFilterConf,
    scrollX: 1500,
    showCalcButton: true,
  },
  projectCostCalc: {
    key: 'projectCostCalc',
    buildColumns: () => [],
    filterConf: projectCostCalcFilterConf,
    scrollX: 1200,
    showCalcButton: false,
    resolveButtons: (ctx: any) => {
      try {
        const hasCalculate = ctx?.pagePermissions?.has?.('calculate');
        const hasExport = ctx?.pagePermissions?.has?.('export');
        return { calculate: !!hasCalculate, export: !!hasExport };
      } catch {
        return { calculate: false, export: false };
      }
    },
  },
  // 医院科室直接成本表（医疗成本）
  deptDirectMedicalCost: {
    key: 'deptDirectMedicalCost',
    buildColumns: () => deptDirectMedicalCost,
    filterConf: deptDirectMedicalCostFilterConf,
    scrollX: 1450,
    showCalcButton: false,
    tablePropsBuilder: () => ({ pagination: false, scroll: { y: 662 } }),
  },
  // 医院科室直接成本表（全成本）
  deptFullDirectCost: {
    key: 'deptFullDirectCost',
    buildColumns: () => deptFullDirectCost,
    filterConf: deptFullDirectCostFilterConf,
    scrollX: 1800,
    showCalcButton: false,
    tablePropsBuilder: () => ({ pagination: false, scroll: { y: 645 } }),
  },
  // 临床服务类科室全成本（医疗成本）
  clinicalDeptMedicalCost: {
    key: 'clinicalDeptMedicalCost',
    buildColumns: () => clinicalDeptMedicalCost,
    filterConf: clinicalDeptMedicalCostFilterConf,
    scrollX: 3000,
    showCalcButton: false,
    tablePropsBuilder: () => ({ pagination: false, scroll: { y: 645 } }),
  },
  // 临床服务类科室全成本（全成本）
  clinicalDeptFullCost: {
    key: 'clinicalDeptFullCost',
    buildColumns: () => clinicalDeptFullCost,
    filterConf: clinicalDeptFullCostFilterConf,
    scrollX: 3000,
    showCalcButton: false,
    tablePropsBuilder: () => ({ pagination: false, scroll: { y: 629 } }),
  },
  // 医院科室成本分摊汇总表（静态列定义，服务端仅返回数据）
  deptCostAllocationSummary: {
    key: 'deptCostAllocationSummary',
    buildColumns: () => (require('./columns') as any).deptCostAllocationSummary,
    filterConf: [
      {
        type: 'input',
        label: '科室名称：',
        placeholder: '请输入',
        key: 'departmentName',
      },
    ],
    scrollX: 1600,
    showCalcButton: false,
    tablePropsBuilder: () => ({ pagination: false, scroll: { y: 610 } }),
  },
  // 临床服务类科室全成本构成分析表（动态表头+数据）
  clinicalDeptFullCostAnalysis: {
    key: 'clinicalDeptFullCostAnalysis',
    // 列由接口 title 动态生成，这里返回空数组占位
    buildColumns: () => [],
    // 仅时间筛选，无额外条件
    filterConf: [],
    scrollX: 800,
    showCalcButton: false,
    tablePropsBuilder: () => ({ pagination: false, scroll: { y: 645 } }),
  },
  // 医院诊次成本构成表
  hospitalVisitCostComposition: {
    key: 'hospitalVisitCostComposition',
    buildColumns: () =>
      (require('./columns') as any).hospitalVisitCostComposition,
    filterConf: [],
    scrollX: 1200,
    showCalcButton: false,
    tablePropsBuilder: () => ({ pagination: false, scroll: { y: 645 } }),
  },
  // 医院科室诊次成本表
  hospitalDeptVisitCost: {
    key: 'hospitalDeptVisitCost',
    buildColumns: () => (require('./columns') as any).hospitalDeptVisitCost,
    filterConf: [
      {
        type: 'input',
        label: '科室名称：',
        placeholder: '请输入',
        key: 'departmentName',
      },
    ],
    scrollX: 1200,
    showCalcButton: false,
    tablePropsBuilder: () => ({ pagination: false, scroll: { y: 645 } }),
  },
  // 医院科室床日成本表
  hospitalDeptBedDayCost: {
    key: 'hospitalDeptBedDayCost',
    buildColumns: () => (require('./columns') as any).hospitalDeptBedDayCost,
    filterConf: [
      {
        type: 'input',
        label: '科室名称：',
        placeholder: '请输入',
        key: 'departmentName',
      },
    ],
    scrollX: 1200,
    showCalcButton: false,
    tablePropsBuilder: () => ({ pagination: false, scroll: { y: 645 } }),
  },
  // 医院床日成本构成表
  hospitalBedDayCostComposition: {
    key: 'hospitalBedDayCostComposition',
    buildColumns: () =>
      (require('./columns') as any).hospitalBedDayCostComposition,
    filterConf: [],
    scrollX: 1200,
    showCalcButton: false,
    tablePropsBuilder: () => ({ pagination: false, scroll: { y: 645 } }),
  },
  // 医院医疗服务项目成本汇总表
  hospitalServiceProjectCost: {
    key: 'hospitalServiceProjectCost',
    buildColumns: () =>
      (require('./columns') as any).hospitalServiceProjectCost,
    filterConf: hospitalServiceProjectCostFilterConf,
    scrollX: 1200,
    showCalcButton: false,
    tablePropsBuilder: () => ({ pagination: false, scroll: { y: 700 } }),
  },
  // 医院医疗服务项目成本明细表
  medicalServiceCostDetail: {
    key: 'medicalServiceCostDetail',
    buildColumns: () => (require('./columns') as any).medicalServiceCostDetail,
    filterConf: medicalServiceCostDetailFilterConf,
    scrollX: 1200,
    showCalcButton: false,
    tablePropsBuilder: () => ({ pagination: false, scroll: { y: 661 } }),
  },
  // 医院病种成本明细表（后端分页+检索）
  diseaseCostDetail: {
    key: 'diseaseCostDetail',
    buildColumns: () => (require('./columns') as any).diseaseCostDetail,
    filterConf: [
      {
        type: 'input',
        label: '病种名称：',
        placeholder: '请输入',
        key: 'diseaseFilter',
      },
    ],
    scrollX: 1200,
    showCalcButton: false,
    // 启用分页，关闭行虚拟化
    tablePropsBuilder: () => ({
      pagination: {
        showSizeChanger: true,
        defaultPageSize: 20,
        pageSizeOptions: ['10', '20', '50', '100'],
      },
      scroll: { y: 600 },
    }),
  },
  // 病种成本构成明细表（后端分页+检索）
  diseaseCostCompositionDetail: {
    key: 'diseaseCostCompositionDetail',
    buildColumns: () =>
      (require('./columns') as any).diseaseCostCompositionDetail,
    filterConf: [
      {
        type: 'input',
        label: '病种名称：',
        placeholder: '请输入',
        key: 'diseaseFilter',
      },
    ],
    scrollX: 2200,
    showCalcButton: false,
    // 启用分页，关闭行虚拟化
    tablePropsBuilder: () => ({
      pagination: {
        showSizeChanger: true,
        defaultPageSize: 20,
        pageSizeOptions: ['10', '20', '50', '100'],
      },
      scroll: { y: 600 },
    }),
  },
  // 医院DRG成本明细表
  drgCostDetail: {
    key: 'drgCostDetail',
    buildColumns: () => (require('./columns') as any).drgCostDetail,
    filterConf: [
      {
        type: 'input',
        label: 'DRG名称：',
        placeholder: '请输入',
        key: 'itemName',
      },
    ],
    scrollX: 1200,
    showCalcButton: false,
    tablePropsBuilder: () => ({ pagination: false, scroll: { y: 661 } }),
  },
  // 医院DRG成本构成明细表
  drgCostCompositionDetail: {
    key: 'drgCostCompositionDetail',
    buildColumns: () => (require('./columns') as any).drgCostCompositionDetail,
    filterConf: [
      {
        type: 'input',
        label: 'DRG名称：',
        placeholder: '请输入',
        key: 'itemName',
      },
    ],
    scrollX: 2200,
    showCalcButton: false,
    tablePropsBuilder: () => ({ pagination: false, scroll: { y: 661 } }),
  },
  // 医院服务单元DRG成本构成明细表（动态多级表头+数据）
  deptDrgCostCompositionDetail: {
    key: 'deptDrgCostCompositionDetail',
    buildColumns: () => [],
    filterConf: [
      {
        type: 'input',
        label: 'DRG名称：',
        placeholder: '请输入',
        key: 'itemName',
      },
    ],
    scrollX: 1200,
    showCalcButton: false,
    tablePropsBuilder: () => ({ pagination: false, scroll: { y: 661 } }),
  },
  // 服务单元病种成本构成明细表（动态表头+数据）
  deptDiseaseCostCompositionDetail: {
    key: 'deptDiseaseCostCompositionDetail',
    // 列由接口 title 动态生成，这里返回空数组占位
    buildColumns: () => [],
    filterConf: [
      {
        type: 'input',
        label: '病种名称：',
        placeholder: '请输入',
        key: 'diseaseFilter',
      },
    ],
    scrollX: 1200,
    showCalcButton: false,
    // 启用分页，关闭行虚拟化
    tablePropsBuilder: () => ({
      pagination: {
        showSizeChanger: true,
        defaultPageSize: 20,
        pageSizeOptions: ['10', '20', '50', '100'],
      },
      scroll: { y: 600 },
    }),
  },
};

export const getCalcPageStrategy = (calcPageKey?: string) => {
  if (!calcPageKey) return undefined;
  return STRATEGIES[calcPageKey];
};
