import { connect } from "umi";
import type { ConnectState } from "@/models/connect";
import type { ActionType } from "@ant-design/pro-table";
import ProTable from "@ant-design/pro-table";
import { useEffect, useImperativeHandle, useRef, useState } from "react";
import type { FormInstance } from "antd";
import { Col, Popconfirm, Row, Space, Typography } from "antd";
import { Button, Drawer, message, Modal, Spin, Tooltip, Image } from "antd";
import moment from 'moment'
import { handleGetGetBUSINESSAPPROVALDetail, handleGetProjectPeriodAccount, handleGetTableMonthlyReconciliation } from "../../ShopExpenseDetail/service";
import { handleNewPrint, handlePrintImg, wrapTreeNode } from "@/utils/format";
import numeral from 'numeral'
import ReactHTMLTableToExcel from "react-html-table-to-excel";
import MonthSettlement from "../../revenueConfirmation/components/monthSettlement";
import RevenueList from "@/pages/BussinessProject/components/RevenueList";
import { formatNumber, formatToTwoDecimalPlaces, getMoney, handleFormatNumber } from "@/services/options";
import './YearExamineDetailTable.less'
import ProForm, { ProFormDateRangePicker, ProFormDigit, ProFormList, ProFormUploadButton } from "@ant-design/pro-form";
import { handleGetPictureList, handleRebuildClosedPeriod, handleRebuildReductionPeriod } from "../service";
import { ExclamationCircleOutlined, MinusCircleOutlined, PlusOutlined } from "@ant-design/icons";
import { deletePicture, uploadPicture } from "@/services/picture";
import PrintContent from "./printContent";
import { handleHighPrecision } from "@/utils/utils";
import HistoricalProjects from "./HistoricalProjects";
import { getProjectDetail } from "@/pages/BussinessProject/service";

const { confirm } = Modal;
type DetailProps = {
    parentRow: any
    currentApprovalstate: any
    onRef: any
    setIsShowMonthBtn?: any// 是否显示月度结算按钮
    setIsYearAllowSettlement?: any // 是否可以进行年度结算
    handleShowSettlementDetail?: any // 点击小计显示的抽屉
    currentUser?: any
    isChangeFile?: any // 是否可以删除上传的附件
    isYear?: any // 判断是不是年度传参进来
}
const YearExamineDetailTable = ({ parentRow, currentApprovalstate, onRef, setIsShowMonthBtn, setIsYearAllowSettlement, handleShowSettlementDetail, currentUser, isChangeFile, isYear }: DetailProps) => {
    const actionRef = useRef<ActionType>();
    const tableRef = useRef<HTMLDivElement>(null);
    const formRef = useRef<FormInstance>();
    const uploadFormDescRef = useRef<any>();
    // 租金减免的表单
    const rentReductionFormRef = useRef<FormInstance>();

    const downloadBtnRef = useRef<any>()
    const downloadBtnRef1 = useRef<any>()
    const MonthSettlementRef = useRef<any>()
    let exportType: number = 0
    const [showExportTable, setShowExportTable] = useState<boolean>(false)
    // 表格加载效果
    const [tableLoading, setTableLoading] = useState<boolean>(false)
    // 表格数据
    const [reqDetailListDetail, setReqDetailListDetail] = useState<any>()
    // 导出的合计行数据
    const [exportSumRow, setExportSumRow] = useState<any>()
    // 表格的整个数据
    const [tableAllData, setTableAllData] = useState<any>()
    // 导出的合计对象
    const [exportData2Obj, setExportData2Obj] = useState<any>()
    // 导出的数据
    const [exportData2, setExportData2] = useState<any>()
    // 明细表的打印数据
    const [printDetailData, setPrintDetailData] = useState<any>()
    // 导出的数据
    const [exportData, setExportData] = useState<any>()
    // 格式化之后导出的数据
    const formatExportData = useRef<any>()
    // 行号的选择
    const [selectRowKey, setSelectRowKey] = useState<any>()
    const [selectDetailList, setSelectDetailList] = useState<any>()
    // 默认选中行
    const [defaultSelectRow, setDefaultSelectRow] = useState<any>()
    // 表格的隐藏字段
    const [columnsStateMap, setColumnsStateMap] = useState<any>({
        BreachPenalty: { show: false },
        // OtherFee: { show: false },
        PaidFee_9010: { show: false },
        PaidFee_9020: { show: false },
        PaidFee_9030: { show: false },
        PaidFee_9050: { show: false },
        PaidFee_9090: { show: false },
        PaidFee_9099: { show: false },
    })
    // 应缴费用明细表抽屉
    const [payableDrawer, setPayableDrawer] = useState<boolean>(false)
    const [otherData, setOtherData] = useState<any>();// 显示表格上方内容
    // 点击日期 显示的抽屉
    const [showDetail, setShowDetail] = useState<boolean>(false)
    // 点击的行详情数据
    const [currentDetailRow, setCurrentDetailRow] = useState<any>()
    // 签名数据
    const [signature, setSignatureObj] = useState<any>()
    // 进度流畅的详情信息
    const [progressDetail, setProgressDetail] = useState<any>()
    // 流程进度的当前状态
    const [progressState, setProgressState] = useState<number>(0)
    // 预览图片
    const [imagePreviewVisible, setImagePreviewVisible] = useState<boolean>(false)
    // 预览的索引
    const [previewIndex, setPreviewIndex] = useState<number>(0)

    // 上传附件的悬浮框
    const [showUpLoadFile, setShowUpLoadFile] = useState<boolean>(false)
    // 附件
    const [fileList, setFileList] = useState<any>()
    // 预览的附件
    const [showImgList, setShowImgList] = useState<any>()
    // 拿到当次请求的表格数据 如果有撤场结算的话 需要把这个list 给撤场结算的接口
    const [closeReqTableData, setCloseReqTableData] = useState<any>()
    // 存一个马上能拿到值的
    const closeReqTableDataRef = useRef<any>()
    // 撤场结算按钮点击之后返回的数据
    // const [afterCloseData, setAfterCloseData] = useState<any>()
    const afterCloseData = useRef<any>()
    // 撤场结算按钮是否显示的判断
    // const [isShowClosebtn, setIsShowClosebtn] = useState<boolean>(false)
    const isShowClosebtn = useRef<boolean>(false)
    // 判断是不是第一次进入到页面
    // const [isFirst, setIsFirst] = useState<boolean>(true)
    const isFirst = useRef<boolean>(true)
    // 判断是否显示撤场结算按钮 如果是撤场的询问框 点击了确定 就不显示 点击了取消就显示
    const [showCloseBtn, setShowCloseBtn] = useState<boolean>(false)
    // 判断是否在进行打印 
    const [isPrinting, setIsPrinting] = useState<boolean>(false)
    // 拿到导出结算明细表的数据
    const [exportDetailTableData, setExportDetailTableData] = useState<any>()
    // 打印结算明细表的数据 无合计
    const [printDetailTableData, setPrintDetailTableData] = useState<any>()
    // 显示租金减免的悬浮框
    const [showRentReduction, setShowRentReduction] = useState<boolean>(false)
    // 悬浮框的加载效果
    const [rentReductionLoading, setRentReductionLoading] = useState<boolean>(false)
    // 项目详情
    const [dataProjectDetail, setDataProjectDetail] = useState<any>()


    const columns: any = [
        {
            title: <div style={{ textAlign: 'center' }}>期限</div>,
            dataIndex: 'PeriodDesc',
            align: 'left',
            width: 250,
            fixed: 'left',
            hideInSearch: true,
            render: (_, record) => {
                return record?.PeriodDesc === '合计' ? <span style={{ color: '#9A3D1A', fontWeight: 600 }}>合计</span> :
                    record?.level === 1 ?
                        <span>{`${record?.PeriodDesc}`}</span> :
                        <>
                            <a onClick={() => {
                                console.log('record', record);
                                console.log('parentRow', parentRow);

                                setCurrentDetailRow(record)
                                setShowDetail(true)
                            }}>
                                {`${record?.StartDate}-${record?.EndDate}`}
                            </a>
                            {
                                record?.EarlySettlement ?
                                    <span style={{ color: 'red', marginLeft: '4px' }}>【提前结算】</span> : ''
                            }
                        </>

            }
        },
        {
            title: <div style={{ textAlign: 'center' }}>结算状态</div>,
            dataIndex: 'IsApplySuccess',
            align: 'right',
            width: 100,
            hideInSearch: true,
            render: (_, record) => {
                return record?.PeriodDesc === '合计' ? '' :
                    record?.level === 1 ?
                        currentApprovalstate === 0 ? <span style={{ color: '#1890ff' }}>{'待结算'}</span> :
                            currentApprovalstate === 1 ? <span style={{ color: '#1890ff' }}>{'审批中'}</span> :
                                currentApprovalstate === 9 ? <span style={{ color: '#faad14' }}>{'已结算'}</span> : '' :
                        record?.IsApplySuccess ?
                            <span style={{ color: '#faad14', cursor: 'pointer' }}>
                                {"已结算"}
                            </span>
                            :
                            record?.BusinessApprovalId ?
                                <span style={{ color: '#faad14', cursor: 'pointer' }}>
                                    结算中
                                </span> :
                                <span style={{ color: '#faad14', cursor: 'pointer' }}>
                                    待结算
                                </span>
            }
            // render: (_, record) => {
            //   return record?.PeriodDesc === '合计' ? '' : record?.level === 1 ?
            //     currentApprovalstate === 0 ? <span style={{ color: '#1890ff' }}>{'待结算'}</span> :
            //       currentApprovalstate === 1 ? <span style={{ color: '#1890ff' }}>{'审批中'}</span> :
            //         currentApprovalstate === 9 ? <span style={{ color: '#faad14' }}>{'已结算'}</span> : ''
            //     : record?.IsApplySuccess ?
            //       // 子级跳进去
            //       <span style={{ color: '#faad14', cursor: 'pointer' }} onClick={() => {
            //         console.log('currentRow', currentRow);
            //         console.log('record', record);
            //         setShowStateCurrentRow({
            //           ...currentRow,
            //           startTime: record?.StartDate ? moment(record?.StartDate).format('YYYY-MM-DD') : '',
            //           endTime: record?.EndDate ? moment(record?.EndDate).format('YYYY-MM-DD') : '',
            //           ShopRoyaltyId: record?.ShopRoyalty_Id,
            //           // BUSINESSPROJECT_ID: currentRow?.BUSINESSPROJECT_ID,
            //           Id: currentRow?.SERVERPARTSHOP_ID,
            //           SERVERPART_ID: currentRow?.SERVERPART_ID,
            //           BUSINESSAPPROVAL_ID: record?.BusinessApprovalId,
            //           STATISTICS_MONTH: record?.EndDate ? moment(record?.EndDate).format('YYYYMM') : '',
            //           Approvalstate: record?.IsApplySuccess ? 9 : record?.BusinessApprovalId ? 1 : 0
            //         })

            //         setShowStateDrawer(true)
            //       }}>{'已结算'}</span>
            //       :
            //       record?.BusinessApprovalId ?
            //         <span style={{ color: '#faad14', cursor: 'pointer' }} onClick={() => {
            //           console.log('结算中', record);

            //           setShowStateCurrentRow({
            //             ...currentRow,
            //             startTime: record?.StartDate ? moment(record?.StartDate).format('YYYY-MM-DD') : '',
            //             endTime: record?.EndDate ? moment(record?.EndDate).format('YYYY-MM-DD') : '',
            //             ShopRoyaltyId: record?.ShopRoyalty_Id,
            //             // BUSINESSPROJECT_ID: currentRow?.BUSINESSPROJECT_ID,
            //             Id: currentRow?.SERVERPARTSHOP_ID,
            //             SERVERPART_ID: currentRow?.SERVERPART_ID,
            //             BusinessApprovalId: record?.BusinessApprovalId,
            //             BUSINESSAPPROVAL_ID: record?.BusinessApprovalId,
            //             STATISTICS_MONTH: record?.EndDate ? moment(record?.EndDate).format('YYYYMM') : '',
            //             Approvalstate: 1,
            //             PEND_STATE: -1
            //           })
            //           setShowStateDrawer(true)
            //         }}>结算中</span> :
            //         <span style={{ color: '#faad14', cursor: 'pointer' }} onClick={() => {
            //           console.log('currentRow', currentRow);
            //           console.log('record', record);
            //           setShowStateCurrentRow({
            //             ...currentRow,
            //             startTime: record?.StartDate ? moment(record?.StartDate).format('YYYY-MM-DD') : '',
            //             endTime: record?.EndDate ? moment(record?.EndDate).format('YYYY-MM-DD') : '',
            //             ShopRoyaltyId: record?.ShopRoyalty_Id,
            //             // BUSINESSPROJECT_ID: currentRow?.BUSINESSPROJECT_ID,
            //             Id: currentRow?.SERVERPARTSHOP_ID,
            //             SERVERPART_ID: currentRow?.SERVERPART_ID,
            //             STATISTICS_MONTH: record?.EndDate ? moment(record?.EndDate).format('YYYYMM') : '',
            //             Approvalstate: 0
            //           })

            //           setShowStateDrawer(true)
            //         }}>{'待结算'}</span>
            // }
        },
        {
            title: '租金信息',
            dataIndex: '',
            hideInSearch: true,
            children: [
                {
                    title: <div style={{ textAlign: 'center' }}>保底/固定租金</div>,
                    dataIndex: 'MinturnOver',
                    valueType: 'digit',
                    align: 'right',
                    width: 130,
                    hideInSearch: true,
                    render: (_, record) => {
                        const str: string = record?.Remark
                        return record?.MinturnOver ?
                            <Tooltip title={str}>
                                {handleFormatNumber(record?.MinturnOver)}
                            </Tooltip>
                            : record?.MinturnOver === 0 ? '0.00' : '-'
                    }
                },
                {
                    title: <div style={{ textAlign: 'center' }}>提成比率</div>,
                    dataIndex: 'GuaranteeRatio',
                    hideInSearch: true,
                    align: 'right',
                    width: 100,
                    render: (_, record) => {
                        return record?.GuaranteeRatio ? `${record?.GuaranteeRatio}%` : ''
                    }
                }
            ]
        },
        {
            title: '营业额',
            dataIndex: '',
            hideInSearch: true,
            children: [
                {
                    title: <div style={{ textAlign: 'center' }}>现金</div>,
                    dataIndex: 'CashAmount',
                    valueType: 'digit',
                    align: 'right',
                    width: 80,
                    hideInSearch: true,
                    render: (_, record) => {
                        return record?.CashAmount ?
                            `${handleFormatNumber(record?.CashAmount)}${record?.CashCorrect ? `（${record?.CashCorrect > 0 ? '+' : record?.CashCorrect < 0 ? '' : ''}${record?.CashCorrect}）` : ''}`
                            : record?.CashAmount === 0 ? '0.00' : '-'
                    }
                },
                {
                    title: <div style={{ textAlign: 'center' }}>微支付</div>,
                    dataIndex: 'MobilePayAmount',
                    valueType: 'digit',
                    align: 'right',
                    width: 100,
                    hideInSearch: true,
                    render: (_, record) => {
                        return record?.MobilePayAmount ?
                            `${handleFormatNumber(record?.MobilePayAmount)}${record?.MobilePayCorrect ? `（${record?.MobilePayCorrect > 0 ? '+' : record?.MobilePayCorrect < 0 ? '' : ''}${record?.MobilePayCorrect}）` : ''}`
                            : record?.MobilePayAmount === 0 ? '0.00' : '-'
                    }
                },
                {
                    title: <div style={{ textAlign: 'center' }}>小计</div>,
                    dataIndex: 'RevenueAmount',
                    valueType: 'digit',
                    align: 'right',
                    width: 150,
                    hideInSearch: true,
                    // render: (_, record) => {
                    //     return <span style={{ color: '#1890ff' }}>{record?.RevenueAmount ? `${numeral(record?.RevenueAmount).format('0,0.00')}${record?.addRevenueMoney ? `（${record?.addRevenueMoney > 0 ? '+' : record?.addRevenueMoney < 0 ? '-' : ''}${record?.addRevenueMoney}）` : ''}` : '0'}</span>
                    // }
                    render: (_, record) => {
                        return record?.level === 1 ?
                            <a onClick={() => {
                                if (currentApprovalstate < 1) {
                                    return
                                }
                                handleShowSettlementDetail()
                            }}>
                                {record?.RevenueAmount ? `${handleFormatNumber(record?.RevenueAmount)}${record?.addRevenueMoney ? `（${record?.addRevenueMoney > 0 ? '+' : record?.addRevenueMoney < 0 ? '' : ''}${record?.addRevenueMoney}）` : ''}` : '0'}
                            </a> :
                            <span>{record?.RevenueAmount ? `${handleFormatNumber(record?.RevenueAmount)}` : ''}</span>
                    }
                    // render: (_, record) => {
                    //   return showSettlementDrawer ? <span style={{ color: '#1890ff' }}>{record?.RevenueAmount ? `${numeral(record?.RevenueAmount).format('0,0.00')}${record?.addRevenueMoney ? `（${record?.addRevenueMoney > 0 ? '+' : record?.addRevenueMoney < 0 ? '-' : ''}${record?.addRevenueMoney}）` : ''}` : '0'}</span> : record.level === 1 ? <a onClick={() => {
                    //     if (currentApprovalstate < 1) {
                    //       return
                    //     }

                    //     let before: number = 0 // 项目开始前
                    //     let first: number = 0 // 第一期
                    //     let firstObj: any = {} // 第一个不能点击
                    //     if (reqDetailListDetail && reqDetailListDetail.length > 0) {
                    //       reqDetailListDetail.forEach((item: any, index: number) => {
                    //         // 水电物业
                    //         const totalFee: number = item.WaterCharge + item.ElectricityCharge + item.PropertyFee + item.HouseRent + item.BreachPenalty + item.OtherFee
                    //         // 提成金额
                    //         const amount: number = item.RevenueAmount * (item.GuaranteeRatio / 100)
                    //         // 项目租金
                    //         const guaranteedRent: number = amount > item.MinturnOver ? amount : item.MinturnOver
                    //         if (item.PeriodIndexStr === '项目开始前' || item.PeriodIndexStr === "装修期") {
                    //           before = item.RoyaltyAmount - (totalFee + guaranteedRent)
                    //         } else {
                    //           first = item.RoyaltyAmount - (totalFee + guaranteedRent)
                    //         }
                    //         if (item.PeriodIndex <= 0 && item.PeriodDesc !== '合计') {
                    //           firstObj = item
                    //         }

                    //       })
                    //     }
                    //     if (moment(firstObj?.EndDate).format('YYYY-MM-DD') === moment(record?.EndDate).format('YYYY-MM-DD') && moment(firstObj?.StartDate).format('YYYY-MM-DD') === moment(record?.StartDate).format('YYYY-MM-DD')) {
                    //       setReadOnlyRowDetail(reqDetailListDetail[reqDetailListDetail.length - 1])
                    //     } else {
                    //       console.log('record', record);
                    //       setReadOnlyRowDetail(record)
                    //     }

                    //     setYearSettlementOnlyRead(true)
                    //     setMoneyFirstBefore([before, first])
                    //     // setDrawerTableData(JSON.parse(JSON.stringify(reqDetailListDetail)))
                    //     setSettlementYearTableData(JSON.parse(JSON.stringify(reqDetailListDetail)))
                    //     setShowSettlementDrawer(true)
                    //   }}>{record?.RevenueAmount ? `${numeral(record?.RevenueAmount).format('0,0.00')}${record?.CORRECT_AMOUNT ? `（${record?.CORRECT_AMOUNT > 0 ? '+' : record?.CORRECT_AMOUNT < 0 ? '' : ''}${record?.CORRECT_AMOUNT}）` : ''}` : '0'}</a> :
                    //     showToExamineModal ?
                    //       <span>{record?.RevenueAmount ? `${numeral(record?.RevenueAmount).format('0,0.00')}${record?.CORRECT_AMOUNT ? `（${record?.CORRECT_AMOUNT > 0 ? '+' : record?.CORRECT_AMOUNT < 0 ? '' : ''}${record?.CORRECT_AMOUNT}）` : ''}` : '0'}</span> :
                    //       <span>{record?.RevenueAmount ? numeral(record?.RevenueAmount).format('0,0.00') : '0'}</span>
                    // }
                }
            ]
        },
        {
            title: <div style={{ textAlign: 'center' }}>业主收款</div>,
            dataIndex: 'RoyaltyAmount',
            valueType: 'digit',
            width: 100,
            align: 'right',
            hideInSearch: true,
            render: (_, record) => {
                return record?.RoyaltyAmount ? handleFormatNumber(record?.RoyaltyAmount) : record?.RoyaltyAmount === 0 ? '0.00' : '-'
            }
        },
        {
            title: '应收费用',
            dataIndex: '',
            hideInSearch: true,
            children: [
                {
                    title: <div style={{ textAlign: 'center' }}>合计</div>,
                    dataIndex: 'ReceivableAmount',
                    valueType: 'digit',
                    align: 'right',
                    width: 100,
                    hideInSearch: true,
                    render: (_, record) => {
                        const str: string = `租金(${numeral(record?.GuaranteeFee).format('0.00')}) + 物业费(${numeral(record?.PropertyFee).format('0.00')}) + 房租(${numeral(record?.HouseRent).format('0.00')}) + 罚款(${numeral(record?.BreachPenalty).format('0.00')}) + 电费(${numeral(record?.ElectricityCharge).format('0.00')}) + 水费(${numeral(record?.WaterCharge).format('0.00')}) + 其他(${numeral(record?.OtherFee).format('0.00')})`
                        return record?.ReceivableAmount ?
                            <Tooltip title={str}>
                                <span>
                                    {handleFormatNumber(record?.ReceivableAmount)}
                                </span>
                            </Tooltip>
                            : ''
                    }
                },
                {
                    title: <div style={{ textAlign: 'center' }}>租金</div>,
                    dataIndex: 'GuaranteeFee',
                    valueType: 'digit',
                    align: 'right',
                    width: 120,
                    hideInSearch: true,
                    render: (_, record) => {
                        const str: string = `租金(${numeral(record?.MinturnOver).format('0.00')}) ${record?.MinturnOver > (record?.RevenueAmount * (record?.GuaranteeRatio) / 100) ? '>' : '<'} 营业额(${record?.RevenueAmount || 0}) * 提成比率(${record?.GuaranteeRatio ? `${record?.GuaranteeRatio}%` : ''})`
                        return record?.GuaranteeFee ?
                            <Tooltip title={record?.PeriodDesc === '合计' ? '' : str}>
                                <span>{handleFormatNumber(record?.GuaranteeFee)}</span>
                            </Tooltip>
                            : ''
                    }
                },
                {
                    title: <div style={{ textAlign: 'center' }}>物业费</div>,
                    dataIndex: 'PropertyFee',
                    valueType: 'digit',
                    align: 'right',
                    width: 100,
                    hideInSearch: true,
                    render: (_, record) => {
                        return record?.PropertyFee ?
                            handleFormatNumber(record?.PropertyFee)
                            : record?.PropertyFee === 0 ? <span style={{ color: 'red' }}>0.00</span> : ''
                    }
                },
                {
                    title: <div style={{ textAlign: 'center' }}>住宿费</div>,
                    dataIndex: 'HouseRent',
                    valueType: 'digit',
                    align: 'right',
                    width: 80,
                    hideInSearch: true,
                    render: (_, record) => {
                        return record?.HouseRent ? handleFormatNumber(record?.HouseRent) : record?.HouseRent === 0 ? '0.00' : '-'
                    }
                },
                {
                    title: <div style={{ textAlign: 'center' }}>罚款</div>,
                    dataIndex: 'BreachPenalty',
                    valueType: 'digit',
                    align: 'right',
                    width: 80,
                    hideInSearch: true,
                    render: (_, record) => {
                        return record?.BreachPenalty ? handleFormatNumber(record?.BreachPenalty) : record?.BreachPenalty === 0 ? '0.00' : '-'
                    }
                },
                {
                    title: <div style={{ textAlign: 'center' }}>电费</div>,
                    dataIndex: 'ElectricityCharge',
                    valueType: 'digit',
                    align: 'right',
                    width: 80,
                    hideInSearch: true,
                    render: (_, record) => {
                        return record?.ElectricityCharge ?
                            handleFormatNumber(record?.ElectricityCharge)
                            : record?.ElectricityCharge === 0 ? <span style={{ color: 'red' }}>0.00</span> : ''
                    }
                },
                {
                    title: <div style={{ textAlign: 'center' }}>水费</div>,
                    dataIndex: 'WaterCharge',
                    valueType: 'digit',
                    align: 'right',
                    width: 80,
                    hideInSearch: true,
                    render: (_, record) => {
                        return record?.WaterCharge ?
                            handleFormatNumber(record?.WaterCharge)
                            : record?.WaterCharge === 0 ? <span style={{ color: 'red' }}>0.00</span> : ''
                    }
                },
                {
                    title: <div style={{ textAlign: 'center' }}>其他</div>,
                    dataIndex: 'OtherFee',
                    valueType: 'digit',
                    align: 'right',
                    width: 80,
                    hideInSearch: true,
                    render: (_, record) => {
                        return record?.OtherFee ? handleFormatNumber(record?.OtherFee) : record?.OtherFee === 0 ? '0.00' : '-'
                    }
                }
            ]
        },
        {
            title: '已缴费用',
            dataIndex: '',
            align: 'center',
            hideInSearch: true,
            children: [
                {
                    title: <div style={{ textAlign: 'center' }}>合计</div>,
                    dataIndex: 'PaidFee',
                    valueType: 'digit',
                    align: 'right',
                    width: 100,
                    hideInSearch: true,
                    render: (_, record) => {
                        const str: string = `水费(${numeral(record?.PaidFee_9010).format('0.00')}) + 电费(${numeral(record?.PaidFee_9020).format('0.00')}) + 房租(${numeral(record?.PaidFee_9030).format('0.00')})
                + 物业费(${numeral(record?.PaidFee_9050).format('0.00')})+ 租金(${numeral(record?.PaidFee_9090).format('0.00')})+ 其他(${numeral(record?.PaidFee_9099).format('0.00')})`
                        return record?.PaidFee
                            ?
                            <Tooltip title={str}>
                                <span>{handleFormatNumber(record?.PaidFee)}</span>
                            </Tooltip>
                            : '0.00'
                    }
                },
                {
                    title: <div style={{ textAlign: 'center' }}>水费</div>,
                    dataIndex: 'PaidFee_9010',
                    valueType: 'digit',
                    align: 'right',
                    width: 80,
                    hideInSearch: true,
                    render: (_, record) => {
                        return record?.PaidFee_9010 ?
                            handleFormatNumber(record?.PaidFee_9010)
                            : record?.PaidFee_9010 === 0 ? <span style={{ color: 'red' }}>0.00</span> : ''
                    }
                },
                {
                    title: <div style={{ textAlign: 'center' }}>电费</div>,
                    dataIndex: 'PaidFee_9020',
                    valueType: 'digit',
                    align: 'right',
                    width: 80,
                    hideInSearch: true,
                    render: (_, record) => {
                        return record?.PaidFee_9020 ?
                            handleFormatNumber(record?.PaidFee_9020)
                            : record?.PaidFee_9020 === 0 ? <span style={{ color: 'red' }}>0.00</span> : ''
                    }
                },
                {
                    title: <div style={{ textAlign: 'center' }}>住宿费</div>,
                    dataIndex: 'PaidFee_9030',
                    valueType: 'digit',
                    align: 'right',
                    width: 80,
                    hideInSearch: true,
                    render: (_, record) => {
                        return record?.PaidFee_9030 ?
                            handleFormatNumber(record?.PaidFee_9030)
                            : record?.PaidFee_9030 === 0 ? <span style={{ color: 'red' }}>0.00</span> : ''
                    }
                },
                {
                    title: <div style={{ textAlign: 'center' }}>物业费</div>,
                    dataIndex: 'PaidFee_9050',
                    valueType: 'digit',
                    align: 'right',
                    width: 100,
                    hideInSearch: true,
                    render: (_, record) => {
                        return record?.PaidFee_9050 ?
                            handleFormatNumber(record?.PaidFee_9050)
                            : record?.PaidFee_9050 === 0 ? <span style={{ color: 'red' }}>0.00</span> : ''
                    }
                },
                {
                    title: <div style={{ textAlign: 'center' }}>租金</div>,
                    dataIndex: 'PaidFee_9090',
                    valueType: 'digit',
                    align: 'right',
                    width: 100,
                    hideInSearch: true,
                    render: (_, record) => {
                        return record?.PaidFee_9090 ?
                            handleFormatNumber(record?.PaidFee_9090)
                            : record?.PaidFee_9090 === 0 ? <span style={{ color: 'red' }}>0.00</span> : ''
                    }
                },
                {
                    title: <div style={{ textAlign: 'center' }}>其他</div>,
                    dataIndex: 'PaidFee_9099',
                    valueType: 'digit',
                    align: 'right',
                    width: 100,
                    hideInSearch: true,
                    render: (_, record) => {
                        return record?.PaidFee_9099 ?
                            handleFormatNumber(record?.PaidFee_9099)
                            : record?.PaidFee_9099 === 0 ? <span style={{ color: 'red' }}>0.00</span> : ''
                    }
                }
            ]
        },
        {
            title: <div style={{ textAlign: 'center' }}>核减租金</div>,
            dataIndex: 'ReductionAmount',
            valueType: 'digit',
            align: 'right',
            // fixed: 'right',
            width: 120,
            hideInSearch: true,
        },
        {
            title: <div style={{ textAlign: 'center' }}>退补款</div>,
            dataIndex: 'RefundSupplement',
            valueType: 'digit',
            align: 'right',
            fixed: 'right',
            width: 100,
            hideInSearch: true,
            render: (_, record) => {
                const str: string = `业主收款(${record?.RoyaltyAmount || 0}) - 应收费用(${record?.ReceivableAmount || 0}) + 已缴费用(${record?.PaidFee || 0})`
                return record?.RefundSupplement ?
                    <Tooltip title={str}>
                        <span style={{ color: '#9A3D1A', fontWeight: 600 }}>{handleFormatNumber(record?.RefundSupplement)}</span>
                    </Tooltip>
                    : ''
            }
        },
    ]
    // 导出excel的columns
    const exportColumns: any = [
        {
            title: <div style={{ textAlign: 'center' }}>期限</div>,
            dataIndex: 'PeriodDescBig',
            children: [
                {
                    dataIndex: 'PeriodIndexStr',
                    title: <div style={{ textAlign: 'center' }}>期数</div>,
                    align: 'center',
                    hideInSearch: true
                },
                {
                    title: <div style={{ textAlign: 'center' }}>期限</div>,
                    dataIndex: 'PeriodDesc',
                    align: 'left',
                    hideInSearch: true,
                    render: (_, record) => {
                        return record?.PeriodDesc !== '合计' && record?.PeriodDesc === '精算数据' ?
                            <span>{`${record?.StartDate}-${record?.EndDate}`}</span> :
                            <span>{`${record?.PeriodDesc}`}</span>
                    }
                }
            ]
        },
        {
            title: <div style={{ textAlign: 'center' }}>租金信息</div>,
            dataIndex: 'PeriodDescBig',
            hideInSearch: true,
            children: [
                {
                    title: <div style={{ textAlign: 'center' }}>保底/固定租金</div>,
                    dataIndex: 'MinturnOver',
                    valueType: 'digit',
                    align: 'right',
                    hideInSearch: true,
                    render: (_, record) => {
                        return <span>{record?.MinturnOver ? handleFormatNumber(record?.MinturnOver) : '0.00'}</span>
                    }
                },
                {
                    title: <div style={{ textAlign: 'center' }}>提成比率</div>,
                    dataIndex: 'GuaranteeRatio',
                    hideInSearch: true,
                    align: 'right',
                    render: (_, record) => {
                        return record?.GuaranteeRatio ? `${record?.GuaranteeRatio}%` : ''
                    }
                }
            ]
        },
        {
            title: <div style={{ textAlign: 'center' }}>营业额</div>,
            dataIndex: 'turnover',
            hideInSearch: true,
            children: [
                {
                    title: <div style={{ textAlign: 'center' }}>现金</div>,
                    dataIndex: 'CashAmount',
                    valueType: 'digit',
                    align: 'right',
                    hideInSearch: true,
                    render: (_, record) => {
                        return <span>{record?.CashAmount ? handleFormatNumber(record?.CashAmount) : '0.00'}</span>
                    }
                },
                {
                    title: <div style={{ textAlign: 'center' }}>微支付</div>,
                    dataIndex: 'MobilePayAmount',
                    valueType: 'digit',
                    align: 'right',
                    hideInSearch: true,
                    render: (_, record) => {
                        return <span>{record?.MobilePayAmount ? handleFormatNumber(record?.MobilePayAmount) : '0.00'}</span>
                    }
                },
                {
                    title: <div style={{ textAlign: 'center' }}>小计</div>,
                    dataIndex: 'RevenueAmount',
                    valueType: 'digit',
                    align: 'right',
                    hideInSearch: true,
                    render: (_, record) => {
                        return <span>{record?.RevenueAmount ? handleFormatNumber(record?.RevenueAmount) : '0.00'}</span>
                    }
                },
                {
                    title: <div style={{ textAlign: 'center' }}>提成金额</div>,
                    dataIndex: 'amount',
                    valueType: 'digit',
                    align: 'right',
                    hideInSearch: true,
                    render: (_, record) => {
                        return <span>{record?.amount ? handleFormatNumber(record?.amount) : '0.00'}</span>
                    }
                    // render: (_, record) => {
                    //   return record.RevenueAmount * (record.GuaranteeRatio / 100)
                    // }
                },
            ]
        },
        {
            title: <div style={{ textAlign: 'center' }}>业主收款</div>,
            dataIndex: 'RoyaltyAmount',
            valueType: 'digit',
            align: 'right',
            hideInSearch: true,
            render: (_, record) => {
                return <span>{record?.RoyaltyAmount ? handleFormatNumber(record?.RoyaltyAmount) : '0.00'}</span>
            }
        },
        {
            title: <div style={{ textAlign: 'center' }}>应收租金</div>,
            dataIndex: 'GuaranteeFee',
            valueType: 'digit',
            align: 'right',
            hideInSearch: true,
            render: (_, record) => {
                return <span>{record?.GuaranteeFee ? handleFormatNumber(record?.GuaranteeFee) : '0.00'}</span>
            }
        },
        {
            title: <div style={{ textAlign: 'center' }}>应收费用</div>,
            dataIndex: 'accountsReceivable',
            valueType: 'digit',
            hideInTable: exportType === 2,
            align: 'right',
            hideInSearch: true,
            // render: (_, record) => {
            //     return <span>{record?.ReceivableAmount ? handleFormatNumber(record?.ReceivableAmount) : '0.00'}</span>
            // }
            render: (_, record) => {
                return <span>{record?.TotalFee ? handleFormatNumber(record?.TotalFee) : '0.00'}</span>
            }
            // render: (_, record) => {
            //   return record?.ReceivableAmount - record?.GuaranteeFee
            // }
        },
        // {
        //     title: <div style={{ textAlign: 'center' }}>应收费用</div>,
        //     dataIndex: 'accountsReceivable',
        //     valueType: 'digit',
        //     align: 'right',
        //     hideInTable: exportType === 1,
        //     hideInSearch: true,
        //     // render: (_, record) => {
        //     //     return <span>{record?.ReceivableAmount ? handleFormatNumber(record?.ReceivableAmount) : '0.00'}</span>
        //     // }
        //     render: (_, record) => {
        //         return <span>{record?.TotalFee ? handleFormatNumber(record?.TotalFee) : '0.00'}</span>
        //     }
        //     // render: (_, record) => {
        //     //   return record?.ReceivableAmount - record?.GuaranteeFee
        //     // }
        // },
        {
            title: <div style={{ textAlign: 'center' }}>已缴费用</div>,
            dataIndex: 'paidFees',
            valueType: 'digit',
            align: 'right',
            hideInSearch: true,
            render: (_, record) => {
                return record?.PaidFee ? handleFormatNumber(record?.PaidFee) : '0.00'
            },
            // children: [
            //     {
            //         title: <div style={{ textAlign: 'center' }}>合计</div>,
            //         dataIndex: 'PaidFee',
            //         valueType: 'digit',
            //         align: 'right',
            //         hideInSearch: true,
            //         render: (_, record) => {
            //             return record?.PaidFee ? numeral(getMoney(record?.PaidFee)).format('0,0.00') : '0'
            //         }
            //     },
            //     {
            //         title: <div style={{ textAlign: 'center' }}>水费</div>,
            //         dataIndex: 'PaidFee_9010',
            //         valueType: 'digit',
            //         align: 'right',
            //         hideInSearch: true,
            //         render: (_, record) => {
            //             return record?.PaidFee_9010 ?
            //                 numeral(getMoney(record?.PaidFee_9010)).format('0,0.00')
            //                 : record?.PaidFee_9010 === 0 ? <span style={{ color: 'red' }}>0</span> : ''
            //         }
            //     },
            //     {
            //         title: <div style={{ textAlign: 'center' }}>电费</div>,
            //         dataIndex: 'PaidFee_9020',
            //         valueType: 'digit',
            //         align: 'right',
            //         hideInSearch: true,
            //         render: (_, record) => {
            //             return record?.PaidFee_9020 ?
            //                 numeral(getMoney(record?.PaidFee_9020)).format('0,0.00')
            //                 : record?.PaidFee_9020 === 0 ? <span style={{ color: 'red' }}>0</span> : ''
            //         }
            //     },
            //     {
            //         title: <div style={{ textAlign: 'center' }}>住宿费</div>,
            //         dataIndex: 'PaidFee_9030',
            //         valueType: 'digit',
            //         align: 'right',
            //         hideInSearch: true,
            //     },
            //     {
            //         title: <div style={{ textAlign: 'center' }}>物业费</div>,
            //         dataIndex: 'PaidFee_9050',
            //         valueType: 'digit',
            //         align: 'right',
            //         hideInSearch: true,
            //         render: (_, record) => {
            //             return record?.PaidFee_9050 ?
            //                 numeral(getMoney(record?.PaidFee_9050)).format('0,0.00')
            //                 : record?.PaidFee_9050 === 0 ? <span style={{ color: 'red' }}>0</span> : ''
            //         }
            //     },
            //     {
            //         title: <div style={{ textAlign: 'center' }}>租金</div>,
            //         dataIndex: 'PaidFee_9090',
            //         valueType: 'digit',
            //         align: 'right',
            //         hideInSearch: true,
            //         hideInTable: isPrinting,
            //         render: (_, record) => {
            //             return record?.PaidFee_9090 ?
            //                 numeral(getMoney(record?.PaidFee_9090)).format('0,0.00')
            //                 : record?.PaidFee_9090 === 0 ? <span style={{ color: 'red' }}>0</span> : ''
            //         }
            //     },
            //     {
            //         title: <div style={{ textAlign: 'center' }}>其他</div>,
            //         dataIndex: 'PaidFee_9099',
            //         valueType: 'digit',
            //         align: 'right',
            //         hideInSearch: true,
            //         hideInTable: isPrinting,
            //         render: (_, record) => {
            //             return record?.PaidFee_9099 ?
            //                 numeral(getMoney(record?.PaidFee_9099)).format('0,0.00')
            //                 : record?.PaidFee_9099 === 0 ? <span style={{ color: 'red' }}>0</span> : ''
            //         }
            //     }
            // ]
        },
        {
            title: <div style={{ textAlign: 'center' }}>核减租金</div>,
            dataIndex: 'ReductionAmount',
            valueType: 'digit',
            align: 'right',
            // fixed: 'right',
            width: 120,
            hideInSearch: true,
        },
        {
            title: <div style={{ textAlign: 'center' }}>退补款</div>,
            dataIndex: 'RefundSupplement',
            valueType: 'digit',
            align: 'right',
            hideInSearch: true,
            render: (_, record) => {
                return <span>{record?.RefundSupplement ? handleFormatNumber(record?.RefundSupplement) : '0.00'}</span>
            }
        },
        {
            title: <div style={{ textAlign: 'center' }}>备注</div>,
            width: 100,
            dataIndex: 'desc',
            align: 'left',
            hideInSearch: true,
        }
    ]
    // 流程进度的数组
    const [progressList, setProgressList] = useState<any>([
        { title: '商户确认', desc: '' },
        { title: '经理审核', desc: '' },
        { title: '中心审核', desc: '' },
        { title: '经发审核', desc: '' },
        { title: '财务审核', desc: '' },
        { title: '已审结', desc: '' },
    ])
    const handleGetTableData = async (id?: any, SHOPROYALTY_ID?: any, obj?: any, newObj?: any) => {
        setReqDetailListDetail([])
        if (setIsShowMonthBtn) {
            setIsShowMonthBtn(false)
        }
        if (!id) {
            return
        }
        setTableLoading(true)
        let nowState: number = 0
        if (parentRow?.BUSINESSAPPROVAL_ID) {
            nowState = await handleGetProcessProgress(parentRow?.BUSINESSAPPROVAL_ID)
        }
        let data: any = {}
        const req = {
            BUSINESSPROJECT_ID: id,
            SHOPROYALTY_ID
        }
        if (newObj) {
            data = newObj
        } else {
            console.log('obj321312', obj);
            // 结算中调用新的接口
            if (obj?.BUSINESSAPPROVAL_ID && nowState !== 1000) {
                const newReq: any = {
                    BUSINESSPROJECT_ID: id,
                    SHOPROYALTY_ID,
                    BUSINESSAPPROVAL_ID: obj?.BUSINESSAPPROVAL_ID
                }
                const newData = await handleGetProjectPeriodAccount(newReq)
                const newObj: any = {
                    OtherData: newData.ProjectModel,
                    List: [
                        {
                            ...newData.ProjectModel,
                            ProjectPeriodList: newData.ProjectPeriodList
                        }
                    ]
                }
                console.log('newObj', newObj);
                data = newObj
            } else {
                data = await handleGetTableMonthlyReconciliation(req)
            }

        }
        setCloseReqTableData(data)
        closeReqTableDataRef.current = data

        console.log('1', data);
        setOtherData({
            ...data.OtherData,
            Dates: `${moment(data?.OtherData?.PROJECT_STARTDATE).format('YYYY/MM/DD')}-${moment(data?.OtherData?.PROJECT_ENDDATE).format('YYYY/MM/DD')}`
        })

        let res: any = {}
        let list: any = []
        let otherMessage: any = {}
        let isYearList: any = {}

        if (data.List && data.List.length > 0) {
            res = data.List[0]
            setTableAllData(res)
            if (data.List[0].ProjectPeriodList) {
                otherMessage = data.List[0].ProjectPeriodList.node
                const resObj: any = data.List[0].ProjectPeriodList
                if (obj?.BUSINESSAPPROVAL_ID && nowState !== 1000) {
                    list = wrapTreeNode(data.List[0].ProjectPeriodList)
                    isYearList = wrapTreeNode(data.List[0].ProjectPeriodList)
                } else {
                    isYearList = wrapTreeNode([data.List[0].ProjectPeriodList])[0]
                    if (resObj.children && resObj.children.length > 0) {
                        list = wrapTreeNode(resObj.children)
                    }
                }
            }
        }

        console.log('2', list);
        if (list && list.length > 0) {
            list.forEach((item: any) => {
                item.level = 1
                if (item.children && item.children.length > 0) {
                    item.children.forEach((subItem: any) => {
                        subItem.level = 2
                    })
                }
            })
        }
        console.log('33333', isYearList);
        let isContinue: boolean = true
        if (isYearList.AllowApply === false) {
            isContinue = false
        }
        let isShowClose: boolean = false
        if (isYearList.IsApplySuccess) {
            isShowClose = true
        }
        isShowClosebtn.current = isShowClose
        // setIsShowClosebtn(isShowClose)
        if (setIsYearAllowSettlement) {
            setIsYearAllowSettlement(isContinue)
        }
        console.log('4', obj);
        // 判断是否已经审核了
        let isOverList: any = []
        // 判断是不是重新申请 重新申请应该走的是else  2024-08-30
        if (obj?.SETTLEMENT_STATE >= 1 && !obj?.APPLY_PROCCESS) {
            const detailReq = {
                BUSINESSPROJECT_ID: id,
                SHOPROYALTY_ID,
                BUSINESSAPPROVAL_ID: obj?.BUSINESSAPPROVAL_ID
            }
            const detailData = await handleGetProjectPeriodAccount(detailReq)
            console.log('detailData', detailData);
            if (detailData.ProjectPeriodList && detailData.ProjectPeriodList.length > 0) {
                const res: any = wrapTreeNode(detailData.ProjectPeriodList)
                isOverList = JSON.parse(JSON.stringify(wrapTreeNode(detailData.ProjectPeriodList)))
                console.log('exportData2', res);
                setExportData2(JSON.parse(JSON.stringify(isOverList)))
                if (res && res.length > 0) {
                    let CashAmountSum: number = 0
                    let MobilePayAmountSum: number = 0
                    let RevenueAmountSum: number = 0
                    let RoyaltyAmountSum: number = 0
                    let ReceivableAmountSum: number = 0
                    let GuaranteeFeeSum: number = 0
                    let PropertyFeeSum: number = 0
                    let HouseRentSum: number = 0
                    let BreachPenaltySum: number = 0
                    let ElectricityChargeSum: number = 0
                    let WaterChargeSum: number = 0
                    let OtherFeeSum: number = 0
                    let PaidFeeSum: number = 0
                    let PaidFee_9010Sum: number = 0
                    let PaidFee_9020Sum: number = 0
                    let PaidFee_9030Sum: number = 0
                    let PaidFee_9050Sum: number = 0
                    let PaidFee_9090Sum: number = 0
                    let PaidFee_9099Sum: number = 0
                    let RefundSupplementSum: number = 0
                    let GuaranteeRatioStr: string = ''
                    let MinturnOverSum: number = 0

                    let addRevenueMoneyStr: any

                    res.forEach((item: any) => {
                        item.level = 1
                        item.CORRECT_AMOUNT = item.CorrectAmount
                        item.addRevenueMoney = item.CorrectAmount
                        if (item.CorrectAmount) {
                            addRevenueMoneyStr = item.CorrectAmount
                        }
                        if (item.children && item.children.length > 0) {
                            item.children.forEach((subItem: any) => {
                                subItem.level = 2
                            })
                        }
                        if (res.length > 1) {
                            CashAmountSum += item.CashAmount * 100
                            MobilePayAmountSum += item.MobilePayAmount * 100
                            RevenueAmountSum += item.RevenueAmount * 100
                            RoyaltyAmountSum += item.RoyaltyAmount * 100
                            ReceivableAmountSum += item.ReceivableAmount * 100
                            GuaranteeFeeSum += item.GuaranteeFee * 100
                            PropertyFeeSum += item.PropertyFee * 100
                            HouseRentSum += item.HouseRent * 100
                            BreachPenaltySum += item.BreachPenalty * 100
                            ElectricityChargeSum += item.ElectricityCharge * 100
                            WaterChargeSum += item.WaterCharge * 100
                            OtherFeeSum += item.OtherFee * 100
                            PaidFeeSum += item.PaidFee * 100
                            PaidFee_9010Sum += item.PaidFee_9010 * 100
                            PaidFee_9020Sum += item.PaidFee_9020 * 100
                            PaidFee_9030Sum += item.PaidFee_9030 * 100
                            PaidFee_9050Sum += item.PaidFee_9050 * 100
                            PaidFee_9090Sum += item.PaidFee_9090 * 100
                            PaidFee_9099Sum += item.PaidFee_9099 * 100
                            RefundSupplementSum += item.RefundSupplement * 100
                            GuaranteeRatioStr = item.GuaranteeRatio
                            MinturnOverSum += item.MinturnOver * 100
                        }
                    })
                    // 拿到没有合计行的导出数据

                    if (res.length > 1) {
                        const obj: any = {
                            PeriodDesc: '合计',
                            level: 0,
                            CashAmount: handleHighPrecision(CashAmountSum),
                            MobilePayAmount: handleHighPrecision(MobilePayAmountSum),
                            RevenueAmount: handleHighPrecision(RevenueAmountSum),
                            RoyaltyAmount: handleHighPrecision(RoyaltyAmountSum),
                            ReceivableAmount: handleHighPrecision(ReceivableAmountSum),
                            GuaranteeFee: handleHighPrecision(GuaranteeFeeSum),
                            PropertyFee: handleHighPrecision(PropertyFeeSum),
                            HouseRent: handleHighPrecision(HouseRentSum),
                            BreachPenalty: handleHighPrecision(BreachPenaltySum),
                            ElectricityCharge: handleHighPrecision(ElectricityChargeSum),
                            WaterCharge: handleHighPrecision(WaterChargeSum),
                            OtherFee: handleHighPrecision(OtherFeeSum),
                            PaidFee: handleHighPrecision(PaidFeeSum),
                            PaidFee_9010: handleHighPrecision(PaidFee_9010Sum),
                            PaidFee_9020: handleHighPrecision(PaidFee_9020Sum),
                            PaidFee_9030: handleHighPrecision(PaidFee_9030Sum),
                            PaidFee_9050: handleHighPrecision(PaidFee_9050Sum),
                            PaidFee_9090: handleHighPrecision(PaidFee_9090Sum),
                            PaidFee_9099: handleHighPrecision(PaidFee_9099Sum),
                            RefundSupplement: handleHighPrecision(RefundSupplementSum),
                            GuaranteeRatio: GuaranteeRatioStr,
                            MinturnOver: handleHighPrecision(MinturnOverSum)
                        }
                        res.unshift(obj)
                        setExportData2Obj(obj)
                    }
                }
                console.log('resfdfsdafasd', res);

                setReqDetailListDetail(res)
                setTableLoading(false)
                if ((list && list.length > 0) || (isOverList && isOverList.length > 0)) {

                    // 导出的数据
                    const exportList: any = obj?.SETTLEMENT_STATE >= 1 ? JSON.parse(JSON.stringify(isOverList)) : JSON.parse(JSON.stringify(list))
                    console.log('exportList', exportList);

                    const exportRes: any = []
                    const exportRes2: any = []

                    const printList: any = []
                    // 保底/固定租金合计
                    let MinturnOverSum: number = 0
                    // 现金
                    let CashAmountSum: number = 0
                    // 微支付
                    let MobilePayAmountSum: number = 0
                    // 小计
                    let RevenueAmountSum: number = 0
                    // 提成金额
                    let amountSum: number = 0
                    let TotalFeeSum: number = 0
                    // 业主收款
                    let RoyaltyAmountSum: number = 0
                    // 应收租金
                    let GuaranteeFeeSum: number = 0
                    // 应收费用
                    let accountsReceivableSum: number = 0
                    let PaidFeeSum: number = 0
                    let PaidFee_9010Sum: number = 0
                    let PaidFee_9020Sum: number = 0
                    let PaidFee_9030Sum: number = 0
                    let PaidFee_9050Sum: number = 0
                    let PaidFee_9090Sum: number = 0
                    let PaidFee_9099Sum: number = 0
                    // 物业费
                    let PropertyFeeSum: number = 0
                    // 住宿费
                    let HouseRentSum: number = 0
                    // 罚款
                    let BreachPenaltySum: number = 0
                    // 电费
                    let ElectricityChargeSum: number = 0
                    // WaterCharge
                    let WaterChargeSum: number = 0
                    // 减免租金的合计
                    let ReductionAmountSum: number = 0
                    // 其他
                    let OtherFeeSum: number = 0
                    // 退补款
                    let RefundSupplementSum: number = 0
                    let GuaranteeRatioStr: any
                    let ReceivableAmountSum: number = 0

                    let addRevenueMoneyStr: any



                    exportList.forEach((item: any, index: number) => {
                        if (item.CorrectAmount) {
                            addRevenueMoneyStr = item.CorrectAmount
                        }



                        if (item.PeriodDesc !== '合计') {
                            if (item.PeriodIndexStr === "项目开始前") {
                                item.PeriodIndexStr = '装修期'
                            }
                            item.accountsReceivable = item.ReceivableAmount - item.GuaranteeFee
                            item.amount = (item.RevenueAmount * (item.GuaranteeRatio / 100)).toFixed(2)
                            console.log('item.amount', item.amount);

                            accountsReceivableSum += item.accountsReceivable * 100
                            amountSum += item.amount * 100
                            RoyaltyAmountSum += item.RoyaltyAmount * 100
                            MinturnOverSum += item.MinturnOver * 100
                            CashAmountSum += item.CashAmount * 100
                            MobilePayAmountSum += item.MobilePayAmount * 100
                            RevenueAmountSum += item.RevenueAmount * 100
                            GuaranteeFeeSum += item.GuaranteeFee * 100
                            RefundSupplementSum += item.RefundSupplement * 100
                            TotalFeeSum += item.TotalFee * 100
                            PaidFeeSum += item.PaidFee * 100
                            PaidFee_9010Sum += item.PaidFee_9010 * 100
                            PaidFee_9020Sum += item.PaidFee_9020 * 100
                            PaidFee_9030Sum += item.PaidFee_9030 * 100
                            PaidFee_9050Sum += item.PaidFee_9050 * 100
                            PaidFee_9090Sum += item.PaidFee_9090 * 100
                            PaidFee_9099Sum += item.PaidFee_9099 * 100
                            PropertyFeeSum += item.PropertyFee * 100
                            ReceivableAmountSum += item.ReceivableAmount * 100
                            HouseRentSum += item.HouseRent * 100
                            BreachPenaltySum += item.BreachPenalty * 100
                            ElectricityChargeSum += item.ElectricityCharge * 100
                            WaterChargeSum += item.WaterCharge * 100
                            ReductionAmountSum += item.ReductionAmount * 100
                            OtherFeeSum += item.OtherFee * 100
                            if (item.GuaranteeRatio) {
                                GuaranteeRatioStr = item.GuaranteeRatio
                            }

                            if (item.children && item.children.length > 0) {
                                item.children.forEach((subItem: any) => {
                                    subItem.accountsReceivable = subItem.ReceivableAmount - subItem.GuaranteeFee
                                    subItem.amount = (subItem.RevenueAmount * (subItem.GuaranteeRatio / 100)).toFixed(2)
                                    printList.push(subItem)
                                })
                            }

                            if (index + 1 === exportList.length) {
                                item.desc = obj.BusinessProcess_Desc
                            }
                            exportRes2.push(JSON.parse(JSON.stringify(item)))
                            item.children = null
                            exportRes.push(item)
                        }
                    })
                    console.log('exportResewsdas', exportRes);
                    console.log('exportRes2', exportRes2);
                    console.log('printList', printList);

                    setExportData(exportRes)
                    setExportData2(printList)
                    setPrintDetailData(exportRes2)
                    const sumObj: any = {
                        MinturnOver: handleHighPrecision(MinturnOverSum),
                        CashAmount: handleHighPrecision(CashAmountSum),
                        MobilePayAmount: handleHighPrecision(MobilePayAmountSum),
                        RevenueAmount: handleHighPrecision(RevenueAmountSum),
                        GuaranteeFee: handleHighPrecision(GuaranteeFeeSum),
                        RefundSupplement: handleHighPrecision(RefundSupplementSum),
                        accountsReceivable: handleHighPrecision(accountsReceivableSum),
                        amount: handleHighPrecision(amountSum),
                        RoyaltyAmount: handleHighPrecision(RoyaltyAmountSum),
                        TotalFee: handleHighPrecision(TotalFeeSum),
                        PaidFee: handleHighPrecision(PaidFeeSum),
                        PaidFee_9010: handleHighPrecision(PaidFee_9010Sum),
                        PaidFee_9020: handleHighPrecision(PaidFee_9020Sum),
                        PaidFee_9030: handleHighPrecision(PaidFee_9030Sum),
                        PaidFee_9050: handleHighPrecision(PaidFee_9050Sum),
                        PaidFee_9090: handleHighPrecision(PaidFee_9090Sum),
                        PaidFee_9099: handleHighPrecision(PaidFee_9099Sum),
                        PeriodIndexStr: '合计',
                        PropertyFee: handleHighPrecision(PropertyFeeSum),
                        HouseRent: handleHighPrecision(HouseRentSum),
                        BreachPenalty: handleHighPrecision(BreachPenaltySum),
                        ElectricityCharge: handleHighPrecision(ElectricityChargeSum),
                        WaterCharge: handleHighPrecision(WaterChargeSum),
                        OtherFee: handleHighPrecision(OtherFeeSum),
                        ReceivableAmount: handleHighPrecision(ReceivableAmountSum),
                        ReductionAmount: handleHighPrecision(ReductionAmountSum),
                        desc: '不含装修期',
                        addRevenueMoney: addRevenueMoneyStr
                    }
                    console.log('sumObj', sumObj);
                    sumObj.GuaranteeRatio = GuaranteeRatioStr
                    setExportSumRow(sumObj)
                }

                // 现在需要审核中或已审结的时候也会出现未选择的数据  2024-09-29
                if (list && list.length > 0) {
                    const newList: any = JSON.parse(JSON.stringify(list))
                    console.log('list', list);
                    console.log('res232', res);
                    // 其实就是 在老的里面 把已经申请了的 给替换成新的
                    const resList: any = []
                    newList.forEach((item: any) => {
                        if (res && res.length > 0) {
                            let isHave: boolean = false
                            let thisItem: any = {}
                            res.forEach((subItem: any) => {
                                if (item.PeriodIndex === subItem.PeriodIndex) {
                                    // item = JSON.parse(JSON.stringify(subItem))
                                    isHave = true
                                    thisItem = subItem
                                }
                            })
                            if (isHave) {
                                resList.push({
                                    ...thisItem,
                                    isInitiated: true // 表示已经申请过的
                                })
                            } else {
                                resList.push(item)
                            }
                        } else {
                            resList.push(item)
                        }
                    })
                    console.log('resList', resList);
                    return resList
                }
                // 一般情况都会被上面resList这个截停

                return res
            }
            setTableLoading(false)
            return []
        }
        let isTrue: boolean = true
        if (list && list.length > 0) {
            let CashAmountSum: number = 0
            let MobilePayAmountSum: number = 0
            let RevenueAmountSum: number = 0
            let RoyaltyAmountSum: number = 0
            let ReceivableAmountSum: number = 0
            let GuaranteeFeeSum: number = 0
            let PropertyFeeSum: number = 0
            let HouseRentSum: number = 0
            let BreachPenaltySum: number = 0
            let ElectricityChargeSum: number = 0
            let MinturnOverSum: number = 0
            let WaterChargeSum: number = 0
            let OtherFeeSum: number = 0
            let PaidFeeSum: number = 0
            let PaidFee_9010Sum: number = 0
            let PaidFee_9020Sum: number = 0
            let PaidFee_9030Sum: number = 0
            let PaidFee_9050Sum: number = 0
            let PaidFee_9090Sum: number = 0
            let PaidFee_9099Sum: number = 0
            let RefundSupplementSum: number = 0
            let GuaranteeRatioStr: string = ''

            list.forEach((item: any) => {
                if (item.children && item.children.length > 0) {
                    item.children.forEach((subItem: any) => {
                        if (!subItem.IsApplySuccess) {
                            isTrue = false
                        }
                    })
                }
                if (list.length > 1) {
                    CashAmountSum += item.CashAmount * 100
                    MobilePayAmountSum += item.MobilePayAmount * 100
                    RevenueAmountSum += item.RevenueAmount * 100
                    RoyaltyAmountSum += item.RoyaltyAmount * 100
                    ReceivableAmountSum += item.ReceivableAmount * 100
                    GuaranteeFeeSum += item.GuaranteeFee * 100
                    PropertyFeeSum += item.PropertyFee * 100
                    HouseRentSum += item.HouseRent * 100
                    BreachPenaltySum += item.BreachPenalty * 100
                    ElectricityChargeSum += item.ElectricityCharge * 100
                    WaterChargeSum += item.WaterCharge * 100
                    OtherFeeSum += item.OtherFee * 100
                    PaidFeeSum += item.PaidFee * 100
                    PaidFee_9010Sum += item.PaidFee_9010 * 100
                    PaidFee_9020Sum += item.PaidFee_9020 * 100
                    PaidFee_9030Sum += item.PaidFee_9030 * 100
                    PaidFee_9050Sum += item.PaidFee_9050 * 100
                    PaidFee_9090Sum += item.PaidFee_9090 * 100
                    PaidFee_9099Sum += item.PaidFee_9099 * 100
                    RefundSupplementSum += item.RefundSupplement * 100
                    GuaranteeRatioStr = item.GuaranteeRatio
                    MinturnOverSum += item.MinturnOver * 100
                }
            })

            if (list.length > 1) {
                const obj: any = {
                    level: 0,
                    PeriodDesc: '合计',
                    CashAmount: handleHighPrecision(CashAmountSum),
                    MobilePayAmount: handleHighPrecision(MobilePayAmountSum),
                    RevenueAmount: handleHighPrecision(RevenueAmountSum),
                    RoyaltyAmount: handleHighPrecision(RoyaltyAmountSum),
                    ReceivableAmount: handleHighPrecision(ReceivableAmountSum),
                    GuaranteeFee: handleHighPrecision(GuaranteeFeeSum),
                    PropertyFee: handleHighPrecision(PropertyFeeSum),
                    HouseRent: handleHighPrecision(HouseRentSum),
                    BreachPenalty: handleHighPrecision(BreachPenaltySum),
                    ElectricityCharge: handleHighPrecision(ElectricityChargeSum),
                    WaterCharge: handleHighPrecision(WaterChargeSum),
                    OtherFee: handleHighPrecision(OtherFeeSum),
                    PaidFee: handleHighPrecision(PaidFeeSum),
                    PaidFee_9010: handleHighPrecision(PaidFee_9010Sum),
                    PaidFee_9020: handleHighPrecision(PaidFee_9020Sum),
                    PaidFee_9030: handleHighPrecision(PaidFee_9030Sum),
                    PaidFee_9050: handleHighPrecision(PaidFee_9050Sum),
                    PaidFee_9090: handleHighPrecision(PaidFee_9090Sum),
                    PaidFee_9099: handleHighPrecision(PaidFee_9099Sum),
                    RefundSupplement: handleHighPrecision(RefundSupplementSum),
                    GuaranteeRatio: GuaranteeRatioStr,
                    MinturnOver: handleHighPrecision(MinturnOverSum)
                }
                list.unshift(obj)
                setExportData2Obj(obj)

            }
        }
        if (setIsShowMonthBtn) {
            setIsShowMonthBtn(isTrue)
        }
        console.log('list321312312', list);
        // setExportData2(list)

        setTableLoading(false)
        setReqDetailListDetail(list)
        if ((list && list.length > 0) || (isOverList && isOverList.length > 0)) {

            // 导出的数据
            let exportList: any = obj?.SETTLEMENT_STATE >= 1 ? JSON.parse(JSON.stringify(isOverList)) : JSON.parse(JSON.stringify(list))
            console.log('exportList', exportList);
            if (exportList && exportList.length > 0) {

            } else {
                exportList = JSON.parse(JSON.stringify(list))
            }

            const exportRes: any = []
            const exportRes2: any = []
            // 保底/固定租金合计
            let MinturnOverSum: number = 0
            // 现金
            let CashAmountSum: number = 0
            // 微支付
            let MobilePayAmountSum: number = 0
            // 小计
            let RevenueAmountSum: number = 0
            // 提成金额
            let amountSum: number = 0
            let TotalFeeSum: number = 0
            // 业主收款
            let RoyaltyAmountSum: number = 0
            // 应收租金
            let GuaranteeFeeSum: number = 0
            // 应收费用
            let accountsReceivableSum: number = 0
            let PaidFeeSum: number = 0
            let PaidFee_9010Sum: number = 0
            let PaidFee_9020Sum: number = 0
            let PaidFee_9030Sum: number = 0
            let PaidFee_9050Sum: number = 0
            let PaidFee_9090Sum: number = 0
            let PaidFee_9099Sum: number = 0
            // 物业费
            let PropertyFeeSum: number = 0
            // 住宿费
            let HouseRentSum: number = 0
            // 罚款
            let BreachPenaltySum: number = 0
            // 电费
            let ElectricityChargeSum: number = 0
            // WaterCharge
            let WaterChargeSum: number = 0
            // 减免金额合计
            let ReductionAmountSum: number = 0
            // 其他
            let OtherFeeSum: number = 0
            // 退补款
            let RefundSupplementSum: number = 0
            let ReceivableAmountSum: number = 0
            let GuaranteeRatioStr: any
            let addRevenueMoneyStr: any



            exportList.forEach((item: any, index: number) => {
                if (item.PeriodDesc !== '合计') {
                    if (item.addRevenueMoney) {
                        addRevenueMoneyStr = item.CorrectAmount
                    }

                    if (item.PeriodIndexStr === "项目开始前") {
                        item.PeriodIndexStr = '装修期'
                    }
                    item.accountsReceivable = item.ReceivableAmount - item.GuaranteeFee
                    item.amount = (item.RevenueAmount * (item.GuaranteeRatio / 100)).toFixed(2)
                    accountsReceivableSum += item.accountsReceivable * 100
                    amountSum += item.amount * 100
                    RoyaltyAmountSum += item.RoyaltyAmount * 100
                    MinturnOverSum += item.MinturnOver * 100
                    CashAmountSum += item.CashAmount * 100
                    MobilePayAmountSum += item.MobilePayAmount * 100
                    RevenueAmountSum += item.RevenueAmount * 100
                    GuaranteeFeeSum += item.GuaranteeFee * 100
                    RefundSupplementSum += item.RefundSupplement * 100
                    TotalFeeSum += item.TotalFee * 100
                    PaidFeeSum += item.PaidFee * 100
                    PaidFee_9010Sum += item.PaidFee_9010 * 100
                    PaidFee_9020Sum += item.PaidFee_9020 * 100
                    PaidFee_9030Sum += item.PaidFee_9030 * 100
                    PaidFee_9050Sum += item.PaidFee_9050 * 100
                    PaidFee_9090Sum += item.PaidFee_9090 * 100
                    PaidFee_9099Sum += item.PaidFee_9099 * 100
                    ReceivableAmountSum += item.ReceivableAmount * 100

                    PropertyFeeSum += item.PropertyFee * 100
                    HouseRentSum += item.HouseRent * 100
                    BreachPenaltySum += item.BreachPenalty * 100
                    ElectricityChargeSum += item.ElectricityCharge * 100
                    ReductionAmountSum += item.ReductionAmount * 100
                    WaterChargeSum += item.WaterCharge * 100
                    OtherFeeSum += item.OtherFee * 100
                    if (item.GuaranteeRatio) {
                        GuaranteeRatioStr = item.GuaranteeRatio
                    }

                    if (item.children && item.children.length > 0) {
                        item.children.forEach((subItem: any) => {
                            subItem.accountsReceivable = subItem.ReceivableAmount - subItem.GuaranteeFee
                            subItem.amount = (subItem.RevenueAmount * (subItem.GuaranteeRatio / 100)).toFixed(2)
                        })
                    }
                    if (index + 1 === exportList.length) {
                        item.desc = obj.BusinessProcess_Desc
                    }

                    exportRes2.push(JSON.parse(JSON.stringify(item)))
                    item.children = null
                    exportRes.push(item)
                }
            })
            console.log('exportResewsdas2', exportRes);
            console.log('exportRes2222222', exportRes2);
            setExportData(exportRes)
            setExportData2(exportRes2)
            const sumObj: any = {
                MinturnOver: handleHighPrecision(MinturnOverSum),
                CashAmount: handleHighPrecision(CashAmountSum),
                MobilePayAmount: handleHighPrecision(MobilePayAmountSum),
                RevenueAmount: handleHighPrecision(RevenueAmountSum),
                GuaranteeFee: handleHighPrecision(GuaranteeFeeSum),
                RefundSupplement: handleHighPrecision(RefundSupplementSum),
                accountsReceivable: handleHighPrecision(accountsReceivableSum),
                amount: handleHighPrecision(amountSum),
                TotalFee: handleHighPrecision(TotalFeeSum),
                RoyaltyAmount: handleHighPrecision(RoyaltyAmountSum),
                PaidFee: handleHighPrecision(PaidFeeSum),
                PaidFee_9010: handleHighPrecision(PaidFee_9010Sum),
                PaidFee_9020: handleHighPrecision(PaidFee_9020Sum),
                PaidFee_9030: handleHighPrecision(PaidFee_9030Sum),
                PaidFee_9050: handleHighPrecision(PaidFee_9050Sum),
                PaidFee_9090: handleHighPrecision(PaidFee_9090Sum),
                PaidFee_9099: handleHighPrecision(PaidFee_9099Sum),
                PeriodIndexStr: '合计',
                HouseRent: handleHighPrecision(HouseRentSum),
                BreachPenalty: handleHighPrecision(HouseRentSum),
                ElectricityCharge: handleHighPrecision(HouseRentSum),
                WaterCharge: handleHighPrecision(HouseRentSum),
                OtherFee: handleHighPrecision(HouseRentSum),
                ReductionAmount: handleHighPrecision(ReductionAmountSum),
                ReceivableAmount: handleHighPrecision(ReceivableAmountSum),
                desc: '不含装修期',
                addRevenueMoney: addRevenueMoneyStr
            }

            sumObj.GuaranteeRatio = GuaranteeRatioStr
            console.log('sumObj', sumObj);

            setExportSumRow(sumObj)
        }
        return list


    }
    // 计算表格的合计值
    const handleGetTableSum = (newList: any, list: any) => {
        // newList实际数据
        // list 已经勾选的行数组
        if (newList && newList.length > 0) {
            let CashAmountSum: number = 0
            let MobilePayAmountSum: number = 0
            let RevenueAmountSum: number = 0
            let RoyaltyAmountSum: number = 0
            let MinturnOverSum: number = 0
            let ReceivableAmountSum: number = 0
            let GuaranteeFeeSum: number = 0
            let PropertyFeeSum: number = 0
            let HouseRentSum: number = 0
            let BreachPenaltySum: number = 0
            let ElectricityChargeSum: number = 0
            let WaterChargeSum: number = 0
            let OtherFeeSum: number = 0
            let PaidFeeSum: number = 0
            let PaidFee_9010Sum: number = 0
            let PaidFee_9020Sum: number = 0
            let PaidFee_9030Sum: number = 0
            let PaidFee_9050Sum: number = 0
            let PaidFee_9090Sum: number = 0
            let PaidFee_9099Sum: number = 0
            let RefundSupplementSum: number = 0
            let GuaranteeRatioStr: string = ''
            newList.forEach((item: any) => {
                // 拿到已经勾选的行
                if (list.indexOf(`${item?.ShopRoyalty_Id}-${item?.PeriodIndexStr}-${item?.StartDate}-${item?.EndDate}-${item?.level}`) !== -1) {
                    CashAmountSum += item.CashAmount * 100
                    MobilePayAmountSum += item.MobilePayAmount * 100
                    RevenueAmountSum += item.RevenueAmount * 100
                    RoyaltyAmountSum += item.RoyaltyAmount * 100
                    ReceivableAmountSum += item.ReceivableAmount * 100
                    GuaranteeFeeSum += item.GuaranteeFee * 100
                    PropertyFeeSum += item.PropertyFee * 100
                    HouseRentSum += item.HouseRent * 100
                    BreachPenaltySum += item.BreachPenalty * 100
                    ElectricityChargeSum += item.ElectricityCharge * 100
                    WaterChargeSum += item.WaterCharge * 100
                    OtherFeeSum += item.OtherFee * 100
                    PaidFeeSum += item.PaidFee * 100
                    PaidFee_9010Sum += item.PaidFee_9010 * 100
                    PaidFee_9020Sum += item.PaidFee_9020 * 100
                    PaidFee_9030Sum += item.PaidFee_9030 * 100
                    PaidFee_9050Sum += item.PaidFee_9050 * 100
                    PaidFee_9090Sum += item.PaidFee_9090 * 100
                    PaidFee_9099Sum += item.PaidFee_9099 * 100
                    RefundSupplementSum += item.RefundSupplement * 100
                    GuaranteeRatioStr = item.GuaranteeRatio
                    MinturnOverSum += item.MinturnOver * 100
                }
            })
            const obj: any = {
                PeriodDesc: '合计',
                level: 0,
                noSelect: true,
                CashAmount: handleHighPrecision(CashAmountSum),
                MobilePayAmount: handleHighPrecision(MobilePayAmountSum),
                RevenueAmount: handleHighPrecision(RevenueAmountSum),
                RoyaltyAmount: handleHighPrecision(RoyaltyAmountSum),
                ReceivableAmount: handleHighPrecision(ReceivableAmountSum),
                GuaranteeFee: handleHighPrecision(GuaranteeFeeSum),
                PropertyFee: handleHighPrecision(PropertyFeeSum),
                HouseRent: handleHighPrecision(HouseRentSum),
                BreachPenalty: handleHighPrecision(BreachPenaltySum),
                ElectricityCharge: handleHighPrecision(ElectricityChargeSum),
                WaterCharge: handleHighPrecision(WaterChargeSum),
                OtherFee: handleHighPrecision(OtherFeeSum),
                PaidFee: handleHighPrecision(PaidFeeSum),
                PaidFee_9010: handleHighPrecision(PaidFee_9010Sum),
                PaidFee_9020: handleHighPrecision(PaidFee_9020Sum),
                PaidFee_9030: handleHighPrecision(PaidFee_9030Sum),
                PaidFee_9050: handleHighPrecision(PaidFee_9050Sum),
                PaidFee_9090: handleHighPrecision(PaidFee_9090Sum),
                PaidFee_9099: handleHighPrecision(PaidFee_9099Sum),
                RefundSupplement: handleHighPrecision(RefundSupplementSum),
                GuaranteeRatio: GuaranteeRatioStr,
                MinturnOver: handleHighPrecision(MinturnOverSum)
            }
            newList.unshift(obj)
        }
        return newList
    }
    const modalRowSelection: any = {
        // defaultSelectedRowKeys: defaultSelectRow,
        selectedRowKeys: selectRowKey,
        onChange: (selectedRowKeys: any, selectedRows: any) => {
            confirm({
                width: 500,
                content: <div>
                    {`是否确认不计提装修期费用`}
                </div>,
                onOk: async () => {
                    console.log('selectedRowKeys', selectedRowKeys);
                    console.log('selectedRows', selectedRows);

                    // 因为直接点击加入装修期之后 装修期会在正常期的后面 肯定不行的 所以按时间排一下
                    const list: any = JSON.parse(JSON.stringify(selectedRows))
                    const len: number = list.length;

                    for (let i = 0; i < len - 1; i++) {
                        for (let j = 0; j < len - 1 - i; j++) {
                            if (new Date(moment(list[j].StartDate).format('YYYY-MM-DD')).getTime() > new Date(moment(list[j + 1].StartDate).format('YYYY-MM-DD')).getTime()) { // 相邻元素两两对比
                                const temp = list[j + 1]; // 元素交换
                                list[j + 1] = list[j];
                                list[j] = temp;
                            }
                        }
                    }
                    console.log('list', list);


                    setSelectRowKey(selectedRowKeys)
                    setSelectDetailList(list)
                    let newList: any = []
                    if (reqDetailListDetail && reqDetailListDetail.length > 0) {
                        reqDetailListDetail.forEach((item: any) => {
                            if (item.children && item.children.length > 0) {
                                item.children.forEach((subItem: any) => {
                                    newList.push(subItem)
                                })
                            }
                            // if (item.PeriodDesc !== '合计') {
                            //     newList.push(item)
                            // }
                        })
                    }
                    console.log('reqDetailListDetail', reqDetailListDetail);
                    console.log('selectedRowKeys', selectedRowKeys);
                    console.log('newList', newList);

                    newList = handleGetTableSum(newList, selectedRowKeys)
                    // console.log('newList', newList);
                    // setReqDetailListDetail(newList)
                }
            });

        },
        getCheckboxProps: (record: any) => ({
            disabled: record?.noSelect,
        }),
    }



    const exportTable = (e) => {
        e.stopPropagation();
        const bigMain = document.getElementsByClassName('settlementAccountHideBox')[0]
        const main = bigMain.getElementsByClassName('export2')[0]

        console.log('formatExportData.current', formatExportData.current);


        const thead = main.querySelector('thead').cloneNode(true);  // 深克隆DOM节点
        const tbody = main.querySelector('tbody').cloneNode(true);  // 深克隆DOM节点
        const tfoot = main.querySelector('tfoot').cloneNode(true);  // 深克隆DOM节点


        const tableTitle = document.createElement('div');
        tableTitle.innerText = `合作经营商户合同期结算明细表`
        tableTitle.setAttribute('style', 'width:100%;text-align:center;font-size:20px;font-weight: 600;')
        const header = document.createElement('div');
        const SPREGIONTYPE_NAME = document.createElement('span');
        SPREGIONTYPE_NAME.innerText = `中心：${otherData?.SPREGIONTYPE_NAME || ''}`

        const SERVERPART_NAME = document.createElement('span');
        SERVERPART_NAME.innerText = `　　　服务区：${otherData?.SERVERPART_NAME || ''}`

        const SERVERPARTSHOP_NAME = document.createElement('span');
        SERVERPARTSHOP_NAME.innerText = `　　　门店名称：${otherData?.SERVERPARTSHOP_NAME || ''}`

        const MERCHANTS_NAME = document.createElement('span');
        MERCHANTS_NAME.innerText = `　　　经营商户名称：${otherData?.MERCHANTS_NAME || ''}`

        const projectDate = document.createElement('span');
        projectDate.innerText = `　　　合同期：${otherData?.PROJECT_STARTDATE ? moment(otherData?.PROJECT_STARTDATE).format('YYYY.MM.DD') : ''}-${otherData?.PROJECT_ENDDATE ? moment(otherData?.PROJECT_ENDDATE).format('YYYY.MM.DD') : ''}`

        header.appendChild(SPREGIONTYPE_NAME)
        header.appendChild(SERVERPART_NAME)
        header.appendChild(SERVERPARTSHOP_NAME)
        header.appendChild(MERCHANTS_NAME)
        header.appendChild(projectDate)
        header.setAttribute('style', 'width:100%;font-size:14px;font-weight: 600;')


        const container = document.querySelector('#hiddenBox');

        const tempTable = document.createElement('table');
        tempTable.appendChild(tableTitle);
        tempTable.appendChild(header);

        tempTable.appendChild(thead);
        tempTable.appendChild(tbody);
        tempTable.appendChild(tfoot);

        tempTable.setAttribute('id', 'table-to-xls-settlementAccount');                    // 给table添加id，值与按钮上的table字段对应

        container.appendChild(tempTable);                                // 把创建的节点添加到页面容器中

        downloadBtnRef.current.handleDownload();
        setShowExportTable(false)
        tempTable.remove() // 防止重复打印一个内容
        exportType = 0
    }

    const exportExcel = (e) => {
        e.stopPropagation();                                            // 防止Collapse组件收起
        const bigMain = document.getElementsByClassName('settlementAccountHideBox')[0]
        const main = bigMain.getElementsByClassName('export1')[0]
        const thead = main.querySelector('thead').cloneNode(true);  // 深克隆DOM节点
        const tbody = main.querySelector('tbody').cloneNode(true);  // 深克隆DOM节点
        const tfoot = main.querySelector('tfoot').cloneNode(true);  // 深克隆DOM节点


        const tableTitle = document.createElement('div');
        tableTitle.innerText = `${parentRow?.BUSINESSPROJECT_NAME}项目结算明细表`
        tableTitle.setAttribute('style', 'width:100%;text-align:center;font-size:20px;font-weight: 600;')

        const container = document.querySelector('#hiddenBox');

        const tempTable = document.createElement('table');

        tempTable.appendChild(tableTitle);
        tempTable.appendChild(thead);
        tempTable.appendChild(tbody);
        tempTable.appendChild(tfoot);

        tempTable.setAttribute('id', 'table-to-xls-settlementAccount1');                    // 给table添加id，值与按钮上的table字段对应

        container.appendChild(tempTable);                                // 把创建的节点添加到页面容器中

        downloadBtnRef1.current.handleDownload();
        setShowExportTable(false)
        tempTable.remove() // 防止重复打印一个内容
        exportType = 0
    }

    // 拿到流程进度的数据
    const handleGetProcessProgress = async (id: any) => {
        const req: any = {
            BUSINESSAPPROVALId: id || parentRow?.BUSINESSAPPROVAL_ID
        }
        const data = await handleGetGetBUSINESSAPPROVALDetail(req)
        console.log('datahandleGetProcessProgress', data);

        // 给导出弄签字
        const obj: any = {
            financeName: '',// 财务部签名
            financeRealName: '',// 财务部签名(只有人名)
            developmentName: '',// 经发部签名
            developmentRealName: '',// 经发部签名(只有人名)
            directorName: '',// 中心主任签名
            directorRealName: '',// 中心主任签名(只有人名)
            centralFinanceName: '',// 中心财务签名
            centralFinanceRealName: '',// 中心财务签名(只有人名)
            operationsSuperName: '',// 中心经营主管签名
            operationsSuperRealName: '',// 中心经营主管签名(只有人名)
            areaManagerName: '',// 服务区经理签名
            areaManagerRealName: '',// 服务区经理签名(只有人名)
            confirmationName: '',// 商户确认签名
            confirmationRealName: '',// 商户确认签名(只有人名)
            developManagerName: data.STAFF_NAME,// 经发人签名
            developManagerRealName: `${data.STAFF_NAME.split('【')[0]} ${data.BUSINESS_STARTDATE}`,// 经发人签名(只有人名)
        }

        if (data.approveList && data.approveList.length > 0) {
            data.approveList.forEach((item: any) => {
                // if (item.APPLYAPPROVE_TYPE === 1000) {
                //     obj.developManagerName = item.STAFF_NAME
                //     obj.developManagerRealName = item.STAFF_NAME.split('【')[0] + ` ${item.APPLYAPPROVE_DATE}`
                // } else
                if (item.APPLYAPPROVE_TYPE === 2000) {
                    obj.confirmationName = item.STAFF_NAME
                    obj.confirmationRealName = `${item.STAFF_NAME.split('【')[0]} ${item.APPLYAPPROVE_DATE}`
                } else if (item.APPLYAPPROVE_TYPE === 2010) {
                    obj.areaManagerName = item.STAFF_NAME
                    obj.areaManagerRealName = `${item.STAFF_NAME.split('【')[0]} ${item.APPLYAPPROVE_DATE}`
                } else if (item.APPLYAPPROVE_TYPE === 2020) {
                    obj.operationsSuperName = item.STAFF_NAME
                    obj.operationsSuperRealName = `${item.STAFF_NAME.split('【')[0]} ${item.APPLYAPPROVE_DATE}`
                } else if (item.APPLYAPPROVE_TYPE === 2030) {
                    obj.centralFinanceName = item.STAFF_NAME
                    obj.centralFinanceRealName = `${item.STAFF_NAME.split('【')[0]} ${item.APPLYAPPROVE_DATE}`
                } else if (item.APPLYAPPROVE_TYPE === 2040) {
                    obj.directorName = item.STAFF_NAME
                    obj.directorRealName = `${item.STAFF_NAME.split('【')[0]} ${item.APPLYAPPROVE_DATE}`
                } else if (item.APPLYAPPROVE_TYPE === 2050) {
                    obj.developmentName = item.STAFF_NAME
                    obj.developmentRealName = `${item.STAFF_NAME.split('【')[0]} ${item.APPLYAPPROVE_DATE}`
                } else if (item.APPLYAPPROVE_TYPE === 2060) {
                    obj.financeName = item.STAFF_NAME
                    obj.financeRealName = `${item.STAFF_NAME.split('【')[0]} ${item.APPLYAPPROVE_DATE}`
                }
            })
        }
        setSignatureObj(obj)

        // 拿到一共有多少个审批流程
        setProgressDetail(data)
        if (data.BUSINESSAPPROVAL_STATE === 2000) {
            setProgressState(1)
        } else if (data.BUSINESSAPPROVAL_STATE === 2010) {
            setProgressState(2)
        } else if (data.BUSINESSAPPROVAL_STATE === 2020) {
            setProgressState(3)
        } else if (data.BUSINESSAPPROVAL_STATE === 2030) {
            setProgressState(4)
        } else if (data.BUSINESSAPPROVAL_STATE === 2040) {
            setProgressState(5)
        } else if (data.BUSINESSAPPROVAL_STATE === 9000) {
            setProgressState(6)
        }
        if (data.approveList && data.approveList.length > 0) {
            const progress: any = JSON.parse(JSON.stringify(progressList))

            data.approveList.forEach((item: any, index: number) => {
                if (progress[index]) {
                    progress[index].desc = item
                }
            })
            setProgressList(progress)
        }
        return data.BUSINESSAPPROVAL_STATE
    }


    // 预览上传后的图片
    const handlePreview = async () => {
        setFileList(fileList)
        setImagePreviewVisible(true)
    };

    // 拿到附件列表
    const handleGetFile = async () => {
        if (!parentRow?.BUSINESSAPPROVAL_ID) {
            return
        }
        const req: any = {
            TableId: parentRow?.BUSINESSAPPROVAL_ID,
            TableType: 1130,
        }
        const data = await handleGetPictureList(req)
        console.log('data', data);
        const list: any = data.Result_Data.List
        const res: any = []
        if (list && list.length > 0) {
            list.forEach((item: any) => {
                res.push({
                    uid: `${item.ImageId}`, // 注意，这个uid一定不能少，否则上传失败
                    name: item.ImageName,
                    status: 'done',
                    url: item.ImageUrl, // url 是展示在页面上的绝对链接
                    imgUrl: item.ImagePath,  // + success.ImageUrl,
                    IsImg: item.IsImg
                })
            })
        }
        console.log('res', res);
        setFileList(res)
    }

    // 退场结算
    const handleCloseSettlement = async (obj: any) => {
        console.log('obj', obj);
        const req: any = obj.List[0]
        setTableLoading(true)
        const data = await handleRebuildClosedPeriod(req)
        if (data.Result_Code === 100) {
            message.success(data.Result_Desc)
            const oldObj: any = JSON.parse(JSON.stringify(obj))
            const oldList: any = oldObj.List
            oldList[0].ProjectPeriodList = data.Result_Data
            // setAfterCloseData(oldObj)
            afterCloseData.current = oldObj
            actionRef.current?.reload()
        } else {
            console.log('datadsadasd', data);

            message.error(data.Result_Desc)
        }
        setTableLoading(false)
    }

    // 对数据一个对象数据进行格式化
    const handleFormatObj = (obj: any, str: string) => {
        if (str) {
            const list: any = str.split(',')
            if (list && list.length > 0) {
                const newObj: any = JSON.parse(JSON.stringify(obj))
                list.forEach((item: any) => {
                    newObj[item] = formatToTwoDecimalPlaces(newObj[item])
                })
                return newObj
            }
        }
    }

    useImperativeHandle(onRef, () => ({
        reqDetailListDetail,
        handleGetTableData,
        selectDetailList,
        afterCloseData // 如果点击过撤场结算 就会有数据 
    }));
    return (
        <div>
            {
                showExportTable ?
                    <div
                        style={{
                            width: '100%',
                            height: '100%',
                            background: 'rgba(0,0,0,0.1)',
                            position: 'fixed',
                            zIndex: 1100,
                            display: 'flex',
                            alignItems: 'center',
                            justifyContent: 'center'
                        }}
                    >
                        <div style={{
                            display: 'flex',
                            alignItems: 'center',
                            justifyContent: 'center',
                            padding: '15px 20px 10px',
                            background: '#fff',
                            borderRadius: '8px',
                            width: '200px'
                        }}>
                            <Spin />
                            <span style={{ marginLeft: '5px' }}>数据导出中...</span>
                        </div>
                    </div> : ''
            }

            <div id='hiddenBox' style={{ position: 'fixed', zIndex: 1100, top: 0, left: 0 }} />
            <div className={'settlementAccountHideBox'} style={{ position: 'fixed', zIndex: -1, top: 0, left: 0 }}>
                <div className="export1">
                    {
                        showExportTable && reqDetailListDetail && reqDetailListDetail.length > 0 ?
                            <ProTable
                                columns={columns}
                                dataSource={exportDetailTableData}
                                pagination={false}
                                expandable={{
                                    defaultExpandAllRows: true
                                }}
                                summary={() => {
                                    return <>
                                        <tr>
                                            <td colSpan={2} align={'center'}>合计</td>
                                            <td>{exportSumRow?.MinturnOver ? handleFormatNumber(exportSumRow?.MinturnOver) : '0'}</td>
                                            <td>{exportSumRow?.GuaranteeRatio ? `${exportSumRow?.GuaranteeRatio}%` : ''}</td>
                                            <td>{exportSumRow?.CashAmount ? handleFormatNumber(exportSumRow?.CashAmount) : '0'}</td>
                                            <td>{exportSumRow?.MobilePayAmount ? handleFormatNumber(exportSumRow?.MobilePayAmount) : '0'}</td>
                                            <td>{exportSumRow?.RevenueAmount ? handleFormatNumber(exportSumRow?.RevenueAmount) : '0'}</td>
                                            <td>{exportSumRow?.RoyaltyAmount ? handleFormatNumber(exportSumRow?.RoyaltyAmount) : '0'}</td>
                                            <td>{exportSumRow?.ReceivableAmount ? handleFormatNumber(exportSumRow?.ReceivableAmount) : '0'}</td>
                                            <td>{exportSumRow?.GuaranteeFee ? handleFormatNumber(exportSumRow?.GuaranteeFee) : '0'}</td>
                                            <td>{exportSumRow?.PropertyFee ? handleFormatNumber(exportSumRow?.PropertyFee) : '0'}</td>
                                            <td>{exportSumRow?.HouseRent ? handleFormatNumber(exportSumRow?.HouseRent) : '0'}</td>
                                            <td>{exportSumRow?.BreachPenalty ? handleFormatNumber(exportSumRow?.BreachPenalty) : '0'}</td>
                                            <td>{exportSumRow?.ElectricityCharge ? handleFormatNumber(exportSumRow?.ElectricityCharge) : '0'}</td>
                                            <td>{exportSumRow?.WaterCharge ? handleFormatNumber(exportSumRow?.WaterCharge) : '0'}</td>
                                            <td>{exportSumRow?.OtherFee ? handleFormatNumber(exportSumRow?.OtherFee) : '0'}</td>
                                            <td>{exportSumRow?.PaidFee ? handleFormatNumber(exportSumRow?.PaidFee) : '0'}</td>
                                            <td>{exportSumRow?.PaidFee_9010 ? handleFormatNumber(exportSumRow?.PaidFee_9010) : '0'}</td>
                                            <td>{exportSumRow?.PaidFee_9020 ? handleFormatNumber(exportSumRow?.PaidFee_9020) : '0'}</td>
                                            <td>{exportSumRow?.PaidFee_9030 ? handleFormatNumber(exportSumRow?.PaidFee_9030) : '0'}</td>
                                            <td>{exportSumRow?.PaidFee_9050 ? handleFormatNumber(exportSumRow?.PaidFee_9050) : '0'}</td>
                                            <td>{exportSumRow?.PaidFee_9090 ? handleFormatNumber(exportSumRow?.PaidFee_9090) : '0'}</td>
                                            <td>{exportSumRow?.PaidFee_9099 ? handleFormatNumber(exportSumRow?.PaidFee_9099) : '0'}</td>
                                            <td>{exportSumRow?.ReductionAmount ? handleFormatNumber(exportSumRow?.ReductionAmount) : '0'}</td>
                                            <td>{exportSumRow?.RefundSupplement ? handleFormatNumber(exportSumRow?.RefundSupplement) : '0'}</td>
                                            <td>{exportSumRow?.addRevenueMoney ? `备注：营收冲正${(exportSumRow?.addRevenueMoney)}元` : ''}</td>
                                        </tr>
                                    </>
                                }}
                            /> : ''
                    }
                </div>
                <div className="export2">
                    {
                        showExportTable && exportData && exportData.length > 0 ?
                            <ProTable
                                columns={exportColumns}
                                dataSource={exportData}
                                pagination={false}
                                expandable={{
                                    defaultExpandAllRows: true
                                }}
                                summary={() => {
                                    return <>
                                        <tr>
                                            <td colSpan={2} align={'center'}>{exportSumRow?.PeriodIndexStr}1</td>
                                            <td>{exportSumRow?.MinturnOver ? handleFormatNumber(exportSumRow?.MinturnOver) : '0'}</td>
                                            <td></td>
                                            <td>{exportSumRow?.CashAmount ? handleFormatNumber(exportSumRow?.CashAmount) : '0'}</td>
                                            <td>{exportSumRow?.MobilePayAmount ? handleFormatNumber(exportSumRow?.MobilePayAmount) : '0'}</td>
                                            <td>{exportSumRow?.RevenueAmount ? handleFormatNumber(exportSumRow?.RevenueAmount) : '0'}</td>
                                            <td>{exportSumRow?.amount ? handleFormatNumber(exportSumRow?.amount) : '0'}</td>
                                            <td>{exportSumRow?.RoyaltyAmount ? handleFormatNumber(exportSumRow?.RoyaltyAmount) : '0'}</td>
                                            <td>{exportSumRow?.GuaranteeFee ? handleFormatNumber(exportSumRow?.GuaranteeFee) : '0'}</td>
                                            {/* <td>{exportSumRow?.ReceivableAmount ? handleFormatNumber(exportSumRow?.ReceivableAmount) : '0'}</td> */}
                                            <td>{exportSumRow?.TotalFee ? handleFormatNumber(exportSumRow?.TotalFee) : '0'}</td>
                                            <td>{exportSumRow?.PaidFee ? handleFormatNumber(exportSumRow?.PaidFee) : '0'}</td>
                                            {/* <td>{exportSumRow?.PaidFee_9010 ? numeral(exportSumRow?.PaidFee_9010).format('0,0.00') : ''}</td>
                                            <td>{exportSumRow?.PaidFee_9020 ? numeral(exportSumRow?.PaidFee_9020).format('0,0.00') : ''}</td>
                                            <td>{exportSumRow?.PaidFee_9030 ? numeral(exportSumRow?.PaidFee_9030).format('0,0.00') : ''}</td>
                                            <td>{exportSumRow?.PaidFee_9050 ? numeral(exportSumRow?.PaidFee_9050).format('0,0.00') : ''}</td>
                                            <td>{exportSumRow?.PaidFee_9090 ? numeral(exportSumRow?.PaidFee_9090).format('0,0.00') : ''}</td>
                                            <td>{exportSumRow?.PaidFee_9099 ? numeral(exportSumRow?.PaidFee_9099).format('0,0.00') : ''}</td> */}
                                            <td>{exportSumRow?.ReductionAmount ? handleFormatNumber(exportSumRow?.ReductionAmount) : '0'}</td>
                                            <td>{exportSumRow?.RefundSupplement ? handleFormatNumber(exportSumRow?.RefundSupplement) : '0'}</td>
                                            <td>{exportSumRow?.desc}</td>
                                        </tr>
                                        <tr></tr>
                                        <tr>
                                            <td colSpan={1} align={'right'}>{`${new Date(parentRow?.CLOSED_DATE || parentRow?.ENDDATE).getTime() > new Date('2025-04-01 00:00:00').getTime() ? '运营管理子公司' : ''}财务部：`}</td>
                                            <td colSpan={6}>{signature?.financeName || ''}</td>
                                            <td colSpan={1} align={'right'}>{`${new Date(parentRow?.CLOSED_DATE || parentRow?.ENDDATE).getTime() > new Date('2025-04-01 00:00:00').getTime() ? '运营管理子公司运营服务部：' : '经发部：'}`}</td>
                                            <td colSpan={6}>{signature?.developmentName || ''}</td>
                                        </tr>
                                        <tr></tr>
                                        <tr>
                                            <td colSpan={1} align={'right'}>{'中心主任：'}</td>
                                            <td colSpan={2}>{signature?.directorName || ''}</td>
                                            <td colSpan={1} align={'right'}>{'中心财务：'}</td>
                                            <td colSpan={2}>{signature?.centralFinanceName || ''}</td>
                                            <td colSpan={1} align={'right'}>{'中心经营主管：'}</td>
                                            <td colSpan={2}>{signature?.operationsSuperName || ''}</td>
                                            <td colSpan={1} align={'right'}>{'服务区经理：'}</td>
                                            <td colSpan={2}>{signature?.areaManagerName || ''}</td>
                                            <td colSpan={1} align={'right'}>{'商户确认：'}</td>
                                            <td colSpan={2}>{signature?.confirmationName || ''}</td>
                                            <td colSpan={1} align={'right'}>{'发起人：'}</td>
                                            <td colSpan={2}>{signature?.developManagerName || ''}</td>
                                        </tr>
                                    </>

                                }}
                            /> : ''
                    }
                </div>
                {/* <div className="exportpayableFees">
                    <ProTable
                        columns={payableFees}
                        dataSource={payableFeesExportTableData}
                        pagination={false}
                        expandable={{
                            defaultExpandAllRows: true
                        }}
                        summary={() => {
                            return <>
                                <tr>
                                    <td colSpan={11} align={'center'}>结算期应扣费用</td>
                                    <td colSpan={1} align={'right'}>{deductibleData ? numeral(getMoney(deductibleData)).format('0,0.00') : ''}</td>
                                </tr>
                            </>
                        }}

                    />
                </div>  */}
            </div>

            <ProTable
                rowKey={(record) => {
                    return `${record?.ShopRoyalty_Id}-${record?.PeriodIndexStr}-${record?.StartDate}-${record?.EndDate}-${record?.level}`
                }}
                ref={tableRef}
                actionRef={actionRef}
                formRef={formRef}
                columns={columns}
                bordered
                search={false}
                className={'detailTable'}
                rowClassName={(record) => {
                    return currentApprovalstate >= 1 && record.garyRow ? 'garyRow' : ''
                }}
                loading={tableLoading}
                request={async (params: any) => {
                    console.log('parentRow222222', parentRow);
                    const resultList: any = await handleGetTableData(parentRow?.BUSINESSPROJECT_ID, parentRow?.SHOPROYALTY_ID, parentRow, afterCloseData.current)

                    // const firstData: any = await handleGetTableData(parentRow?.BUSINESSPROJECT_ID, parentRow?.SHOPROYALTY_ID, parentRow)
                    // console.log('firstData', firstData);
                    // let req: any = {}
                    // if (firstData.isShowClose) {
                    //     req = await handleCloseSettlement(firstData.data)
                    // } else {
                    //     req = firstData.data
                    // }
                    // const resultList: any = await handleGetTableData(parentRow?.BUSINESSPROJECT_ID, parentRow?.SHOPROYALTY_ID, parentRow, req)

                    // console.log('reqDetailListDetail222222', resultList);
                    console.log('resultList3213123', resultList);

                    if (resultList && resultList.length > 0) {
                        // 现在变成表格数据的合计项必须是勾选了的才计算合计 那么从这开始计算的时候必须要给表格赋值新的值
                        let newList: any = [] // 用来算合计的实际勾选数据
                        const list: string[] = []
                        const res: any = []
                        // 导出结算明细表的数据 2024-11-04
                        const exportDetailList: any = []

                        // 当前状态
                        let currentState: any = ''
                        // 需要先拿流程状态
                        if (parentRow?.BUSINESSAPPROVAL_ID) {
                            const req: any = {
                                BUSINESSAPPROVALId: parentRow?.BUSINESSAPPROVAL_ID
                            }
                            const BUSINESSAPPROVALData = await handleGetGetBUSINESSAPPROVALDetail(req)
                            currentState = BUSINESSAPPROVALData?.BUSINESSAPPROVAL_STATE
                        }

                        resultList.forEach((item: any) => {
                            console.log('item', item);

                            if (item.PeriodDesc === '合计') {
                                item.noSelect = true
                            } else {

                                if ((item.RefundSupplement === 0 || !item.RefundSupplement)) {
                                    let sum: number = 0
                                    if (item.children && item.children.length > 0) {
                                        item.children.forEach((subItem: any) => {
                                            sum += subItem.RefundSupplement
                                        })
                                    }
                                    item.RefundSupplement = sum
                                }
                                newList.push(item)
                            }
                            // 如果是重新申请 即使有BUSINESSAPPROVAL_ID 也不能把装修期他们算进去
                            if (parentRow?.BUSINESSAPPROVAL_ID) {
                                if (item.PeriodDesc !== '合计') {

                                    if (currentState === 1000) {
                                        // 默认选中
                                        list.push(`${item?.ShopRoyalty_Id}-${item?.PeriodIndexStr}-${item?.StartDate}-${item?.EndDate}-${item?.level}`)
                                        res.push(item)
                                        if (item.PeriodIndex > 0) {
                                            item.noSelect = true
                                        }
                                    } else {
                                        if (item.isInitiated) {
                                            list.push(`${item?.ShopRoyalty_Id}-${item?.PeriodIndexStr}-${item?.StartDate}-${item?.EndDate}-${item?.level}`)
                                            res.push(item)
                                            item.noSelect = true
                                        } else {
                                            item.garyRow = true
                                            if (item.children && item.children.length > 0) {
                                                item.children.forEach((childrenItem: any) => {
                                                    childrenItem.garyRow = true
                                                })
                                            }
                                            item.noSelect = true
                                        }
                                    }

                                }
                            } else {
                                // 默认选中
                                list.push(`${item?.ShopRoyalty_Id}-${item?.PeriodIndexStr}-${item?.StartDate}-${item?.EndDate}-${item?.level}`)
                                res.push(item)
                                if (item.PeriodIndex > 0) {

                                    item.noSelect = true
                                }
                            }
                            if (item.children && item.children.length > 0) {

                                item.children.forEach((subItem: any) => {

                                    // 拿到结算明细excel的数据 只要子级的数据 2024-11-04 
                                    exportDetailList.push(subItem)

                                    subItem.noSelect = true
                                    // list.push(`${subItem?.ShopRoyalty_Id}-${subItem?.PeriodIndexStr}-${subItem?.StartDate}-${subItem?.EndDate}-${subItem?.level}`)
                                })

                            }


                        })
                        console.log('newList', newList);
                        // 给表格添加新的合计项 但是需要已经勾选表格数据大于一条
                        if (list && list.length > 0) {
                            newList = handleGetTableSum(newList, list)
                        }
                        console.log('newListnewListnewListnewList', newList);
                        console.log('listdasdasda', list);
                        console.log('resresresres', res);
                        // 默认展开的有子级的数据
                        if (newList && newList.length > 0) {
                            const defaultList: any = []
                            newList.forEach((item: any) => {
                                if (item.PeriodDesc !== '合计') {
                                    defaultList.push(`${item?.ShopRoyalty_Id}-${item?.PeriodIndexStr}-${item?.StartDate}-${item?.EndDate}-${item?.level}`)
                                }
                            })
                            // 默认不展开 2024-11-05
                            // setDefaultSelectRow(defaultList)
                        }
                        console.log('newList', newList);

                        setReqDetailListDetail(newList)
                        // 默认选中行的具体数据
                        setSelectDetailList(res)
                        setSelectRowKey(list)


                        // 导出结算明细 的每一项数据 和计算合计
                        if (exportDetailList && exportDetailList.length > 0) {
                            const printList: any = []
                            // 保底/固定租金合计
                            let MinturnOverSum: number = 0
                            // 现金
                            let CashAmountSum: number = 0
                            // 微支付
                            let MobilePayAmountSum: number = 0
                            // 小计
                            let RevenueAmountSum: number = 0
                            // 提成金额
                            let amountSum: number = 0
                            // 业主收款
                            let RoyaltyAmountSum: number = 0
                            // 应收租金
                            let GuaranteeFeeSum: number = 0
                            // 应收费用
                            let accountsReceivableSum: number = 0
                            let PaidFeeSum: number = 0
                            let PaidFee_9010Sum: number = 0
                            let PaidFee_9020Sum: number = 0
                            let PaidFee_9030Sum: number = 0
                            let PaidFee_9050Sum: number = 0
                            let PaidFee_9090Sum: number = 0
                            let PaidFee_9099Sum: number = 0
                            // 退补款
                            let RefundSupplementSum: number = 0
                            let ReceivableAmountSum: number = 0
                            let PropertyFeeSum: number = 0
                            let HouseRentSum: number = 0
                            let BreachPenaltySum: number = 0
                            let ElectricityChargeSum: number = 0
                            let WaterChargeSum: number = 0
                            let OtherFeeSum: number = 0


                            exportDetailList.forEach((item: any) => {
                                ReceivableAmountSum += item.ReceivableAmount
                                item.accountsReceivable = item.ReceivableAmount - item.GuaranteeFee
                                item.amount = getMoney(item.RevenueAmount * (item.GuaranteeRatio / 100))
                                accountsReceivableSum += item.accountsReceivable
                                amountSum += item.amount
                                RoyaltyAmountSum += item.RoyaltyAmount
                                MinturnOverSum += item.MinturnOver
                                CashAmountSum += item.CashAmount
                                MobilePayAmountSum += item.MobilePayAmount
                                RevenueAmountSum += item.RevenueAmount
                                GuaranteeFeeSum += item.GuaranteeFee
                                RefundSupplementSum += item.RefundSupplement
                                PaidFeeSum += item.PaidFee
                                PaidFee_9010Sum += item.PaidFee_9010
                                PaidFee_9020Sum += item.PaidFee_9020
                                PaidFee_9030Sum += item.PaidFee_9030
                                PaidFee_9050Sum += item.PaidFee_9050
                                PaidFee_9090Sum += item.PaidFee_9090
                                PaidFee_9099Sum += item.PaidFee_9099
                                PropertyFeeSum += item.PropertyFee
                                HouseRentSum += item.HouseRent
                                BreachPenaltySum += item.BreachPenalty
                                ElectricityChargeSum += item.ElectricityCharge
                                WaterChargeSum += item.WaterCharge
                                OtherFeeSum += item.OtherFee
                            })

                            const sumObj: any = {
                                MinturnOver: MinturnOverSum,
                                CashAmount: CashAmountSum,
                                MobilePayAmount: MobilePayAmountSum,
                                RevenueAmount: RevenueAmountSum,
                                GuaranteeFee: GuaranteeFeeSum,
                                RefundSupplement: RefundSupplementSum,
                                accountsReceivable: accountsReceivableSum,
                                amount: amountSum,
                                RoyaltyAmount: RoyaltyAmountSum,
                                PaidFee: PaidFeeSum,
                                PaidFee_9010: PaidFee_9010Sum,
                                PaidFee_9020: PaidFee_9020Sum,
                                PaidFee_9030: PaidFee_9030Sum,
                                PaidFee_9050: PaidFee_9050Sum,
                                PaidFee_9090: PaidFee_9090Sum,
                                PaidFee_9099: PaidFee_9099Sum,
                                PeriodDesc: '合计',
                                desc: '不含装修期',
                                PropertyFee: PropertyFeeSum,
                                HouseRent: HouseRentSum,
                                BreachPenalty: BreachPenaltySum,
                                ElectricityCharge: ElectricityChargeSum,
                                WaterCharge: WaterChargeSum,
                                OtherFee: OtherFeeSum,
                                ReceivableAmount: ReceivableAmountSum,
                            }
                            setPrintDetailTableData(exportDetailList)
                            // exportDetailList.push(sumObj)

                            setExportDetailTableData(exportDetailList)
                        }

                    }

                    // 如果是第一次进入到页面 再判断是不是退场项目 是的话 就弹出询问的内容问它要不要进行退场结算

                    if (isFirst.current) {
                        isFirst.current = false

                        if (isYear && isShowClosebtn.current && parentRow?.PeriodClosed) {
                            handleCloseSettlement(closeReqTableDataRef.current)
                        } else if (isShowClosebtn.current && parentRow?.CLOSED_DATE && !isYear && parentRow?.PeriodClosed) {
                            confirm({
                                title: '该项目为提前撤场项目，是否进行撤场结算？',
                                icon: <ExclamationCircleOutlined />,
                                async onOk() {
                                    handleCloseSettlement(closeReqTableDataRef.current)
                                },
                                onCancel() {
                                    setShowCloseBtn(true)
                                },
                            });
                        }

                        // if (isShowClosebtn.current && parentRow?.PeriodClosed) {
                        //     // CLOSED_DATE
                        //     // 直接执行 不提示
                        //     if (parentRow?.PeriodClosed)
                        //         handleCloseSettlement(closeReqTableDataRef.current)
                        //     // confirm({
                        //     //     title: '该项目为提前撤场项目，是否进行撤场结算？',
                        //     //     icon: <ExclamationCircleOutlined />,
                        //     //     async onOk() {
                        //     //         console.log('isFirst', isFirst.current);
                        //     //         console.log('closeReqTableDataRef', closeReqTableDataRef.current);

                        //     //         handleCloseSettlement(closeReqTableDataRef.current)
                        //     //     },
                        //     //     onCancel() {
                        //     //         setShowCloseBtn(true)
                        //     //     },
                        //     // });
                        // }

                    }

                    const dataProject = await getProjectDetail(parentRow?.BUSINESSPROJECT_ID)
                    setDataProjectDetail(dataProject)
                    // if (parentRow?.BUSINESSAPPROVAL_ID) {
                    //     handleGetProcessProgress(parentRow?.BUSINESSAPPROVAL_ID)
                    // }
                }}
                expandable={{
                    expandedRowKeys: defaultSelectRow,
                    onExpand: (expanded, record) => {
                        if (expanded) {
                            if (defaultSelectRow && defaultSelectRow.length > 0) {
                                setDefaultSelectRow([...defaultSelectRow, `${record?.ShopRoyalty_Id}-${record?.PeriodIndexStr}-${record?.StartDate}-${record?.EndDate}-${record?.level}`]);
                            } else {
                                setDefaultSelectRow([`${record?.ShopRoyalty_Id}-${record?.PeriodIndexStr}-${record?.StartDate}-${record?.EndDate}-${record?.level}`]);

                            }
                        } else {
                            if (defaultSelectRow && defaultSelectRow.length > 0) {
                                const nowData = defaultSelectRow?.reduce((p, c) => {
                                    if (c !== `${record?.ShopRoyalty_Id}-${record?.PeriodIndexStr}-${record?.StartDate}-${record?.EndDate}-${record?.level}`) {
                                        p.push(c);
                                    }
                                    return p;
                                }, []);
                                setDefaultSelectRow(nowData || []);
                            }
                        }
                    }
                    // defaultExpandAllRows: true,
                    // defaultExpandedRowKeys: defaultSelectRow
                }}
                scroll={{ x: 'max-content' }}
                headerTitle={<span style={{ fontWeight: 600, fontSize: '14px', color: '#1890ff' }}>{`${parentRow?.MERCHANTS_NAME}-${parentRow?.SETTLEMENT_DATE ? `${moment(parentRow?.SETTLEMENT_DATE).format('YYYY')}年度` : ''}结算明细表`}</span>} // 列表表头
                dataSource={reqDetailListDetail}
                pagination={false}
                columnsState={{
                    value: columnsStateMap,
                    onChange: setColumnsStateMap,
                }}
                toolbar={{
                    actions:
                        [
                            <span style={{ visibility: 'hidden' }}>
                                <ReactHTMLTableToExcel
                                    buttonText={'导出excel'}
                                    ref={downloadBtnRef1}
                                    table="table-to-xls-settlementAccount1"
                                    filename={`${parentRow?.MERCHANTS_NAME}-${parentRow?.SETTLEMENT_DATE ? `${moment(parentRow?.SETTLEMENT_DATE).format('YYYY')}年度` : ''}结算明细表`}
                                    sheet="sheet1"
                                />
                            </span>,
                            <span style={{ visibility: 'hidden' }}>
                                <ReactHTMLTableToExcel
                                    buttonText={'导出excel'}
                                    ref={downloadBtnRef}
                                    table="table-to-xls-settlementAccount"
                                    filename={`${parentRow?.MERCHANTS_NAME}-${parentRow?.SETTLEMENT_DATE ? `${moment(parentRow?.SETTLEMENT_DATE).format('YYYY')}年度` : ''}结算表`}
                                    sheet="sheet1"
                                />
                            </span>,
                            <>
                                {
                                    parentRow?.CLOSED_DATE || dataProjectDetail?.CLOSED_DATE ?
                                        <Typography.Text type="secondary" style={{ marginRight: '4px' }}>撤场时间：{parentRow?.CLOSED_DATE || dataProjectDetail?.CLOSED_DATE}</Typography.Text>
                                        : ''
                                }
                                {
                                    showCloseBtn ? <Popconfirm
                                        title={"确认进行撤场结算？"}
                                        onConfirm={() => {
                                            handleCloseSettlement(closeReqTableData)
                                        }}
                                    >
                                        <Button type="primary">撤场结算</Button>
                                    </Popconfirm> : ''
                                }
                            </>,
                            <>
                                <Button type="primary" onClick={() => {
                                    setShowRentReduction(true)
                                }}>租金减免</Button>
                            </>,
                            <>
                                <Button type="primary" onClick={() => {
                                    setShowUpLoadFile(true)
                                }}>查看附件</Button>
                                {/* {
                                    parentRow?.BUSINESSAPPROVAL_ID && (progressDetail?.STAFF_ID === currentUser?.ID) ?
                                         : ''
                                } */}
                            </>,
                            <Button type="primary" style={{ marginRight: '8px' }} onClick={() => {
                                setPayableDrawer(true);
                            }}>应缴费用明细表</Button>,
                            <Button
                                key="new"
                                type="primary"
                                style={{ marginRight: '8px' }}
                                onClick={(e) => {
                                    if (reqDetailListDetail && reqDetailListDetail.length > 0) {
                                        setShowExportTable(true)
                                        exportType = 1
                                        setTimeout(() => {
                                            exportExcel(e)
                                        }, 100)
                                    } else {
                                        message.error('暂无数据可导出！')
                                    }
                                }}
                            >
                                导出结算明细表
                            </Button>,
                            <Button
                                key="new"
                                type="primary"
                                onClick={(e) => {
                                    if (exportData && exportData.length > 0) {
                                        setShowExportTable(true)
                                        exportType = 2
                                        setTimeout(() => {
                                            exportTable(e)
                                        }, 100)
                                    } else {
                                        message.error('暂无数据可导出！')
                                    }
                                }}
                            >
                                导出结算表
                            </Button>,
                            <>
                                {
                                    currentApprovalstate === 9 ?
                                        <>
                                            <Button key="new" onClick={() => {
                                                setIsPrinting(true)
                                                console.log('exportData', exportData);

                                                // window.print();
                                                const printName: string = `${parentRow?.MERCHANTS_NAME}-${parentRow?.SETTLEMENT_DATE ? `${moment(parentRow?.SETTLEMENT_DATE).format('YYYY')}年度` : ''}结算明细表`

                                                const neckList: any = [
                                                    { label: '管理中心', value: otherData?.SPREGIONTYPE_NAME },
                                                    { label: '服务区', value: otherData?.SERVERPART_NAME },
                                                    { label: '经营商户', value: otherData?.MERCHANTS_NAME },
                                                    { label: '门店名称', value: otherData?.SERVERPARTSHOP_NAME },
                                                    { label: '合同期限', value: `${otherData?.PROJECT_STARTDATE ? `${moment(otherData?.PROJECT_STARTDATE).format('YYYY.MM.DD')}` : ''}${otherData?.PROJECT_ENDDATE ? `-${moment(otherData?.PROJECT_ENDDATE).format('YYYY.MM.DD')}` : ''}` },
                                                ]
                                                // 表格的dom元素
                                                // let tabldDom: any = document.getElementsByClassName('detailTable')[0]
                                                // let tableContent: any = tabldDom.getElementsByClassName('ant-table-content')[0].innerHTML

                                                // let tableContent: any = tableRef.current?.innerHTML;
                                                // console.log('tableContent', tableContent);

                                                const styles = Array.from(document.styleSheets) // 获取页面的CSS样式
                                                    .map((sheet) =>
                                                        Array.from(sheet.cssRules).map((rule) => rule.cssText).join('\n')
                                                    )
                                                    .join('\n');

                                                const originalTable: any = document.getElementsByClassName('YearExamineTableTestTable')[0] // 拿到要打印的数据表格
                                                console.log('originalTable', originalTable);

                                                const clonedTable = originalTable.cloneNode(true) as HTMLElement;// 克隆表格元素，包括其子元素
                                                // 修改克隆后的表格样式
                                                clonedTable.style.display = 'block';

                                                // 遍历克隆表格的 <th> 和 <td> 以及它们的所有子元素，设置字体大小为 16px
                                                const setFontSizeRecursively = (element: HTMLElement) => {
                                                    element.style.fontSize = '10px'; // 设置字体大小为 16px
                                                    element.style.padding = '4px'; // 设置字体大小为 16px

                                                    Array.from(element.children).forEach((child) =>
                                                        setFontSizeRecursively(child as HTMLElement)
                                                    );
                                                };

                                                // 遍历克隆表格的 <th> 和 <td> 单元格，并设置字体大小为 16px
                                                const tableCells = clonedTable.querySelectorAll('thead th, tbody td,tfoot td');
                                                tableCells.forEach((cell) => setFontSizeRecursively(cell as HTMLElement));

                                                // 获取克隆后的 HTML 内容
                                                const clonedHTML = clonedTable.getElementsByClassName('ant-table-content')[0].innerHTML;
                                                console.log('clonedHTML', clonedHTML);

                                                const footer: string = `<div style="width:100%;box-sizing: border-box;padding: 12px 12px 12px 20px;">
                                            <div style="width: 100%;display: flex;align-items: center;">
                                                <div style="width: 33%;box-sizing: border-box;padding-left: 5%">
                                                    <span style="font-size: 14px;font-weight: 600;margin-right: 2px;">${new Date(parentRow?.CLOSED_DATE || parentRow?.ENDDATE).getTime() > new Date('2025-04-01 00:00:00').getTime() ? '运营管理子公司' : ''}财务部：</span>
                                                    <span style="font-size: 12px;">${signature?.financeRealName || ''}</span>
                                                </div>
                                                <div style="width: 33%;box-sizing: border-box;padding-left: 5%">
                                                    <span style="font-size: 14px;font-weight: 600;margin-right: 2px;">${new Date(parentRow?.CLOSED_DATE || parentRow?.ENDDATE).getTime() > new Date('2025-04-01 00:00:00').getTime() ? '运营管理子公司运营服务部：' : '经发部'}</span>
                                                    <span style="font-size: 12px;">${signature?.developmentRealName || ''}</span>
                                                </div>
                                                <div style="width: 33%;box-sizing: border-box;padding-left: 5%">
                                                    <span style="font-size: 14px;font-weight: 600;margin-right: 2px;">中心主任：</span>
                                                    <span style="font-size: 12px;">${signature?.directorRealName || ''}</span>
                                                </div>
                                            </div>
                                            <div style="width: 100%;display: flex;align-items: center;flex-wrap: wrap;">
                                                <div style="width: 33%;box-sizing: border-box;padding-left: 5%">
                                                    <span style="font-size: 14px;font-weight: 600;margin-right: 2px;">中心财务：</span>
                                                    <span style="font-size: 12px;">${signature?.centralFinanceRealName || ''}</span>
                                                </div>
                                                <div style="width: 33%;box-sizing: border-box;padding-left: 5%">
                                                    <span style="font-size: 14px;font-weight: 600;margin-right: 2px;">中心经营主管：</span>
                                                    <span style="font-size: 12px;">${signature?.operationsSuperRealName || ''}</span>
                                                </div>
                                                <div style="width: 33%;box-sizing: border-box;padding-left: 5%">
                                                    <span style="font-size: 14px;font-weight: 600;margin-right: 2px;">服务区经理：</span>
                                                    <span style="font-size: 12px;">${signature?.areaManagerRealName || ''}</span>
                                                </div>
                                            </div>
                                            <div style="width: 100%;display: flex;align-items: center;flex-wrap: wrap;}">
                                                <div style="width: 66%;box-sizing: border-box;padding-left: 5%">
                                                    <span style="font-size: 14px;font-weight: 600;margin-right: 2px;">商户确认：</span>
                                                    <span style="font-size: 12px;">${signature?.confirmationRealName || ''}</span>
                                                </div>
                                                <div style="width: 33%;box-sizing: border-box;padding-left: 5%">
                                                    <span style="font-size: 14px;font-weight: 600;margin-right: 2px;">发起人：</span>
                                                    <span style="font-size: 12px;">${signature?.developManagerRealName || ''}</span>
                                                </div>
                                            </div>
                                        </div>`

                                                handleNewPrint(printName, `${parentRow?.BUSINESSPROJECT_NAME}结算表(年度)`, neckList, styles, clonedHTML, footer)

                                                setIsPrinting(false)
                                            }}>打印结算表</Button>

                                            <Button style={{ marginLeft: '8px' }} key="new" onClick={() => {
                                                setIsPrinting(true)
                                                console.log('exportData', exportData);
                                                console.log('parentRow', parentRow);


                                                // window.print();
                                                const printName: string = `${parentRow?.MERCHANTS_NAME}-${parentRow?.SETTLEMENT_DATE ? `${moment(parentRow?.SETTLEMENT_DATE).format('YYYY')}年度` : ''}结算明细表`

                                                const neckList: any = [
                                                    { label: '管理中心', value: otherData?.SPREGIONTYPE_NAME },
                                                    { label: '服务区', value: otherData?.SERVERPART_NAME },
                                                    { label: '经营商户', value: otherData?.MERCHANTS_NAME },
                                                    { label: '门店名称', value: otherData?.SERVERPARTSHOP_NAME },
                                                    { label: '合同期限', value: `${otherData?.PROJECT_STARTDATE ? `${moment(otherData?.PROJECT_STARTDATE).format('YYYY.MM.DD')}` : ''}${otherData?.PROJECT_ENDDATE ? `-${moment(otherData?.PROJECT_ENDDATE).format('YYYY.MM.DD')}` : ''}` },
                                                ]
                                                // 表格的dom元素
                                                // let tabldDom: any = document.getElementsByClassName('detailTable')[0]
                                                // let tableContent: any = tabldDom.getElementsByClassName('ant-table-content')[0].innerHTML

                                                // let tableContent: any = tableRef.current?.innerHTML;
                                                // console.log('tableContent', tableContent);

                                                const styles = Array.from(document.styleSheets) // 获取页面的CSS样式
                                                    .map((sheet) =>
                                                        Array.from(sheet.cssRules).map((rule) => rule.cssText).join('\n')
                                                    )
                                                    .join('\n');

                                                const originalTable: any = document.getElementsByClassName('YearExamineDetailTableTestTable')[0] // 拿到要打印的数据表格
                                                console.log('originalTable', originalTable);

                                                const clonedTable = originalTable.cloneNode(true) as HTMLElement;// 克隆表格元素，包括其子元素
                                                // 修改克隆后的表格样式
                                                clonedTable.style.display = 'block';

                                                // 遍历克隆表格的 <th> 和 <td> 以及它们的所有子元素，设置字体大小为 16px
                                                const setFontSizeRecursively = (element: HTMLElement) => {
                                                    element.style.fontSize = '9px'; // 设置字体大小为 16px
                                                    element.style.padding = '4px'; // 设置字体大小为 16px

                                                    Array.from(element.children).forEach((child) =>
                                                        setFontSizeRecursively(child as HTMLElement)
                                                    );
                                                };

                                                // 遍历克隆表格的 <th> 和 <td> 单元格，并设置字体大小为 16px
                                                const tableCells = clonedTable.querySelectorAll('thead th, tbody td,tfoot td');
                                                tableCells.forEach((cell) => setFontSizeRecursively(cell as HTMLElement));

                                                // 获取克隆后的 HTML 内容
                                                const clonedHTML = clonedTable.getElementsByClassName('ant-table-content')[0].innerHTML;
                                                console.log('clonedHTML', clonedHTML);

                                                const footer: string = `<div style="width:100%;box-sizing: border-box;padding: 12px 12px 12px 20px;">
                                                    <div style="width: 100%;display: flex;align-items: center;">
                                                    <div style="width: 33%;box-sizing: border-box;padding-left: 5%">
                                                        <span style="font-size: 14px;font-weight: 600;margin-right: 2px;"> ${new Date(parentRow?.CLOSED_DATE || parentRow?.ENDDATE).getTime() > new Date('2025-04-01 00:00:00').getTime() ? '运营管理子公司' : ''}财务部：</span>
                                                        <span style="font-size: 12px;">${signature?.financeRealName || ''}</span>
                                                    </div>
                                                    <div style="width: 33%;box-sizing: border-box;padding-left: 5%">
                                                        <span style="font-size: 14px;font-weight: 600;margin-right: 2px;">${new Date(parentRow?.CLOSED_DATE || parentRow?.ENDDATE).getTime() > new Date('2025-04-01 00:00:00').getTime() ? '运营管理子公司运营服务部：' : '经发部：'}</span>
                                                        <span style="font-size: 12px;">${signature?.developmentRealName || ''}</span>
                                                    </div>
                                                    <div style="width: 33%;box-sizing: border-box;padding-left: 5%">
                                                        <span style="font-size: 14px;font-weight: 600;margin-right: 2px;">中心主任：</span>
                                                        <span style="font-size: 12px;">${signature?.directorRealName || ''}</span>
                                                    </div>
                                                    </div>
                                                    <div style="width: 100%;display: flex;align-items: center;flex-wrap: wrap;">
                                                    <div style="width: 33%;box-sizing: border-box;padding-left: 5%">
                                                        <span style="font-size: 14px;font-weight: 600;margin-right: 2px;">中心财务：</span>
                                                        <span style="font-size: 12px;">${signature?.centralFinanceRealName || ''}</span>
                                                    </div>
                                                    <div style="width: 33%;box-sizing: border-box;padding-left: 5%">
                                                        <span style="font-size: 14px;font-weight: 600;margin-right: 2px;">中心经营主管：</span>
                                                        <span style="font-size: 12px;">${signature?.operationsSuperRealName || ''}</span>
                                                    </div>
                                                    <div style="width: 33%;box-sizing: border-box;padding-left: 5%">
                                                        <span style="font-size: 14px;font-weight: 600;margin-right: 2px;">服务区经理：</span>
                                                        <span style="font-size: 12px;">${signature?.areaManagerRealName || ''}</span>
                                                    </div>
                                                    </div>
                                                    <div style="width: 100%;display: flex;align-items: center;flex-wrap: wrap;}">
                                                    <div style="width: 66%;box-sizing: border-box;padding-left: 5%">
                                                        <span style="font-size: 14px;font-weight: 600;margin-right: 2px;">商户确认：</span>
                                                        <span style="font-size: 12px;">${signature?.confirmationRealName || ''}</span>
                                                    </div>
                                                    <div style="width: 33%;box-sizing: border-box;padding-left: 5%">
                                                        <span style="font-size: 14px;font-weight: 600;margin-right: 2px;">发起人：</span>
                                                        <span style="font-size: 12px;">${signature?.developManagerRealName || ''}</span>
                                                    </div>
                                                    </div>
                                                    </div>`

                                                handleNewPrint(printName, `${parentRow?.BUSINESSPROJECT_NAME}结算明细表(年度)`, neckList, styles, clonedHTML, footer)

                                                setIsPrinting(false)
                                            }}>
                                                打印结算明细表
                                            </Button>
                                        </>
                                        : ''
                                }
                            </>


                        ]
                }}
                rowSelection={{
                    type: 'checkbox',
                    ...modalRowSelection,
                }}
            >
            </ProTable>


            {/* 判断当期项目 是不是最后一期  是最后一期的话 就显示 历史期的数据 */}
            {/* <HistoricalProjects parentRow={parentRow} /> */}
            {
                parentRow?.PROJECT_ENDDATE && parentRow?.ENDDATE && moment(parentRow?.PROJECT_ENDDATE).format('YYYY-MM-DD') === moment(parentRow?.ENDDATE).format('YYYY-MM-DD') && parentRow?.BUSINESSAPPROVAL_ID > 0 ?
                    <HistoricalProjects parentRow={parentRow} pageType={'search'} /> : ""
            }



            {/* 导出结算表 */}
            <PrintContent pageName={'YearExamineTable'} exportColumns={exportColumns} exportData={exportData} exportSumRow={exportSumRow} type={'year'} />

            {/* 导出结算明细表 */}
            <PrintContent pageName={'YearExamineDetailTable'} exportColumns={exportColumns} exportData={exportData2} exportSumRow={exportSumRow} type={'year'} />




            {/* <ProTable
                style={{ display: "none" }}
                className="YearExamineDetailTableTestTable"
                columns={exportColumns}
                dataSource={exportData}
                pagination={false}
                bordered
                expandable={{
                    defaultExpandAllRows: true
                }}
                summary={() => {
                    return <>
                        <tr>
                            <td colSpan={2} align={'center'}>{exportSumRow?.PeriodIndexStr}</td>
                            <td>{exportSumRow?.MinturnOver ? numeral(exportSumRow?.MinturnOver).format('0,0') : ''}</td>
                            <td></td>
                            <td>{exportSumRow?.CashAmount ? numeral(exportSumRow?.CashAmount).format('0,0.00') : ''}</td>
                            <td>{exportSumRow?.MobilePayAmount ? numeral(exportSumRow?.MobilePayAmount).format('0,0.00') : ''}</td>
                            <td>{exportSumRow?.RevenueAmount ? numeral(exportSumRow?.RevenueAmount).format('0,0.00') : ''}</td>
                            <td>{exportSumRow?.amount ? numeral(exportSumRow?.amount).format('0,0.00') : ''}</td>
                            <td>{exportSumRow?.RoyaltyAmount ? numeral(exportSumRow?.RoyaltyAmount).format('0,0.00') : ''}</td>
                            <td>{exportSumRow?.GuaranteeFee ? numeral(exportSumRow?.GuaranteeFee).format('0,0.00') : ''}</td>
                            <td>{exportSumRow?.accountsReceivable ? numeral(exportSumRow?.accountsReceivable).format('0,0.00') : ''}</td>
                            <td>{exportSumRow?.PaidFee ? numeral(exportSumRow?.PaidFee).format('0,0.00') : ''}</td>
                            <td>{exportSumRow?.PaidFee_9010 ? numeral(exportSumRow?.PaidFee_9010).format('0,0.00') : ''}</td>
                            <td>{exportSumRow?.PaidFee_9020 ? numeral(exportSumRow?.PaidFee_9020).format('0,0.00') : ''}</td>
                            <td>{exportSumRow?.PaidFee_9030 ? numeral(exportSumRow?.PaidFee_9030).format('0,0.00') : ''}</td>
                            <td>{exportSumRow?.PaidFee_9050 ? numeral(exportSumRow?.PaidFee_9050).format('0,0.00') : ''}</td>
                            <td>{exportSumRow?.PaidFee_9090 ? numeral(exportSumRow?.PaidFee_9090).format('0,0.00') : ''}</td>
                            <td>{exportSumRow?.PaidFee_9099 ? numeral(exportSumRow?.PaidFee_9099).format('0,0.00') : ''}</td>
                            <td>{exportSumRow?.RefundSupplement ? numeral(exportSumRow?.RefundSupplement).format('0,0.00') : ''}</td>
                            <td>{exportSumRow?.desc}</td>
                        </tr>
                        {/* <tr></tr>
                        <tr>
                            <td colSpan={1} align={'right'}>{'财务部：'}</td>
                            <td colSpan={6}>{signature?.financeName || ''}</td>
                            <td colSpan={1} align={'right'}>{'经发部：'}</td>
                            <td colSpan={6}>{signature?.developmentName || ''}</td>
                        </tr>
                        <tr></tr>
                        <tr>
                            <td colSpan={1} align={'right'}>{'中心主任：'}</td>
                            <td colSpan={2}>{signature?.directorName || ''}</td>
                            <td colSpan={1} align={'right'}>{'中心财务：'}</td>
                            <td colSpan={2}>{signature?.centralFinanceName || ''}</td>
                            <td colSpan={1} align={'right'}>{'中心经营主管：'}</td>
                            <td colSpan={2}>{signature?.operationsSuperName || ''}</td>
                            <td colSpan={1} align={'right'}>{'服务区经理：'}</td>
                            <td colSpan={2}>{signature?.areaManagerName || ''}</td>
                            <td colSpan={1} align={'right'}>{'商户确认：'}</td>
                            <td colSpan={2}>{signature?.confirmationName || ''}</td>
                            <td colSpan={1} align={'right'}>{'发起人：'}</td>
                            <td colSpan={2}>{signature?.developManagerName || ''}</td>
                        </tr> */}
            {/* </>
 
                }}
/> */}

            {/* 应缴费用明细表的抽屉 */}
            <Drawer
                width="80%"
                visible={payableDrawer} // 抽屉弹框是否显示状态
                onClose={() => { // 关闭抽屉 则在清空选中行数据 并 设置抽屉状态为关闭
                    setPayableDrawer(false);
                }}
                bodyStyle={{ backgroundColor: "#f9f9f9", padding: 0 }}
                closable={false}
                destroyOnClose
            >
                <MonthSettlement onRef={MonthSettlementRef} detail={{
                    ...parentRow,
                }} showState={true} haveSum={true} noOption={true} parentTableData={reqDetailListDetail} />
                {/* ...payableParams */}

            </Drawer>

            {/* 点击期限显示的分润报表 */}
            <Drawer
                width="80%"
                className="project-drawer"
                visible={showDetail} // 抽屉弹框是否显示状态
                onClose={() => { // 关闭抽屉 则在清空选中行数据 并 设置抽屉状态为关闭
                    setCurrentDetailRow(undefined);
                    setShowDetail(false);
                }}
                bodyStyle={{ backgroundColor: "#f9f9f9", padding: 0 }}
                closable={false}
            >
                {/* 抽屉打开时 加载项目详情组件 */}
                {showDetail && <RevenueList BusinessProjectId={parentRow?.BUSINESSPROJECT_ID} propsBP={otherData}
                    propsRC={tableAllData} isShowDetail={showDetail}
                    ShopRoyaltyId={parentRow?.SHOPROYALTY_ID ? parentRow?.SHOPROYALTY_ID : 0}
                    ShopIds={parentRow?.SERVERPARTSHOP_ID ? parentRow?.SERVERPARTSHOP_ID : ''}
                    StartDate={moment(currentDetailRow?.StartDate).format('YYYY-MM-DD')}
                    EndDate={moment(currentDetailRow?.EndDate).format('YYYY-MM-DD')} type={'monthSettlement'}></RevenueList>}
            </Drawer>
            {/* 上传附件的悬浮框 */}
            {
                showImgList && showImgList.length > 0 && <div style={{ display: 'none' }}>

                    <Image.PreviewGroup

                        preview={{
                            visible: imagePreviewVisible,
                            onVisibleChange: vis => {
                                setImagePreviewVisible(vis)
                            },
                            current: previewIndex
                        }}>
                        {
                            showImgList.map((n) =>
                                <Image src={n.url} key={n.url} />
                            )
                        }
                    </Image.PreviewGroup>


                </div>
            }
            <Modal
                width={500}
                open={showUpLoadFile}
                title={'上传附件'}
                onOk={() => {

                }}
                footer={false}
                destroyOnClose
                onCancel={() => {
                    setShowUpLoadFile(false)
                }}
            >
                <ProForm
                    formRef={uploadFormDescRef}
                    submitter={false}
                    request={async () => {
                        await handleGetFile()
                        return {}
                    }}
                >
                    <Row gutter={4}>
                        <Col span={20}>
                            <ProFormUploadButton
                                label={"上传年度结算单"}
                                name="files"
                                fileList={fileList}
                                fieldProps={{
                                    onPreview: async (file: any) => {
                                        console.log('file', file);
                                        if (file.url.indexOf('.png') === -1 && file.url.indexOf('.jpg') === -1 && file.url.indexOf('.jpeg') === -1 && file.url.indexOf('.PNH') === -1 && file.url.indexOf('.JPG') === -1 && file.url.indexOf('.JPEG') === -1) {
                                            window.open(file.url);
                                        } else {

                                            if (fileList && fileList.length > 0) {
                                                const showFileList: any = []
                                                fileList.forEach((item: any) => {
                                                    if (item.url.indexOf('.png') !== -1 || item.url.indexOf('.jpg') !== -1 || item.url.indexOf('.jpeg') !== -1 || item.url.indexOf('.PNG') !== -1 || item.url.indexOf('.JPG') !== -1 || item.url.indexOf('.JPEG') !== -1) {
                                                        showFileList.push(item)
                                                    }
                                                })
                                                console.log('showFileList', showFileList);
                                                let previewIndex: number = 0
                                                if (showFileList && showFileList.length > 0) {
                                                    showFileList.forEach((item: any, index: number) => {
                                                        if (file.url === item.url) {
                                                            previewIndex = index
                                                        }
                                                    })
                                                }
                                                setPreviewIndex(previewIndex)

                                                setShowImgList(showFileList)
                                                setImagePreviewVisible(true)
                                            }

                                        }
                                    },
                                    onChange: async (info: any) => {
                                        console.log('info', info);
                                        console.log('fileList', fileList);


                                        // 检查文件类型是否为图片
                                        if (info.file.type && !info.file.type.startsWith("image/")) {
                                            message.error("只能上传图片文件！");
                                            return; // 如果不是图片，直接返回，避免继续执行
                                        }

                                        if (info.file.status === 'removed') {
                                            // 如果在待上传列表中找到，则说明当前图片没有上传服务器，可直接删除
                                            const index = fileList.findIndex(n => n.uid === info.file.uid);

                                            // if (info.file?.status === "removed" && ) {
                                            //     const newFileList = fileList.slice();
                                            //     newFileList.splice(index, 1);
                                            //     setFileList(newFileList)
                                            //     return
                                            // }
                                            confirm({
                                                title: '确认删除该文件吗？',
                                                icon: <ExclamationCircleOutlined />,
                                                async onOk() {
                                                    const deleteLoading = message.loading('正在删除...')
                                                    const success = await deletePicture(info.file?.deletepath, info.file?.uid, '', '3000')
                                                    deleteLoading()

                                                    if (success) {
                                                        const files = [...fileList]
                                                        files.splice(index, 1)
                                                        setFileList(files)
                                                    }
                                                    else {
                                                        message.error("删除失败")
                                                    }
                                                },
                                                onCancel() {
                                                },
                                            });
                                        } else {
                                            if (info.fileList && info.fileList.length > 0) {

                                                const formData = new FormData();
                                                info.fileList.forEach((item: any) => {
                                                    if (item.status !== "done") {
                                                        console.log('item', item);
                                                        formData.append('files[]', item.originFileObj);
                                                        // formData.append('ImageName', item.name);
                                                    }
                                                })
                                                formData.append('TableType', '1130');
                                                formData.append('TableId', parentRow?.BUSINESSAPPROVAL_ID);

                                                const success = await uploadPicture(formData)
                                                console.log('success', success);
                                                if (success) {
                                                    message.success("上传成功！")
                                                }
                                                await handleGetFile()
                                            }
                                        }
                                    }
                                }}
                                disabled={isChangeFile ? false : !((parentRow?.BUSINESSAPPROVAL_ID && progressDetail?.STAFF_ID === currentUser?.ID && currentApprovalstate !== 9))}
                                buttonProps={{
                                    style: { display: parentRow?.BUSINESSAPPROVAL_ID && (progressDetail?.STAFF_ID === currentUser?.ID) && currentApprovalstate !== 9 ? '' : 'none' }
                                }}
                                title={"上传年度结算单"}
                            />
                        </Col>
                        <Col span={4}>
                            <div style={{ width: '100%', height: '100%', boxSizing: 'border-box', paddingTop: '52px' }}>
                                {
                                    fileList && fileList.length > 0 ?
                                        fileList.map((item: any) => {
                                            return <div style={{ height: '66px', display: 'flex', alignItems: 'center' }}>
                                                {
                                                    item.IsImg ?
                                                        <Button type={'primary'} onClick={() => {
                                                            console.log('item', item);
                                                            handlePrintImg(item.url)
                                                        }}>打印</Button> : ''
                                                }
                                            </div>
                                        }) : ''
                                }
                            </div>
                        </Col>
                    </Row>

                    {
                        fileList && fileList.length > 0 ?
                            '' : <div style={{ color: '#00000073' }}>
                                未有上传附件，需发起人进行附件上传，请联系<span style={{ color: '#1890ff', fontWeight: 600 }}>{progressDetail?.STAFF_NAME}</span>上传附件！
                            </div>
                    }

                </ProForm>
            </Modal>


            {/* 租金减免 */}
            <Modal
                width={500}
                open={showRentReduction}
                title={'租金减免'}
                onOk={() => {
                    rentReductionFormRef.current?.validateFields().then(async (res: any) => {
                        setTableLoading(true)
                        console.log('res', res);
                        setRentReductionLoading(true)

                        const dateRanges: any = (res.dateRanges || [])
                            .map((item) => item?.range)
                            .filter(Boolean);
                        console.log('最终未营业日期数组', dateRanges);

                        const dateList: any = []
                        if (dateRanges && dateRanges.length > 0) {
                            dateRanges.forEach((item: any) => {
                                dateList.push({
                                    StartDate: moment(item[0]._d).format('YYYY-MM-DD'),
                                    EndDate: moment(item[1]._d).format('YYYY-MM-DD'),
                                    ReductionType: 0
                                })
                            })
                        }


                        const obj: any = closeReqTableDataRef.current.List[0]
                        const req = {
                            ...obj,
                            ReductionList: dateList,
                            ReductionAmount: res.ReductionAmount
                        }
                        console.log('req', req);

                        const data = await handleRebuildReductionPeriod(req)
                        setTableLoading(false)
                        if (data.Result_Code === 100) {
                            message.success(data.Result_Desc)
                            setShowRentReduction(false)
                            setRentReductionLoading(false)
                            const result: any = wrapTreeNode([data.Result_Data])
                            result[0].PeriodDesc = '合计'
                            console.log('resresresres31312', result);
                            const resultList: any = []
                            const newDefaultSelectRow: string[] = []
                            const selectRow: string[] = []
                            if (result && result.length > 0) {
                                result.forEach((item: any) => {
                                    item.level = 0
                                    item.noSelect = true
                                    resultList.push(item)
                                    newDefaultSelectRow.push(`${item?.ShopRoyalty_Id}-${item?.PeriodIndexStr}-${item?.StartDate}-${item?.EndDate}-${item?.level}`)

                                    if (item.children && item.children.length > 0) {
                                        item.children.forEach((subItem: any) => {
                                            subItem.level = 1
                                            selectRow.push(`${subItem?.ShopRoyalty_Id}-${subItem?.PeriodIndexStr}-${subItem?.StartDate}-${subItem?.EndDate}-${subItem?.level}`)
                                            resultList.push(subItem)
                                        })
                                    }
                                })
                            }
                            console.log('resultList321321', resultList);
                            console.log('parentRow', parentRow);
                            console.log('defaultSelectRow', defaultSelectRow);
                            console.log('newDefaultSelectRow', newDefaultSelectRow);

                            setDefaultSelectRow([...newDefaultSelectRow]);
                            setSelectRowKey([...selectRow])
                            setReqDetailListDetail(result)
                            setSelectDetailList(result)
                            // actionRef.current?.reload()
                        } else {
                            console.log('datadsadasd', data);
                            message.error(data.Result_Desc)
                        }
                    })
                }}
                confirmLoading={rentReductionLoading}
                destroyOnClose
                onCancel={() => {
                    setShowRentReduction(false)
                    setRentReductionLoading(false)
                }}
            >
                <ProForm
                    formRef={rentReductionFormRef}
                    submitter={false}
                >
                    <Row>
                        <Col span={24}>
                            <ProFormDigit
                                label={"减免金额"}
                                name={"ReductionAmount"}
                                rules={[{
                                    required: true,
                                    message: "请输入减免金额！"
                                }]}
                            />
                        </Col>
                        <Col span={24}>
                            <ProFormList
                                name="dateRanges" // 存储所有时间范围的数组字段名
                                label="未营业日期"
                                initialValue={[{ range: [] }]} // 确保默认有一条空记录
                                creatorButtonProps={{
                                    position: 'bottom',
                                    creatorButtonText: '添加未营业日期',
                                    icon: <PlusOutlined rev={undefined} />,
                                }}
                                copyIconProps={false} // 禁用复制按钮
                                deleteIconProps={false}
                                actionGuard={{
                                    beforeRemoveRow: async (index) => {
                                        if (index === 0) {
                                            return false; // 禁止删除第一条
                                        }
                                        return true;
                                    },
                                }}
                            >
                                {(field, index, action) => (
                                    <Space key={field.key} align="baseline">
                                        {/* 时间范围选择器 */}
                                        <ProFormDateRangePicker
                                            name={'range'}
                                            rules={[{ required: true, message: "请选择未营业日期！" }]}
                                            placeholder={['开始日期', '结束日期']}
                                            transform={(value) => ({ range: value })}
                                        />

                                        {/* 删除按钮（只有非第一条时才显示） */}
                                        {index !== 0 && (  // 修改为 index !== 0 更符合语义
                                            <MinusCircleOutlined
                                                onClick={() => action.remove(index)}
                                                style={{ color: 'red', marginLeft: 8 }} rev={undefined} />
                                        )}
                                    </Space>
                                )}
                            </ProFormList>
                            {/* <ProFormDateRangePicker
                                label={"未营业日期"}
                                name={"staticDate"}
                                rules={[{
                                    required: true,
                                    message: "请选择未营业日期！"
                                }]}
                            /> */}
                        </Col>
                    </Row>
                </ProForm>
            </Modal>
        </div >
    )
}

export default connect(({ user, }: ConnectState) => ({
    currentUser: user.currentUser,
}))(YearExamineDetailTable);
