import React, { useEffect, useRef, useState } from "react";
import type { CurrentUser } from "umi";
import { connect } from "umi";
import type { ConnectState } from "@/models/connect";
import {
  handleCorrectDailyEndaccount,
  handleGetApplyMonthAccountProinst, handleGetAPPROVALROUTEDetail,
  handleGetBUSINESSPROJECTSPLITList, handleGetProjectPeriodIncome, handleGetRevenueReportByBIZPSPLITMONTH,
  handleGetRevenueReportByDate, handleGetRoyaltyRecordList, handleGetYSSellMasterList
} from "@/pages/reports/revenueConfirmation/components/service";
import { handleNewPrint, handlePrintImg, wrapTreeNode } from "@/utils/format";
import type { ActionType, ProColumns } from "@ant-design/pro-table";
import ProTable from "@ant-design/pro-table";
import type { ProFormInstance } from "@ant-design/pro-form";
import { ProFormUploadButton } from "@ant-design/pro-form";
import moment from "moment";
import { getFieldEnum, getMoney, handleCallLogs, unique } from "@/services/options";
import * as numeral from "numeral";
import './compareList.less'
import { Button, Col, Descriptions, Drawer, message, Modal, Popconfirm, Row, Select, Statistic, Tooltip, Typography, Image } from "antd";
import { handleAgain } from "@/pages/BussinessProject/service";
import { getProjectDetail } from "@/pages/reports/accountTable/service";
import session from "@/utils/session";
import ProDescriptions from "@ant-design/pro-descriptions";
import ProForm, { ProFormDigit, ProFormText, ProFormTextArea, ProFormSelect } from "@ant-design/pro-form";
import addIcon from '@/assets/ai/add.png'
import reduce from '@/assets/ai/reduce.png'
import type {
  RevenueStatisticsModel,
  RevenueStatisticsParams
} from "@/pages/reports/BusinessAnalysis/RevenueReport/data";
import { getRevenueReport } from "@/pages/reports/BusinessAnalysis/RevenueReport/service";
import ReactHTMLTableToExcel from "react-html-table-to-excel";
import ReactToPrint from "react-to-print";
import { printOutBody } from "@/utils/utils";
import DailyRevenue from "@/pages/reports/revenueConfirmation/components/dailyRevenue";
import ReviewProcess from "@/pages/reports/revenueConfirmation/components/ReviewProcess";
import Draggable from "react-draggable";
import RevenueList from "@/pages/BussinessProject/components/RevenueList";
import { handleGetBIZPSPLITMONTHDetail, handleGetBUSINESSAPPROVALDetail } from "@/pages/examine/monthSettlement/service";
import './styleTop.less'
import MonthDaily from "./monthDaily";
import RevenueSecondList from "./RevenueSecondList";
import { handleGetGetBUSINESSAPPROVALDetail, handleGetProjectAccountList, handleGetProjectPeriodAccount, handleGetTableMonthlyReconciliation, handleGetTableRevenueRecognition } from "../../ShopExpenseDetail/service";
import { handleGetAPPROVALROUTEList } from "@/pages/Setting/serviceConfig/service";
import { handleSolidProjectRevenue } from "../../revenueDifference/service";
import MonthSettlement from "./monthSettlement";
import MonthTopTable from "./monthTopTable";
import { deleteAHYDPicture, deletePicture, uploadAHYDPicture, uploadPicture } from "@/services/picture";
import { ExclamationCircleOutlined } from "@ant-design/icons";
import { handleGetPictureList, handleGetProjectExpenseList } from "../../settlementAccount/service";
import PrintContent from "../../settlementAccount/component/printContent";

const { Text } = Typography;

const amountDom = (value: any) => {
  const stringValue = `${value}`
  const [intValue, floatValue] = stringValue.split(".")
  return floatValue ?
    <><Text type="warning" style={{
      fontSize: 36, lineHeight: 1,
      fontFamily: "Bahnschrift Regular"
    }}>{numeral(intValue || 0).format("0,0")}</Text><Text type="warning" style={{
      fontSize: 18,
      fontFamily: "Bahnschrift Regular"
    }}>.{floatValue}</Text>
      <Text type="warning" style={{ fontSize: 14 }}>(万元)</Text></>
    :
    <><Text type="warning" style={{
      fontSize: 36, lineHeight: 1,
      fontFamily: "Bahnschrift Regular"
    }}>{intValue}</Text><Text type="warning" style={{ fontSize: 14 }}>(万元)</Text></>
}


// come 标识来自哪个页面
const compareList: React.FC<{
  currentUser: CurrentUser, compareCurrent: any, showCompareDrawer: any, monthTime: any, handleGetRefreshTableData?: any,
  onlyRead?: boolean, fatherActionRef?: any, setShowCompareDrawer?: any, handleGetNewMonth?: any, type?: string, come?: string, comeColumns?: any
  showTopTable?: boolean, isChangeFile?: any
}> = (props) => {
  const { currentUser } = props
  const { compareCurrent } = props
  const { showCompareDrawer } = props
  const { monthTime } = props
  const { handleGetRefreshTableData } = props
  const { onlyRead } = props
  const { fatherActionRef } = props
  const { setShowCompareDrawer } = props
  const { showTopTable } = props
  const { handleGetNewMonth } = props
  const { type } = props
  const { come } = props
  const { comeColumns } = props
  const { isChangeFile } = props // 判断是否可以删除附件
  const actionRef = useRef<ActionType>();
  const formRef = useRef<ProFormInstance>();
  const formDescRef = useRef<ProFormInstance>();
  const editFormRef = useRef<ProFormInstance>();
  const MonthSettlementRef = useRef<any>()
  const uploadFormDescRef = useRef<any>();
  const { confirm } = Modal;
  // 当天的详情流水抽屉
  const [dailyDetailSales, setDailyDetailSales] = useState<boolean>(false)
  // 表格加载效果
  const [compareTableLoading, setCompareTableLoading] = useState<boolean>(false)
  const [tableSecondLoading, setTableSecondLoading] = useState<boolean>(false)
  // 点击查看每日流水的行数据
  const [selectRow, setSelectRow] = useState<any>()
  // 是否显示差异数据 不显示就显示全部数据
  const [showBigTableDifference, setShowBigTableDifference] = useState<boolean>(true)
  // 外面表格显示的数据
  const [tableData, setTableData] = useState<any>()
  // 外面表格显示的全部数据
  const [tableAllData, setTableAllData] = useState<any>()
  // 外面表格显示的差异的数据
  const [tableDifferenceData, setTableDifferenceData] = useState<any>()
  // 判断是否点击了重新生成
  const handleClickAgain = useRef<boolean>(false)
  // 判断是否有差异
  const [handleHaveDifference, setHandleHaveDifference] = useState<boolean>(true)
  // 抽屉里面是否显示差异数据的判断
  const [showTableDifference, setShowTableDifference] = useState<boolean>(true)
  // 抽表格左边的全部数据
  const [drawerLeftTableAllData, setDrawerLeftTableAllData] = useState<any>()
  // 抽表格右边的全部数据
  const [drawerRightTableAllData, setDrawerRightTableAllData] = useState<any>()
  // 抽屉表格左边的显示数据
  const [leftTableData, setLeftTableData] = useState<any>()
  // 抽屉表格右边的显示数据
  const [rightTableData, setRightTableData] = useState<any>()
  // 抽屉表格左边的差异数据
  const [leftDifferenceTableData, setLeftDifferenceTableData] = useState<any>()
  // 抽屉表格右边的差异数据
  const [rightDifferenceTableData, setRightDifferenceTableData] = useState<any>()
  // 提交结算悬浮框
  const [settlementModal, setSettlementModal] = useState<boolean>(false)
  // 校验后的数据
  const [secondTableData, setSecondTable] = useState<any>()
  // 判断上月是否已经审结了 能不能点击审结
  const [lastMonthIsOver, setLastMonthIsOver] = useState<boolean>(false)
  // 判断最近的审结月份
  const [LastSettlementMonth, setLastSettlementMonth] = useState<string>()
  const [columnsStateMap, setColumnsStateMap] = useState<any>({
    SELLMASTER_COUNT: { show: false },
    SELLMASTER_OFFPRICE: { show: false },
    SHOPNAME: { show: false },
    MACHINECODE: { show: false },
    SELLWORKER_NAME: { show: false },
    SELLMASTER_CODE: { show: false },
  })
  const [columnsStateMapSecond, setColumnsStateMapSecond] = useState<any>({
    MACHINECODE: { show: false },
    SELLMASTER_STATETEXT: { show: false },
    SELLWORKER_NAME: { show: false },
  })
  const [recordColumnsStateMap, setRecordColumnsStateMap] = useState<any>({
    Machine_Code: { show: false },
    Account_Price: { show: false },
    SubRoyalty_Price: { show: false },
    Ticket_Fee: { show: false },
    Royalty_Price: { show: false },
    Royalty_Rate: { show: false },
  })
  // 隐藏日结校验
  const [hiddenCorrectAmount, setHiddenCorrectAmount] = useState<boolean>(true)
  // 差额类型
  const [DifferenceType, setDifferenceType] = useState<number>(0)
  // 移动支付差额
  const [mobilePayCorrectNumber, setMobilePayCorrectNumber] = useState<any>()
  // 现金支付差额
  const [cashPayCorrectNumber, setCashPayCorrectNumber] = useState<any>()
  const SETTLEMENT_MODESObj = session.get('SETTLEMENT_MODESObj')
  // 判断是否点了重新校验 且调成功了
  const [clickCalibration, setClickCalibration] = useState<boolean>(false)
  // 第一张表格的数据
  const [firstTableData, setFirstTableData] = useState<any>()
  // 初始的结算数据
  const [defaultFirstTableData, setDefaultFirstTableData] = useState<any>()
  // 显示重新校验按钮
  const [showRecalibration, setShowRecalibration] = useState<boolean>(false)
  // 灰色小字的数据
  const [noticeRowData, setNoticeRowData] = useState<any>()
  // 点击日期 显示的抽屉
  const [dailyRevenueDetail, setDailyRevenueDetail] = useState<boolean>(false)
  // 给每日抽屉的行值
  const [dailyCurrentRow, setDailyCurrentRow] = useState<any>()
  const [disabled, setDraggleDisabled] = useState<boolean>() // 是否拖动
  // 拖动开始
  const [bounds, setBounds] = useState<{ left: number, right: number, top: number, bottom: number }>() // 移动的位置
  const draggleRef = React.createRef<any>()
  // 是否显示左侧文字
  const [showLeftText, setShowLeftText] = useState<boolean>(false)
  // 该项目的审核状态(最近的审核时间 审核状态...)
  const [settlementObj, setSettlementObj] = useState<any>()
  // 表格加载显示的问题
  const [loadingText, setLoadingText] = useState<string>('')
  // 月份的id
  const [monethId, setMonthId] = useState<any>()
  // 显示附件的抽屉
  const [showSearchFile, setShowSearchFile] = useState<boolean>(false)
  // 当前是否为指定重新申请
  const [currentREJECTTYPE, setCurrentREJECT_TYPE] = useState<boolean>(false)
  // 指定的下一个状态
  const [nextState, setNextState] = useState<any>()
  // 预览图片
  const [imagePreviewVisible, setImagePreviewVisible] = useState<boolean>(false)
  // 预览的索引
  const [previewIndex, setPreviewIndex] = useState<number>(0)
  // 预览的附件
  const [showImgList, setShowImgList] = useState<any>()
  // 重新申请加载效果
  const [reapply, setReapply] = useState<boolean>(false)


  // 预览上传后的图片
  const handlePreview = async (file: any) => {
    console.log('file', file);

    // 检查文件类型是否为图片
    if (file.type && !file.type.startsWith("image/")) {
      // 若不是图片，则在新页面打开文件链接
      window.open(file.url || file.preview, '_blank');
    } else {
      // 若是图片，则执行图片预览逻辑
      handlePreview(file);
    }


    setFileList(fileList)
    setImagePreviewVisible(true)
  };

  const columns: any = [
    {
      title: '日期',
      dataIndex: 'STATISTICS_DATE',
      width: 200,
      hideInSearch: true,
      render: (_, record) => {
        // onClick={()=>{
        //   setDailyCurrentRow({
        //     ...compareCurrent,
        //     ...record
        //   })
        //   setDailyRevenueDetail(true)
        // }}
        return record.STATISTICS_DATE !== '合计' ?
          <span >{record.STATISTICS_DATE}</span> : record.STATISTICS_DATE
      },
      onCell: (record) => ({
        style: {
          border: record.STATISTICS_DATE === '合计' ? '1px solid red' : '',
          borderRightColor: 'transparent'
          // backgroundColor: record.STATISTICS_DATE === '合计' ? '#dacece' :''
        }
      })
    },
    {
      title: '合计',
      dataIndex: 'rowSUM',
      hideInSearch: true,
      children: [
        {
          title: '自然日',
          dataIndex: 'DailyRowSum',
          width: 200,
          hideInSearch: true,
          valueType: 'money',
          render: (_, record) => {
            return <a onClick={() => {
              setDailyCurrentRow({
                ...compareCurrent,
                ...record
              })
              setDailyRevenueDetail(true)
            }}>
              {
                record?.Mobile_Correct || record?.Cash_Correct ?
                  `¥${numeral(getMoney(record?.DailyRowSum)).format('0,0.00')}(${Number(record?.Cash_Correct) + Number(record?.Mobile_Correct) > 0 ? `+${numeral(getMoney(Number(record?.Cash_Correct) + Number(record?.Mobile_Correct))).format('0.00')}` : Number(record?.Cash_Correct) + Number(record?.Mobile_Correct) < 0 ? `${numeral(getMoney(Number(record?.Cash_Correct) + Number(record?.Mobile_Correct))).format('0.00')}` : ''})` :
                  `¥${numeral(getMoney(record?.DailyRowSum)).format('0,0.00')}`
              }
              {/* {`¥${numeral(getMoney(record?.MobilePay_Amount + record?.CashPay_Amount)).format('0,0.00')}`} */}
              {/* {`¥${numeral(getMoney(record?.DailyRowSum)).format('0,0.00')}`} */}
            </a>

          },
          onCell: (record) => ({
            style: {
              border: record.STATISTICS_DATE === '合计' ? '1px solid red' : '',
              borderRightColor: 'transparent',
              borderLeftColor: 'transparent'
              // backgroundColor: record.STATISTICS_DATE === '合计' ? '#dacece' :''
            }
          })
        },
        {
          title: '项目拆分',
          dataIndex: 'ProjectRowSum',
          width: 200,
          hideInSearch: true,
          valueType: 'money',
          render: (_, record) => {
            return `¥${numeral(getMoney(record?.ProjectRowSum)).format('0,0.00')}`
            // `¥${numeral(getMoney(record?.CURMOBILEPAY_AMOUNT + record?.CURCASHPAY_AMOUNT)).format('0,0.00')}`
          },
          onCell: (record) => ({
            style: {
              border: record.STATISTICS_DATE === '合计' ? '1px solid red' : '',
              borderRightColor: 'transparent',
              borderLeftColor: 'transparent'
              // backgroundColor: record.STATISTICS_DATE === '合计' ? '#dacece' :''
            }
          })
        },
        {
          title: '差额',
          dataIndex: 'DifferenceRowSum',
          width: 200,
          hideInSearch: true,
          // valueType: 'money'

          render: (_, record) => {
            return `¥${numeral(getMoney(record?.DifferenceRowSum)).format('0,0.00')}`
            // `¥${numeral(getMoney((record?.MobilePay_Amount + record?.CashPay_Amount) -(record?.CURMOBILEPAY_AMOUNT + record?.CURCASHPAY_AMOUNT))).format('0,0.00')}`
          },
          onCell: (record) => ({
            style: {
              border: record.STATISTICS_DATE === '合计' ? '1px solid red' : '',
              borderLeftColor: 'transparent'
              // backgroundColor: record.STATISTICS_DATE === '合计' ? '#dacece' :''
            }
          })
        },
      ]
    },
    {
      title: '移动支付交易',
      dataIndex: 'MobilePaySUM',
      hideInSearch: true,
      children: [
        {
          title: '自然日',
          dataIndex: 'MobilePay_Amount',
          hideInSearch: true,
          width: 200,
          valueType: 'money',
          render: (_, record) => {
            return <a onClick={() => {
              setDailyCurrentRow({
                ...compareCurrent,
                ...record
              })
              setDailyRevenueDetail(true)
            }}>{
                record?.Mobile_Correct ?
                  `¥${numeral(record?.MobilePay_Amount).format('0,0.00')}（${(record?.Mobile_Correct) > 0 ? '+' : (record?.Mobile_Correct) < 0 ? '' : ''}${numeral((record?.Mobile_Correct)).format('0,0.00')}）`
                  :
                  `¥${numeral(record?.MobilePay_Amount).format('0,0.00')}`
              }</a>


            // return record?.Mobile_Correct || record?.MobilePay_AmountRect?
            //   `¥${numeral(getMoney(record?.MobilePay_Amount + (record?.Mobile_Correct || record?.MobilePay_AmountRect))).format('0,0.00')}（${(record?.Mobile_Correct || record?.MobilePay_AmountRect)>0?'+':(record?.Mobile_Correct || record?.MobilePay_AmountRect)<0?'-':''}${(record?.Mobile_Correct || record?.MobilePay_AmountRect)}）`
            //   : `¥${numeral(getMoney(record?.MobilePay_Amount)).format('0,0.00')}`
          }
        },
        {
          title: '项目拆分',
          dataIndex: 'CURMOBILEPAY_AMOUNT',
          hideInSearch: true,
          width: 200,
          valueType: 'money'
        },
        {
          title: <div style={{ display: 'flex', alignItems: 'center' }}>
            差额
            <div className={'questionBox'}>
              <img className={'questionIcon'} src={'https://eshangtech.com/ShopICO/ahyd-BID/newIndex3/noticeIcon.svg'} />
              <div className={'questionContent'}>
                <div style={{ marginBottom: '16px' }}>
                  <div style={{ fontWeight: 'bold' }}>精算金额：</div>
                  <div
                    style={{ textIndent: '2rem' }}>{'自然日移动支付<项目拆分移动支付，系统会自动校准差异金额，进行冲正补偿'}</div>
                </div>
                <div>
                  <div style={{ fontWeight: 'bold' }}>移动支付差异：</div>
                  <div
                    style={{ textIndent: '2rem' }}>{'1、存在人工确认，实际支付失败交易订单，项目拆分移动支付金额>自然日移动支付金额，人工确认金额转为现金交易'}</div>
                  <div
                    style={{ textIndent: '2rem' }}>{'2、项目拆分移动支付金额>自然日移动支付金额，且无人工确认订单，以项目拆分移动支付金额为准'}</div>
                  <div
                    style={{ textIndent: '2rem' }}>{'3、项目拆分移动支付金额<自然日移动支付金额，缺失经营项目拆分记录，需要重新生成数据'}</div>
                </div>
              </div>
            </div>
          </div>,
          dataIndex: 'differenceMobile',
          hideInSearch: true,
          width: 200,
          render: (_, record) => {
            return <div
              style={{ cursor: record?.STATISTICS_DATE !== '合计' ? 'pointer' : '', width: '100%', height: '100%' }}
              onClick={() => {
                console.log('record', record)
                if (record?.STATISTICS_DATE !== '合计') {
                  // if (record?.Mobile_Correct || record?.MobilePay_Amount !== record?.CURMOBILEPAY_AMOUNT || record?.DifferenceMobile!==0){
                  if (record?.DifferenceMobile !== 0 || record?.Mobile_Correct) {
                    console.log('record', record);
                    setSelectRow(record)
                    setDifferenceType(1)
                    setDailyDetailSales(true)
                  }
                }
              }}>{
                record.Mobile_Correct ?
                  `${numeral(getMoney(record?.MobilePay_Amount) - getMoney(record?.CURMOBILEPAY_AMOUNT)).format('0,0.00')}`
                  :
                  `${numeral(getMoney(record?.MobilePay_Amount) - getMoney(record?.CURMOBILEPAY_AMOUNT)).format('0,0.00')}`
                // record?.STATISTICS_DATE==='合计'?
                //   record?.MobilePay_AmountRect?
                // // （+${record?.MobilePay_AmountRect}）
                //     `${numeral(record?.MobilePay_Amount - record?.CURMOBILEPAY_AMOUNT).format('0.00')}`
                //     :record?.MobilePay_Amount === record?.CURMOBILEPAY_AMOUNT?'':`${numeral(record?.MobilePay_Amount- record?.CURMOBILEPAY_AMOUNT).format('0.00')}`
                // // （${record?.Mobile_Correct>0?'+':record?.Mobile_Correct<0?'-':''}${record?.Mobile_Correct}）
                //   :record?.Mobile_Correct && record?.Mobile_Correct>0?`${numeral(record?.MobilePay_Amount + record?.Mobile_Correct - record?.CURMOBILEPAY_AMOUNT).format('0.00')}`
                //     :record?.MobilePay_AmountRect?
                // // （+${record?.MobilePay_AmountRect}）
                //       `${numeral(record?.MobilePay_Amount+record?.MobilePay_AmountRect - record?.CURMOBILEPAY_AMOUNT).format('0.00')}`
                //       :record?.MobilePay_Amount === record?.CURMOBILEPAY_AMOUNT?'':`${numeral(record?.MobilePay_Amount- record?.CURMOBILEPAY_AMOUNT).format('0.00')}`
              }
            </div>
          },
          onCell: (record) => ({
            style: {
              backgroundColor: record.STATISTICS_DATE === '合计' ? '' : record?.DifferenceMobile !== 0 || record?.Mobile_Correct ? '#FFD5D8' : ''
              // backgroundColor: record.STATISTICS_DATE === '合计' ? '#fff' : record?.MobilePay_Amount ?
              //   (record?.MobilePay_Amount + (record?.MobilePay_AmountRect || 0)) === record?.CURMOBILEPAY_AMOUNT ? '#fff' :
              //     '#FFD5D8' : record?.DifferenceMobile!==0?'#FFD5D8':'#fff'
            }
          })
        },
      ]
    },
    {
      title: '现金支付交易',
      dataIndex: 'CashPaySUM',
      hideInSearch: true,
      children: [
        {
          title: '自然日',
          dataIndex: 'CashPay_Amount',
          width: 200,
          hideInSearch: true,
          valueType: 'money',
          render: (_, record) => {
            return <a onClick={() => {
              setDailyCurrentRow({
                ...compareCurrent,
                ...record
              })
              setDailyRevenueDetail(true)
            }}>{
                record?.Cash_Correct ?
                  `¥${numeral(record?.CashPay_Amount).format('0,0.00')}（${(record?.Cash_Correct) > 0 ? '+' : (record?.Cash_Correct) < 0 ? '' : ''}${numeral((record?.Cash_Correct)).format('0,0.00')}）`
                  :
                  `¥${numeral(record?.CashPay_Amount).format('0,0.00')}`
              }</a>

            // : `¥${numeral(getMoney(record?.CashPay_Amount)).format('0,0.00')}`
          }
        },
        {
          title: '项目拆分',
          dataIndex: 'CURCASHPAY_AMOUNT',
          width: 200,
          hideInSearch: true,
          valueType: 'money'
        },
        {
          title: <div style={{ display: 'flex', alignItems: 'center' }}>
            差额
            <div className={'questionBox'}>
              <img className={'questionIcon'} src={'https://eshangtech.com/ShopICO/ahyd-BID/newIndex3/noticeIcon.svg'} />
              <div className={'questionContent'}>
                {/* <div style={{marginBottom:'16px'}}> */}
                {/*   <div style={{fontWeight: 'bold'}}>精算金额：</div> */}
                {/*   <div */}
                {/*     style={{textIndent: '2rem'}}>{'自然日移动支付<项目拆分移动支付，系统会自动校准差异金额，进行冲正补偿'}</div> */}
                {/* </div> */}
                <div>
                  <div style={{ fontWeight: 'bold' }}>现金支付差异：</div>
                  <div
                    style={{ textIndent: '2rem' }}>{'1、收银系统上传的销售流水数据缺失：项目拆分金额<自然日现金支付金额'}</div>
                  <div style={{ textIndent: '2rem' }}>{'2、自然日报表未生成：项目拆分金额>自然日现金支付金额'}</div>
                  <div
                    style={{ textIndent: '2rem' }}>{'3、收银系统销售流水传输存在延迟情况：当日差异金额体现在后面的某一天中，需要重新生成拆分数据消除差异'}</div>
                  <div style={{ textIndent: '2rem' }}>{'4、收银机故障：项目拆分金额和自然日现金支付金额均会缺失'}</div>
                </div>
              </div>
            </div>
          </div>,
          dataIndex: 'differenceCash',
          width: 200,
          hideInSearch: true,
          render: (_, record) => {
            return <div
              style={{ cursor: record?.STATISTICS_DATE !== '合计' ? 'pointer' : '', width: '100%', height: '100%' }}
              onClick={() => {
                if (record?.CashPay_Amount && record?.STATISTICS_DATE !== '合计') {
                  if (record?.Cash_Correct || record?.CashPay_Amount !== record?.CURCASHPAY_AMOUNT) {
                    setSelectRow(record)
                    setDifferenceType(2)
                    setDailyDetailSales(true)
                  }
                }
              }}>{
                record.Cash_Correct ?
                  `${numeral(getMoney(record?.CashPay_Amount) - getMoney(record?.CURCASHPAY_AMOUNT)).format('0,0.00')}`
                  :
                  `${numeral(getMoney(record?.CashPay_Amount) - getMoney(record?.CURCASHPAY_AMOUNT)).format('0,0.00')}`




                // record?.STATISTICS_DATE==='合计'?
                //   record?.CashPay_AmountRect?
                // // （+${record?.CashPay_AmountRect}）
                //     `${numeral(record?.CashPay_Amount - record?.CURCASHPAY_AMOUNT).format('0.00')}`
                //     :record?.CashPay_Amount === record?.CURCASHPAY_AMOUNT?'':`${numeral(record?.CashPay_Amount- record?.CURCASHPAY_AMOUNT).format('0.00')}`
                // // （${record?.Cash_Correct>0?'+':record?.Cash_Correct<0?'-':''}${record?.Cash_Correct}）
                //   :record?.Cash_Correct && record?.Cash_Correct>0?`${numeral(record?.CashPay_Amount + record?.Cash_Correct - record?.CURCASHPAY_AMOUNT).format('0.00')}`
                //     :record?.CashPay_AmountRect?
                // // （+${record?.CashPay_AmountRect}）
                //       `${numeral(record?.CashPay_Amount+record?.CashPay_AmountRect - record?.CURCASHPAY_AMOUNT).format('0.00')}`
                //       :record?.CashPay_Amount === record?.CURCASHPAY_AMOUNT?'':`${numeral(record?.CashPay_Amount- record?.CURCASHPAY_AMOUNT).format('0.00')}`
              }</div>
          },
          onCell: (record) => ({
            style: {
              backgroundColor: record.STATISTICS_DATE === '合计' ? '' : record?.DifferenceCash !== 0 || record?.Cash_Correct ?
                '#FFD5D8' : ''
            },
          })
        }
      ]
    },

    {
      title: '日结冲正',
      width: 120,
      dataIndex: 'Correct_Amount',
      hideInSearch: true,
      hideInTable: compareCurrent?.PERIOD_STATE === 0 || hiddenCorrectAmount,
      render: (_, record) => {
        return record?.Correct_Amount ? record?.Correct_Amount : ''
      }
    }
  ]
  const [defaultColumnsStateMap, setDefaultColumnsStateMap] = useState<any>({
    monthConfirmIncome: {
      show: false,
      children: {
        ROYALTYTHEORYMUST: { show: false },
        ROYALTYTHEORYOK: { show: false },
        ROYALTYTHEORYMONTHLYMUST: { show: false },
      }
    },


    // CurMonthRevenue: { show: currentUser?.UserPattern === 2000 ? true : false },
    // ROYALTYTHEORYMUST: { show: currentUser?.UserPattern === 2000 ? false : true },
    // monthConfirmIncome: { show: currentUser?.UserPattern === 2000 ? false : true },
    // ROYALTYTHEORYOK: { show: currentUser?.UserPattern === 2000 ? false : true },
    // ROYALTYTHEORYMONTHLYMUST: { show: currentUser?.UserPattern === 2000 ? false : true },
  })
  // 同时控制两边的表格加载效果
  const [twoTableLoading, setTwoTableLoading] = useState<boolean>(false)
  // 底部表格的合計行數據
  const [bottomTableSum, setBottomTableSum] = useState<any>()
  // 月度结算的确认加载效果
  const [monthModalLoading, setMonthModalLoading] = useState<boolean>(false)
  // 顶部的项目数据
  const [topProjectDetail, setTopProjectDetail] = useState<any>()
  // 结算悬浮框的值
  const [modalFormValue, setModalFormValue] = useState<any>()
  // 显示审核流程抽屉
  const [showReviewProcess, setShowReviewProcess] = useState<boolean>(false)
  // 点击期限 出现的每月或每日的数据
  const [showDailyDrawer, setShowDailyDrawer] = useState<boolean>(false)
  // 月度收入数据抽屉
  const [showMonthlyDarwer, setShowMonthlyDrawer] = useState<boolean>(false)
  const [currentMonthly, setCurrentMonthly] = useState<any>()
  // 顶部表格数据
  const [topTable, setTopTable] = useState<any>()
  // 顶部表格的加载
  const [topTableLoading, setTopTableLoading] = useState<boolean>(false)
  // 展示更多
  const [showMoreBtn, setShowMoreBtn] = useState<boolean>(false)
  // 导出报表的表格数据
  const [printData, setPrintData] = useState<any>()
  // 附件
  const [fileList, setFileList] = useState<any>()
  // 签名数据
  const [signature, setSignatureObj] = useState<any>()

  const topColumns: any = [
    {
      title: <div style={{ textAlign: 'center' }}>期限</div>,
      dataIndex: '',
      fixed: 'left',
      children: [
        {
          title: <div style={{ textAlign: 'center' }}>期数</div>,
          dataIndex: 'IndexStr',
          width: 80,
          align: 'center'
        },
        {
          title: <div style={{ textAlign: 'center' }}>时限</div>,
          dataIndex: 'IndexDesc',
          width: 200,
          align: 'center',
          render: (_, record) => {
            // let [start,end] = record?.IndexDesc.split('-')
            // let startTime: string = moment(start).format('YYYY/MM/DD')
            // let endTime: string = moment(end).format('YYYY/MM/DD')
            // let realEndTime: string = new Date(record?.currentMonth).getTime() < new Date(endTime).getTime() ? moment(record?.currentMonth).endOf('month').format('YYYY/MM/DD'):endTime
            return record?.IndexDesc || ''
          }
        }
      ]
    },
    {
      title: <div style={{ textAlign: 'center' }}>租金信息</div>,
      dataIndex: '',
      children: [
        {
          title: <div style={{ textAlign: 'center' }}>保底/固定租金</div>,
          align: 'right',
          width: 160,
          valueType: 'digit',
          dataIndex: 'RENTFEE',
        },
        {
          title: <div style={{ textAlign: 'center' }}>提成比率</div>,
          dataIndex: 'GUARANTEERATIO',
          align: 'center',
          width: 120,
          render: (_, record) => {
            return record?.GUARANTEERATIO ? `${record?.GUARANTEERATIO}%` : ''
          }
        }
      ]
    },
    {
      title: <div style={{ textAlign: 'center' }}>累计营业额</div>,
      dataIndex: '',
      children: [
        {
          title: <div style={{ textAlign: 'center' }}>现金</div>,
          align: 'right',
          width: 120,
          valueType: 'digit',
          dataIndex: 'CASHPAY_AMOUNT',
        },
        {
          title: <div style={{ textAlign: 'center' }}>微支付</div>,
          align: 'right',
          width: 120,
          valueType: 'digit',
          dataIndex: 'MOBILEPAY_AMOUNT'
        },
        {
          title: <div style={{ textAlign: 'center' }}>小计</div>,
          align: 'right',
          valueType: 'digit',
          width: 120,
          dataIndex: 'REVENUEDAILY_AMOUNTTotal',
        },
        {
          title: <div style={{ textAlign: 'center' }}>提成金额</div>,
          align: 'right',
          valueType: 'digit',
          width: 120,
          dataIndex: 'GUARANTEERATIOAMOUNT',
          // render: (_, record) => {
          //   let number: number = record?.RevenueAmount * (record?.GuaranteeRatio / 100)
          //   return number ? numeral(number).format('0,0.00') : '-'
          // }
        }
      ]
    },
    {
      title: <div style={{ textAlign: 'center' }}>业主收款</div>,
      align: 'right',
      valueType: 'digit',
      width: 120,
      dataIndex: 'BANKACCOUNT_AMOUNT',
    },
    {
      title: <div style={{ textAlign: 'center' }}>应收租金</div>,
      align: 'right',
      width: 120,
      valueType: 'digit',
      dataIndex: 'ROYALTYTHEORYMUST',
    },
    {
      title: <div style={{ textAlign: 'center' }}>应收费用</div>,
      align: 'right',
      valueType: 'digit',
      width: 120,
      dataIndex: 'SHOPEXPENSE_AMOUNT',
    },
    {
      title: <div style={{ textAlign: 'center' }}>已缴费用</div>,
      align: 'right',
      valueType: 'digit',
      width: 120,
      dataIndex: 'PAID_AMOUNT',
    },
    {
      title: <div style={{ textAlign: 'center' }}>退补款</div>,
      align: 'right',
      valueType: 'digit',
      width: 120,
      dataIndex: 'RefundSupplement',
      fixed: 'right',
      render: (_, record) => {
        const number: number = record?.BANKACCOUNT_AMOUNT - record?.ROYALTYTHEORYMUST - record?.SHOPEXPENSE_AMOUNT + record?.PAID_AMOUNT
        return number ? numeral(number).format('0,0.00') : '-'
      }
    },
  ]

  const defaultColumns: any = [
    {
      title: '类型',
      dataIndex: 'type',
      width: 150,
      hideInSearch: true,
      render: (_, record) => {
        return <span>{record?.type}
          <span onClick={() => {
            setShowReviewProcess(true)
          }} style={{ color: 'red', cursor: 'pointer' }}>
            {`${compareCurrent?.Approvalstate === 9 && record?.type === '精算金额' ? '（已审结）' :
              compareCurrent?.Approvalstate > 0 && compareCurrent?.Approvalstate < 9 && record?.type === '精算金额' && !(compareCurrent?.Approvalstate > 0 && compareCurrent.PEND_STATE === 0) ?
                '（审核中）' : ''}`}</span>
        </span>
      }
    },
    {
      title: '统计时间',
      dataIndex: 'search_months',
      valueType: 'date',
      initialValue: moment().subtract(1, 'months').format('YYYY-MM'),
      search: {
        transform: (value) => {
          return {
            MonthDate: moment(value).startOf("month").format('YYYY-MM'),
          };
        },
      },
      hideInTable: true,
      fieldProps: {
        picker: "month",
        format: 'YYYY-MM',
      }
    },
    {
      title: <div style={{ textAlign: 'center' }}>{'期限'}</div>,
      dataIndex: 'IndexDesc',
      align: 'left',
      width: 180,
      hideInSearch: true,
      render: (_, record) => {
        return <a onClick={() => {
          console.log('c', compareCurrent)
          setShowDailyDrawer(true)
        }}>{record?.IndexDesc || ''}</a>
      }
    },
    {
      title: '浮动提成应确认收入',
      dataIndex: '',
      hideInSearch: true,
      children: [
        {
          title: <div style={{ textAlign: 'center' }}>{'累计营业额'}</div>,
          dataIndex: 'REVENUEDAILY_AMOUNTTotal',
          width: 120,
          valueType: 'digit',
          align: 'right',
          hideInSearch: true,
          render: (_, record) => {
            return record?.REVENUEDAILY_AMOUNTTotal ?
              <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'flex-end' }}>
                {
                  record?.RevenueTrend === true || record?.RevenueTrend === false ?
                    <img style={{ width: '20px', height: '20px' }}
                      src={record?.RevenueTrend === true ? addIcon : reduce} /> : ''
                }
                {
                  record?.BUSINESSPROJECT_ID ?
                    <span>{numeral(getMoney(record?.REVENUEDAILY_AMOUNTTotal)).format('0,0.00')}</span> :
                    <span>{numeral(getMoney(record?.REVENUEDAILY_AMOUNTTotal)).format('0,0.00')}</span>
                }
              </div>
              :
              '-'
          }
        },
        {
          title: <div style={{ textAlign: 'center' }}>{'移动支付'}</div>,
          dataIndex: 'MobilePay',
          valueType: 'digit',
          width: 120,
          align: 'right',
          hideInSearch: true,
        },
        {
          title: <div style={{ textAlign: 'center' }}>{'移动冲正'}</div>,
          dataIndex: 'MOBILEPAY_CORRECT',
          align: 'right',
          valueType: 'digit',
          width: 120,
          hideInSearch: true,
        },
        {
          title: <div style={{ textAlign: 'center' }}>{'现金交易'}</div>,
          dataIndex: 'CashPay',
          valueType: 'digit',
          width: 120,
          align: 'right',
          hideInSearch: true,
        },
        {
          title: <div style={{ textAlign: 'center' }}>{'现金冲正'}</div>,
          dataIndex: 'CASHPAY_CORRECT',
          align: 'right',
          valueType: 'digit',
          width: 120,
          hideInSearch: true,
        },
        {
          title: <div style={{ textAlign: 'center' }}>{'提成金额'}</div>,
          dataIndex: 'GUARANTEERATIOAMOUNT',
          width: 120,
          valueType: 'digit',
          align: 'right',
          hideInSearch: true,
          render: (_, record) => {
            const title: string = `分润营业额(${record.REVENUEDAILY_AMOUNTTotal}) * 提成比例(${record.GUARANTEERATIO ? `${record.GUARANTEERATIO}%` : ''})`
            // const title: string = `分润营业额(${record.REVENUEDAILY_AMOUNTTotal}) * 提成比例(${numeral(record.GUARANTEERATIO / 100).format('0.00')})`
            return record.GUARANTEERATIO ? <Tooltip title={title}>
              <span>{numeral(record?.GUARANTEERATIOAMOUNT).format('0,0.00')}</span>
            </Tooltip> : <span>{numeral(record?.GUARANTEERATIOAMOUNT).format('0,0.00')}</span>
          }
        },
        {
          title: <div style={{ textAlign: 'center' }}>{'提成收入'}</div>,
          dataIndex: 'GUARANTEERATIOINCOME',
          width: 120,
          valueType: 'digit',
          align: 'right',
          hideInSearch: true,
          render: (_, record) => {
            const title: string = `提成金额(${record.GUARANTEERATIOAMOUNT}) / 税(1 + ${numeral(record.TaxRate / 100).format('0.00')})`
            return record?.TaxRate ? <Tooltip title={title}>
              <span>{numeral(record?.GUARANTEERATIOINCOME).format('0,0.00')}</span>
            </Tooltip> : <span>{numeral(record?.GUARANTEERATIOINCOME).format('0,0.00')}</span>
          }
        },

      ]
    },
    {
      title: <div style={{ textAlign: 'center' }}>
        <div>{`${moment(compareCurrent?.STATISTICS_MONTH || monthTime || '').format('YYYY/MM')}月度分润营业额`}</div>
        {/* <div>{`(${moment(compareCurrent?.STATISTICS_MONTH || monthTime || '').startOf('month').format('YYYY/MM/DD')}-${moment(compareCurrent?.STATISTICS_MONTH || monthTime || '').endOf('month').format('YYYY/MM/DD')})`}</div> */}
      </div>,
      dataIndex: 'CurMonthRevenue',
      width: 180,
      valueType: 'digit',
      align: 'right',
      hideInSearch: true,
    },
    {
      title: '本月确认收入',
      dataIndex: 'monthConfirmIncome',
      hideInSearch: true,
      children: [
        {
          title: <div style={{ textAlign: 'center' }}>{'累计应确认收入'}</div>,
          dataIndex: 'ROYALTYTHEORYMUST',
          width: 120,
          valueType: 'digit',
          align: 'right',
          hideInSearch: true,
          render: (_, record) => {
            const title: string = record?.GUARANTEERATIOINCOME > record?.MonthlyTotalIncome ?
              `${record?.GUARANTEERATIOINCOME}(提成收入)>${record?.MonthlyTotalIncome}(累计应确认收入)=${record?.GUARANTEERATIOINCOME}(提成收入)` :
              `${record?.MonthlyTotalIncome}(累计应确认收入)>${record?.GUARANTEERATIOINCOME}(提成收入)=${record?.MonthlyTotalIncome}(累计应确认收入)`
            return record?.ROYALTYTHEORYMUST && record?.BUSINESSPROJECT_ID ?
              <Tooltip title={title}>
                <span>{record?.ROYALTYTHEORYMUST ? numeral(record?.ROYALTYTHEORYMUST).format('0,0.00') : '-'}</span>
              </Tooltip>
              : record?.ROYALTYTHEORYMUST ?
                <Tooltip title={title}>
                  <span>{numeral(record?.ROYALTYTHEORYMUST).format('0,0.00')}</span>
                </Tooltip>
                : '-'
          }
        },
        {
          title: <div style={{ textAlign: 'center' }}>{'累计已确认收入'}</div>,
          dataIndex: 'ROYALTYTHEORYOK',
          width: 140,
          valueType: 'digit',
          align: 'right',
          hideInSearch: true,
          render: (_, record) => {
            return <a onClick={() => {
              setCurrentMonthly(record)
              setShowMonthlyDrawer(true)
            }}>{record?.ROYALTYTHEORYOK ? numeral(record?.ROYALTYTHEORYOK).format('0,0.00') : '-'}</a>
          }
        },
        {
          title: <div style={{ textAlign: 'center' }}>{'本月应确认'}</div>,
          dataIndex: 'ROYALTYTHEORYMONTHLYMUST',
          width: 120,
          valueType: 'digit',
          align: 'right',
          hideInSearch: true,
          render: (_, record) => {
            const title: string = `累计应确认收入(${record.ROYALTYTHEORYMUST}) - 累计已确认收入(${numeral(record?.ROYALTYTHEORYOK).format('0.00')})`
            return <Tooltip title={title}>
              <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'flex-end' }}>
                {
                  record?.ROYALTYTrend === true || record?.ROYALTYTrend === false ?
                    <img style={{ width: '20px', height: '20px' }}
                      src={record?.ROYALTYTrend === true ? addIcon : reduce} /> : ''
                }
                <span>{record?.ROYALTYTHEORYMONTHLYMUST ? numeral(record?.ROYALTYTHEORYMONTHLYMUST).format('0,0.00') : '-'}</span>
              </div>
            </Tooltip>
          }
        },
      ]
    },
  ]

  const detailColumns: any = [
    {
      dataIndex: 'index',
      title: '序号',
      hideInSearch: true,
      // valueType: 'index',
      align: 'center',
      width: 48,
    },
    {
      dataIndex: 'SELLMASTER_DATE',
      valueType: "date",
      width: 150,
      title: '销售时间',
      align: 'center',
      initialValue: moment().add(-1, 'day'),
      render: (_, record) => {
        return record?.SELLMASTER_DATE
      },
      fieldProps: {
        disabledDate: (current: any) => current && current > moment().endOf('day').add(-1, 'day')
      }
    },
    // {
    //   dataIndex: 'TICKET_CODE',
    //   title: '小票编号',
    //   hideInSearch: true,
    //   align: 'center',
    // },
    {
      dataIndex: 'SELLMASTER_CODE',
      title: '订单编号',
      align: 'center',
      hideInDescriptions: true,
      hideInSearch: true,
    },
    {
      dataIndex: 'SELLMASTER_COUNT',
      title: '销售数量',
      hideInSearch: true,
      align: 'right',
      sorter: (a, b) => a.SELLMASTER_COUNT - b.SELLMASTER_COUNT
    },
    {
      title: '订单状态',
      dataIndex: 'SELLMASTER_STATETEXT',
    },
    {
      dataIndex: 'SELLMASTER_AMOUNT',
      title: '本地流水',
      hideInSearch: true,
      valueType: "money",
      align: 'right',
      sorter: (a, b) => a.SELLMASTER_AMOUNT - b.SELLMASTER_AMOUNT
    },
    {
      dataIndex: 'SELLMASTER_OFFPRICE',
      title: '优惠金额',
      hideInSearch: true,
      valueType: "money",
      align: 'right',
      sorter: (a, b) => a.SELLMASTER_OFFPRICE - b.SELLMASTER_OFFPRICE
    },
    {
      dataIndex: 'PAYMENT_TYPE_TEXT',
      title: '支付方式',
      hideInSearch: true,
      align: 'center',
      render: (_, record) => {
        return record?.PAYMENT_TYPE_TEXT ? record?.PAYMENT_TYPE_TEXT : ''
      }
    },
    {
      dataIndex: 'Ticket_Price',
      title: '项目拆分',
      hideInSearch: true,
      hideInTable: DifferenceType !== 1,
      align: 'center',
      onCell: (record) => ({
        style: {
          backgroundColor: record.SELLMASTER_AMOUNT !== record.Ticket_Price && record.SELLMASTER_DATE !== '合计' ? '#FFD5D8' : ''
        }
      })
    },
    {
      dataIndex: 'SHOPNAME',
      hideInSearch: true,
      title: '门店名称',
      align: 'center',
      width: '12%',
    },
    {
      dataIndex: 'MACHINECODE',
      hideInSearch: true,
      title: '收银机号',
      align: 'center',
    },
    {
      dataIndex: 'SELLWORKER_NAME',
      hideInSearch: true,
      title: '收银人员',
      align: 'center',
    }
  ]

  const recordColumns: any = [
    {
      dataIndex: 'index',
      title: '序号',
      hideInSearch: true,
      // valueType: 'index',
      align: 'center',
      width: 48,
    },
    {
      dataIndex: 'Pay_Date',
      title: '交易时间',
      align: 'center',
      hideInSearch: true,
      hideInDescriptions: true,
    },
    {
      dataIndex: 'Ticket_Code',
      title: '订单编号',
      align: 'center',
      hideInDescriptions: true,
      hideInSearch: true,
    },
    {
      dataIndex: 'Machine_Code',
      title: '机器编码',
      align: 'center',
      hideInSearch: true,
      hideInDescriptions: true,
    },
    {
      dataIndex: 'Ticket_Price',
      title: '项目拆分',
      align: 'right',
      hideInSearch: true,
      hideInDescriptions: true,
    },
    {
      dataIndex: 'Account_Price',
      title: '到账金额',
      align: 'right',
      hideInSearch: true,
      hideInDescriptions: true,
    },
    {
      dataIndex: 'SubRoyalty_Price',
      title: '商家分润',
      align: 'right',
      hideInSearch: true,
      hideInDescriptions: true,
    },
    {
      dataIndex: 'Ticket_Fee',
      title: '手续费',
      align: 'right',
      hideInSearch: true,
      hideInDescriptions: true,
    },
    {
      title: '业主分润',
      dataIndex: 'Royalty_Price',
      align: 'right',
      hideInSearch: true,
      hideInDescriptions: true,
    },
    {
      title: '分账比例',
      dataIndex: 'Royalty_Rate',
      align: 'right',
      hideInSearch: true,
      hideInDescriptions: true,
      render: (_, record) => {
        return record?.Royalty_Rate && record?.SubRoyalty_Rate ? `${record.Royalty_Rate / 100}:${record.SubRoyalty_Rate / 100}` : ''
      },
    },
  ]
  const onDraggaleStart = (event, uiData) => {

    const { clientWidth, clientHeight } = window.document.documentElement;
    const targetRect = draggleRef.current?.getBoundingClientRect();
    if (!targetRect) {
      return;
    }
    setBounds({
      left: -targetRect.left + uiData.x,
      right: clientWidth - (targetRect.right - uiData.x),
      top: -targetRect.top + uiData.y,
      bottom: clientHeight - (targetRect.bottom - uiData.y),
    });
  };

  // 获得第一层抽屉的表格数据的方法
  const handleGetTableData = async () => {

    setCompareTableLoading(true)
    if (compareCurrent?.Approvalstate > 0) {
      setTableSecondLoading(true)
    }

    console.log('compareCurrentcompareCurrentcompareCurrent', compareCurrent);

    const req: any = {
      StartDate: compareCurrent?.startTime || '',
      EndDate: compareCurrent?.endTime || '',
      SHOPROYALTY_ID: compareCurrent?.ShopRoyaltyId || compareCurrent?.ShopRoyaltyId === 0 ? compareCurrent?.ShopRoyaltyId : '',
      BUSINESSPROJECT_ID: compareCurrent?.BUSINESSPROJECT_ID || '',
      ACCOUNT_TYPE: 1000,
      SERVERPARTSHOP_ID: compareCurrent?.Id || '',
      DataSourceType: 2,
      SERVERPART_ID: compareCurrent?.SERVERPART_ID,
      STATISTICS_MONTH: compareCurrent?.STATISTICS_MONTH ? moment(compareCurrent?.STATISTICS_MONTH).format('YYYYMM') : monthTime ? moment(monthTime).format('YYYYMM') : ''
    }

    console.log('reqreqreqreqreqreq', req);


    if (compareCurrent) {
      if (compareCurrent.IndexDesc || compareCurrent?.ENDDATE) {
        let [start, end]: any[] = []
        if (compareCurrent.IndexDesc) {
          [start, end] = compareCurrent.IndexDesc.split('-')
          end = moment(end).format('YYYY-MM-DD')
        } else {
          end = compareCurrent?.ENDDATE
        }
        // const [start, end] = compareCurrent.IndexDesc.split('-')
        const overTime: string = moment(end).format('YYYY-MM-DD')
        const y: number = new Date(overTime).getFullYear()
        const m: number = new Date(overTime).getMonth() + 1
        const d: number = new Date(overTime).getDate()
        const currentYear: number = new Date(moment(compareCurrent?.STATISTICS_MONTH || monthTime).format('YYYY-MM-DD')).getFullYear()
        const currentMonth: number = new Date(moment(compareCurrent?.STATISTICS_MONTH || monthTime).format('YYYY-MM-DD')).getMonth() + 1

        // 如果跟查询时间是同一月份 且 年份月份都对上 那就显示日结冲正
        if (m === currentMonth && y === currentYear) {
          setHiddenCorrectAmount(false)
        }
        //  如果结束期限跟当前实际的时间 年月天都对上 那就显示日结冲正
        const nowY: number = new Date().getFullYear()
        const nowM: number = new Date().getMonth() + 1
        const nowD: number = new Date().getDate()
        if (y === nowY && m === nowM && d === nowD) {
          setHiddenCorrectAmount(false)
        }
      }
    }
    const data = await handleGetRevenueReportByBIZPSPLITMONTH(req)
    let res: any = {}
    if (data && data.length > 0) {
      res = data[0]
    }
    console.log('data212', data)
    // 已经发起申请了的 就不去请求下面表格的数据了
    // 也不会显示 请求上面那个接口是因为要拿到顶部的详情数据
    if (compareCurrent?.Approvalstate > 0 && come !== 'ConfirmationDifference') {
      if (res) {
        setTopProjectDetail(res.RevenueRecognition)
      }
      if (compareCurrent.Approvalstate === 9) {
        let detailObj: any = {}
        console.log('compareCurrent', compareCurrent)
        let detail: any = {}
        if (compareCurrent?.BUSINESSAPPROVAL_ID || compareCurrent?.BusinessApprovalId) {
          detail = await handleGetBUSINESSAPPROVALDetail({ BUSINESSAPPROVALId: compareCurrent?.BUSINESSAPPROVAL_ID || compareCurrent?.BusinessApprovalId })
        }
        console.log('detail', detail);
        if (detail?.BUSINESSPROCESS_ID) {
          const res = await handleGetBIZPSPLITMONTHDetail({ BIZPSPLITMONTHId: detail?.BUSINESSPROCESS_ID })
          detailObj = res
        }
        console.log('detailObj', detailObj);
        const req: any = {
          BusinessProjectId: detailObj?.BUSINESSPROJECT_ID,
          StatisticsMonth: detailObj?.STATISTICS_MONTH ? moment(detailObj?.STATISTICS_MONTH).format('YYYYMM') : '',
          ShopRoyaltyId: detailObj?.SHOPROYALTY_ID,
          MobilePayCorrect: detailObj?.MOBILEPAY_CORRECT || 0,
          CashPayCorrect: detailObj?.CASHPAY_CORRECT || 0
        }
        const income = await handleGetProjectPeriodIncome(req)
        console.log('income', income);
        let incomeObj: any = {}
        if (income && income.length > 0) {
          incomeObj = income[0]
        }
        console.log('setFirstTableData1');
        setFirstTableData([{
          // ...secondItem,
          ...incomeObj,
          type: '精算金额',
          // IndexDesc: incomeObj.IndexDesc,
          IndexDesc: `${compareCurrent?.STARTDATE}-${compareCurrent?.ENDDATE}`,
          MOBILEPAY_CORRECT: detailObj?.MOBILEPAY_CORRECT,
          CASHPAY_CORRECT: detailObj?.CASHPAY_CORRECT,
          REVENUEDAILY_AMOUNTTotal: incomeObj?.REVENUEDAILY_AMOUNTTotal,
          MobilePay: detailObj?.MOBILEPAY_AMOUNT,
          CashPay: detailObj?.CASHPAY_AMOUNT,
        }])

      } else {
        let detailObj: any = {}
        console.log('compareCurrent', compareCurrent)
        let detail: any = {}
        if (compareCurrent?.BUSINESSAPPROVAL_ID || compareCurrent?.BusinessApprovalId) {
          detail = await handleGetBUSINESSAPPROVALDetail({ BUSINESSAPPROVALId: compareCurrent?.BUSINESSAPPROVAL_ID || compareCurrent?.BusinessApprovalId })
        }
        console.log('detail', detail);
        if (detail?.BUSINESSPROCESS_ID) {
          const res = await handleGetBIZPSPLITMONTHDetail({ BIZPSPLITMONTHId: detail?.BUSINESSPROCESS_ID })
          detailObj = res
        }
        console.log('detailObj32', detailObj);

        if (compareCurrent?.Approvalstate > 0 && compareCurrent.PEND_STATE === 0 && compareCurrent.APPLY_PROCCESS === true) {
          const req: any = {
            BusinessProjectId: compareCurrent?.BUSINESSPROJECT_ID,
            StatisticsMonth: compareCurrent?.STATISTICS_MONTH ? moment(compareCurrent?.STATISTICS_MONTH).format('YYYYMM') : monthTime ? moment(monthTime).format('YYYYMM') : '',
            ShopRoyaltyId: compareCurrent?.ShopRoyaltyId,
          }
          const income = await handleGetProjectPeriodIncome(req)
          console.log('income', income)
          let incomeObj: any = {}
          if (income && income.length > 0) {
            incomeObj = income[0]
          }
          console.log('incomeObj2222323', incomeObj);
          if (incomeObj?.AllowSettlement === 1) {
            setLastMonthIsOver(true)
          } else if (incomeObj?.AllowSettlement === 2) {
            setLastMonthIsOver(false)
            setLastSettlementMonth(`${incomeObj?.LastSettlementMonth}审结中月度结算正在审批中，请审结后再发起${compareCurrent?.STATISTICS_MONTH}月度结算`)
          } else {
            setLastMonthIsOver(false)
            if (incomeObj?.LastSettlementState === 0) {
              setLastSettlementMonth(`请先进行${incomeObj?.LastSettlementMonth}月度结算`)
            } else if (incomeObj?.LastSettlementState === 1) {
              setLastSettlementMonth(`请先进行${incomeObj?.LastSettlementMonth}月度结算`)
            } else if (incomeObj?.LastSettlementState === 2) {
              setLastSettlementMonth(`请先进行${incomeObj?.LastSettlementMonth}月度结算正在审批中，请审结后再发起下一个月度结算`)
            }
          }
          setSettlementObj({
            AllowSettlement: incomeObj?.AllowSettlement,
            LastSettlementState: incomeObj?.LastSettlementState,
            LastSettlementMonth: incomeObj?.LastSettlementMonth
          })
          let sumObj: any = {}
          sumObj = res.CompareTotal
          console.log('setFirstTableData2');
          setFirstTableData([{
            ...compareCurrent,
            MobilePay: sumObj?.MobilePay_Amount || incomeObj?.MOBILEPAY_AMOUNT,
            CashPay: sumObj?.CashPay_Amount || incomeObj?.CASHPAY_AMOUNT,
            MOBILEPAY_CORRECT: compareCurrent?.MOBILEPAY_CORRECT || incomeObj?.MOBILEPAY_CORRECT,
            CASHPAY_CORRECT: compareCurrent?.CASHPAY_CORRECT || incomeObj?.CASHPAY_CORRECT,
            type: '结算金额',
            IndexDesc: compareCurrent?.IndexDesc || `${compareCurrent?.STARTDATE}-${compareCurrent?.ENDDATE}`,
            REVENUEDAILY_AMOUNTTotal: compareCurrent?.REVENUEDAILY_AMOUNTTotal || incomeObj?.REVENUEDAILY_AMOUNTTotal,
            ROYALTYTHEORYMUST: type === 'revenueConfirmation' ? compareCurrent?.ROYALTYTHEORYMUST : incomeObj?.ROYALTYTHEORYMUST,
            ROYALTYTHEORYOK: type === 'revenueConfirmation' ? compareCurrent?.ROYALTYTHEORYOK : incomeObj?.ROYALTYTHEORYOK,
            ROYALTYTHEORYMONTHLYMUST: type === 'revenueConfirmation' ? compareCurrent?.ROYALTYTHEORYMONTHLYMUST : incomeObj?.ROYALTYTHEORYMONTHLYMUST,
            GUARANTEERATIO: incomeObj?.GUARANTEERATIO,
            GUARANTEERATIOAMOUNT: incomeObj?.GUARANTEERATIOAMOUNT,
            GUARANTEERATIOINCOME: incomeObj?.GUARANTEERATIOINCOME,
            TaxRate: incomeObj?.TaxRate,
            MonthlyTotalIncome: incomeObj?.MonthlyTotalIncome
          }])

          // 存一份初始的
          setDefaultFirstTableData({
            ...compareCurrent,
            MobilePay: sumObj?.MobilePay_Amount || incomeObj?.MOBILEPAY_AMOUNT,
            CashPay: sumObj?.CashPay_Amount || incomeObj?.CASHPAY_AMOUNT,
            MOBILEPAY_CORRECT: compareCurrent?.MOBILEPAY_CORRECT || incomeObj?.MOBILEPAY_CORRECT,
            CASHPAY_CORRECT: compareCurrent?.CASHPAY_CORRECT || incomeObj?.CASHPAY_CORRECT,
            type: '结算金额',
            IndexDesc: compareCurrent?.IndexDesc || `${compareCurrent?.STARTDATE}-${compareCurrent?.ENDDATE}`,
            REVENUEDAILY_AMOUNTTotal: compareCurrent?.REVENUEDAILY_AMOUNTTotal || incomeObj?.REVENUEDAILY_AMOUNTTotal,
            ROYALTYTHEORYMUST: type === 'revenueConfirmation' ? compareCurrent?.ROYALTYTHEORYMUST : incomeObj?.ROYALTYTHEORYMUST,
            ROYALTYTHEORYOK: type === 'revenueConfirmation' ? compareCurrent?.ROYALTYTHEORYOK : incomeObj?.ROYALTYTHEORYOK,
            ROYALTYTHEORYMONTHLYMUST: type === 'revenueConfirmation' ? compareCurrent?.ROYALTYTHEORYMONTHLYMUST : incomeObj?.ROYALTYTHEORYMONTHLYMUST,
            GUARANTEERATIO: incomeObj?.GUARANTEERATIO,
            GUARANTEERATIOAMOUNT: incomeObj?.GUARANTEERATIOAMOUNT,
            GUARANTEERATIOINCOME: incomeObj?.GUARANTEERATIOINCOME,
            TaxRate: incomeObj?.TaxRate,
            MonthlyTotalIncome: incomeObj?.MonthlyTotalIncome
          })

        } else {
          await getCalibrationTableData(detailObj?.MOBILEPAY_CORRECT, detailObj?.CASHPAY_CORRECT, res.CompareTotal, detailObj)
        }
      }

      setTableSecondLoading(false)
    } else {
      if (res) {
        let list: any = []
        if (res.Compares && res.Compares.length > 0) {
          list = JSON.parse(JSON.stringify(res.Compares))
        }
        setTopProjectDetail(res.RevenueRecognition)
        // 项目详情数据
        setBottomTableSum(res.CompareTotal)
        let sumObj: any = {}
        sumObj = res.CompareTotal
        list.unshift(res.CompareTotal)

        if (compareCurrent.Approvalstate === 9) {
          let detailObj: any = {}
          console.log('compareCurrent', compareCurrent)
          let detail: any = {}
          if (compareCurrent?.BUSINESSAPPROVAL_ID || compareCurrent?.BusinessApprovalId) {
            detail = await handleGetBUSINESSAPPROVALDetail({ BUSINESSAPPROVALId: compareCurrent?.BUSINESSAPPROVAL_ID || compareCurrent?.BusinessApprovalId })
          }
          console.log('detail', detail);
          if (detail?.BUSINESSPROCESS_ID) {
            const res = await handleGetBIZPSPLITMONTHDetail({ BIZPSPLITMONTHId: detail?.BUSINESSPROCESS_ID })
            detailObj = res
          }
          console.log('detailObj', detailObj);
          const req: any = {
            BusinessProjectId: detailObj?.BUSINESSPROJECT_ID,
            StatisticsMonth: detailObj?.STATISTICS_MONTH ? moment(detailObj?.STATISTICS_MONTH).format('YYYYMM') : '',
            ShopRoyaltyId: detailObj?.SHOPROYALTY_ID,
            MobilePayCorrect: detailObj?.MOBILEPAY_CORRECT || 0,
            CashPayCorrect: detailObj?.CASHPAY_CORRECT || 0
          }
          const income = await handleGetProjectPeriodIncome(req)
          console.log('income', income);
          let incomeObj: any = {}
          if (income && income.length > 0) {
            incomeObj = income[0]
          }
          console.log('setFirstTableData3');
          setFirstTableData([{
            // ...secondItem,
            ...incomeObj,
            type: '精算金额',
            // IndexDesc: incomeObj.IndexDesc,
            IndexDesc: `${compareCurrent?.STARTDATE}-${compareCurrent?.ENDDATE}`,
            MOBILEPAY_CORRECT: detailObj?.MOBILEPAY_CORRECT,
            CASHPAY_CORRECT: detailObj?.CASHPAY_CORRECT,
            REVENUEDAILY_AMOUNTTotal: incomeObj?.REVENUEDAILY_AMOUNTTotal,
            MobilePay: detailObj?.MOBILEPAY_AMOUNT,
            CashPay: detailObj?.CASHPAY_AMOUNT,
          }])

        } else {
          // if (compareCurrent?.CASHPAY_CORRECT || compareCurrent?.MOBILEPAY_CORRECT || (compareCurrent?.Approvalstate > 0 && compareCurrent?.Approvalstate < 9)) {
          if (compareCurrent?.Approvalstate > 0 && compareCurrent?.Approvalstate < 9) {

            let detailObj: any = {}
            console.log('compareCurrent', compareCurrent)
            let detail: any = {}
            if (compareCurrent?.BUSINESSAPPROVAL_ID || compareCurrent?.BusinessApprovalId) {
              detail = await handleGetBUSINESSAPPROVALDetail({ BUSINESSAPPROVALId: compareCurrent?.BUSINESSAPPROVAL_ID || compareCurrent?.BusinessApprovalId })
            }
            if (detail?.BUSINESSPROCESS_ID) {
              const res = await handleGetBIZPSPLITMONTHDetail({ BIZPSPLITMONTHId: detail?.BUSINESSPROCESS_ID })
              detailObj = res
            }
            await getCalibrationTableData(detailObj?.MOBILEPAY_CORRECT, detailObj?.CASHPAY_CORRECT, res.CompareTotal, detailObj)
          } else {
            const req: any = {
              BusinessProjectId: compareCurrent?.BUSINESSPROJECT_ID,
              StatisticsMonth: compareCurrent?.STATISTICS_MONTH ? moment(compareCurrent?.STATISTICS_MONTH).format('YYYYMM') : monthTime ? moment(monthTime).format('YYYYMM') : '',
              ShopRoyaltyId: compareCurrent?.ShopRoyaltyId,
            }
            const income = await handleGetProjectPeriodIncome(req)
            console.log('income', income)
            let incomeObj: any = {}
            if (income && income.length > 0) {
              incomeObj = income[0]
            }
            console.log('incomeObj32', incomeObj);
            if (incomeObj?.AllowSettlement === 1) {
              setLastMonthIsOver(true)
            } else if (incomeObj?.AllowSettlement === 2) {
              setLastMonthIsOver(false)
              setLastSettlementMonth(`${incomeObj?.LastSettlementMonth}审结中月度结算正在审批中，请审结后再发起${compareCurrent?.STATISTICS_MONTH}月度结算`)
            } else {
              setLastMonthIsOver(false)
              if (incomeObj?.LastSettlementState === 0) {
                setLastSettlementMonth(`请先进行${incomeObj?.LastSettlementMonth}月度结算`)
              } else if (incomeObj?.LastSettlementState === 1) {
                setLastSettlementMonth(`请先进行${incomeObj?.LastSettlementMonth}月度结算`)
              } else if (incomeObj?.LastSettlementState === 2) {
                setLastSettlementMonth(`请先进行${incomeObj?.LastSettlementMonth}月度结算正在审批中，请审结后再发起下一个月度结算`)
              }
            }
            setSettlementObj({
              AllowSettlement: incomeObj?.AllowSettlement,
              LastSettlementState: incomeObj?.LastSettlementState,
              LastSettlementMonth: incomeObj?.LastSettlementMonth
            })
            // 现在会有一种情况是手动冲正的情况
            // 手动冲正的情况只会出现在未发起申请 即Approvalstate为0的时候 所以在这里 加个判断 有没有手动冲正
            // 若有手动冲正 就直接显示精算金额
            if (compareCurrent?.MOBILEPAY_CORRECT || incomeObj?.MOBILEPAY_CORRECT || compareCurrent?.CASHPAY_CORRECT || incomeObj?.CASHPAY_CORRECT) {
              console.log('setFirstTableData4');
              setFirstTableData([{
                ...compareCurrent,
                type: '精算金额',
                MobilePay: sumObj?.MobilePay_Amount || incomeObj?.MOBILEPAY_AMOUNT,
                CashPay: sumObj?.CashPay_Amount || incomeObj?.CASHPAY_AMOUNT,
                CashPay_Amount: sumObj?.CashPay_Amount || incomeObj?.CASHPAY_AMOUNT,
                MOBILEPAY_AMOUNT: sumObj?.MobilePay_Amount || incomeObj?.MOBILEPAY_AMOUNT,
                MOBILEPAY_CORRECT: compareCurrent?.MOBILEPAY_CORRECT || incomeObj?.MOBILEPAY_CORRECT,
                CASHPAY_CORRECT: compareCurrent?.CASHPAY_CORRECT || incomeObj?.CASHPAY_CORRECT,
                IndexDesc: compareCurrent?.IndexDesc || `${compareCurrent?.STARTDATE}-${compareCurrent?.ENDDATE}`,
                REVENUEDAILY_AMOUNTTotal: compareCurrent?.REVENUEDAILY_AMOUNTTotal || incomeObj?.REVENUEDAILY_AMOUNTTotal,
                ROYALTYTHEORYMUST: type === 'revenueConfirmation' ? compareCurrent?.ROYALTYTHEORYMUST : incomeObj?.ROYALTYTHEORYMUST,
                ROYALTYTHEORYOK: type === 'revenueConfirmation' ? compareCurrent?.ROYALTYTHEORYOK : incomeObj?.ROYALTYTHEORYOK,
                ROYALTYTHEORYMONTHLYMUST: type === 'revenueConfirmation' ? compareCurrent?.ROYALTYTHEORYMONTHLYMUST : incomeObj?.ROYALTYTHEORYMONTHLYMUST,
                GUARANTEERATIO: incomeObj?.GUARANTEERATIO,
                GUARANTEERATIOAMOUNT: incomeObj?.GUARANTEERATIOAMOUNT,
                GUARANTEERATIOINCOME: incomeObj?.GUARANTEERATIOINCOME,
                TaxRate: incomeObj?.TaxRate,
                MonthlyTotalIncome: incomeObj?.MonthlyTotalIncome
              }])

            } else {
              console.log('res.UnCompares', res.UnCompares);

              if (res.UnCompares && res.UnCompares.length > 0) {
                console.log('setFirstTableData5');
                setFirstTableData([{
                  ...compareCurrent,
                  MobilePay: sumObj?.MobilePay_Amount || incomeObj?.MOBILEPAY_AMOUNT,
                  CashPay: sumObj?.CashPay_Amount || incomeObj?.CASHPAY_AMOUNT,
                  CashPay_Amount: sumObj?.CashPay_Amount || incomeObj?.CASHPAY_AMOUNT,
                  MOBILEPAY_AMOUNT: sumObj?.MobilePay_Amount || incomeObj?.MOBILEPAY_AMOUNT,
                  MOBILEPAY_CORRECT: compareCurrent?.MOBILEPAY_CORRECT || incomeObj?.MOBILEPAY_CORRECT,
                  CASHPAY_CORRECT: compareCurrent?.CASHPAY_CORRECT || incomeObj?.CASHPAY_CORRECT,
                  type: '结算金额',
                  IndexDesc: compareCurrent?.IndexDesc || `${compareCurrent?.STARTDATE}-${compareCurrent?.ENDDATE}`,
                  REVENUEDAILY_AMOUNTTotal: compareCurrent?.REVENUEDAILY_AMOUNTTotal || incomeObj?.REVENUEDAILY_AMOUNTTotal,
                  ROYALTYTHEORYMUST: type === 'revenueConfirmation' ? compareCurrent?.ROYALTYTHEORYMUST : incomeObj?.ROYALTYTHEORYMUST,
                  ROYALTYTHEORYOK: type === 'revenueConfirmation' ? compareCurrent?.ROYALTYTHEORYOK : incomeObj?.ROYALTYTHEORYOK,
                  ROYALTYTHEORYMONTHLYMUST: type === 'revenueConfirmation' ? compareCurrent?.ROYALTYTHEORYMONTHLYMUST : incomeObj?.ROYALTYTHEORYMONTHLYMUST,
                  GUARANTEERATIO: incomeObj?.GUARANTEERATIO,
                  GUARANTEERATIOAMOUNT: incomeObj?.GUARANTEERATIOAMOUNT,
                  GUARANTEERATIOINCOME: incomeObj?.GUARANTEERATIOINCOME,
                  TaxRate: incomeObj?.TaxRate,
                  MonthlyTotalIncome: incomeObj?.MonthlyTotalIncome,
                  CurMonthRevenue: incomeObj?.CurMonthRevenue
                }])

                // 存一份初始的
                setDefaultFirstTableData({
                  ...compareCurrent,
                  MobilePay: sumObj?.MobilePay_Amount || incomeObj?.MOBILEPAY_AMOUNT,
                  CashPay: sumObj?.CashPay_Amount || incomeObj?.CASHPAY_AMOUNT,
                  CashPay_Amount: sumObj?.CashPay_Amount || incomeObj?.CASHPAY_AMOUNT,
                  MOBILEPAY_AMOUNT: sumObj?.MobilePay_Amount || incomeObj?.MOBILEPAY_AMOUNT,
                  MOBILEPAY_CORRECT: compareCurrent?.MOBILEPAY_CORRECT || incomeObj?.MOBILEPAY_CORRECT,
                  CASHPAY_CORRECT: compareCurrent?.CASHPAY_CORRECT || incomeObj?.CASHPAY_CORRECT,
                  type: '结算金额',
                  IndexDesc: compareCurrent?.IndexDesc || `${compareCurrent?.STARTDATE}-${compareCurrent?.ENDDATE}`,
                  REVENUEDAILY_AMOUNTTotal: compareCurrent?.REVENUEDAILY_AMOUNTTotal || incomeObj?.REVENUEDAILY_AMOUNTTotal,
                  ROYALTYTHEORYMUST: type === 'revenueConfirmation' ? compareCurrent?.ROYALTYTHEORYMUST : incomeObj?.ROYALTYTHEORYMUST,
                  ROYALTYTHEORYOK: type === 'revenueConfirmation' ? compareCurrent?.ROYALTYTHEORYOK : incomeObj?.ROYALTYTHEORYOK,
                  ROYALTYTHEORYMONTHLYMUST: type === 'revenueConfirmation' ? compareCurrent?.ROYALTYTHEORYMONTHLYMUST : incomeObj?.ROYALTYTHEORYMONTHLYMUST,
                  GUARANTEERATIO: incomeObj?.GUARANTEERATIO,
                  GUARANTEERATIOAMOUNT: incomeObj?.GUARANTEERATIOAMOUNT,
                  GUARANTEERATIOINCOME: incomeObj?.GUARANTEERATIOINCOME,
                  TaxRate: incomeObj?.TaxRate,
                  MonthlyTotalIncome: incomeObj?.MonthlyTotalIncome,
                  CurMonthRevenue: incomeObj?.CurMonthRevenue
                })
              } else {
                // 当没有差异的时候  默认出现精算金额 和结算金额一样的
                console.log('setFirstTableData6', [{
                  ...compareCurrent,
                  MobilePay: sumObj?.MobilePay_Amount || incomeObj?.MOBILEPAY_AMOUNT,
                  CashPay: sumObj?.CashPay_Amount || incomeObj?.CASHPAY_AMOUNT,
                  CashPay_Amount: sumObj?.CashPay_Amount || incomeObj?.CASHPAY_AMOUNT,
                  MOBILEPAY_AMOUNT: sumObj?.MobilePay_Amount || incomeObj?.MOBILEPAY_AMOUNT,
                  MOBILEPAY_CORRECT: compareCurrent?.MOBILEPAY_CORRECT || incomeObj?.MOBILEPAY_CORRECT,
                  CASHPAY_CORRECT: compareCurrent?.CASHPAY_CORRECT || incomeObj?.CASHPAY_CORRECT,
                  type: '结算金额',
                  IndexDesc: compareCurrent?.IndexDesc || `${compareCurrent?.STARTDATE}-${compareCurrent?.ENDDATE}`,
                  REVENUEDAILY_AMOUNTTotal: compareCurrent?.REVENUEDAILY_AMOUNTTotal || incomeObj?.REVENUEDAILY_AMOUNTTotal,
                  ROYALTYTHEORYMUST: type === 'revenueConfirmation' ? compareCurrent?.ROYALTYTHEORYMUST : incomeObj?.ROYALTYTHEORYMUST,
                  ROYALTYTHEORYOK: type === 'revenueConfirmation' ? compareCurrent?.ROYALTYTHEORYOK : incomeObj?.ROYALTYTHEORYOK,
                  ROYALTYTHEORYMONTHLYMUST: type === 'revenueConfirmation' ? compareCurrent?.ROYALTYTHEORYMONTHLYMUST : incomeObj?.ROYALTYTHEORYMONTHLYMUST,
                  GUARANTEERATIO: incomeObj?.GUARANTEERATIO,
                  GUARANTEERATIOAMOUNT: incomeObj?.GUARANTEERATIOAMOUNT,
                  GUARANTEERATIOINCOME: incomeObj?.GUARANTEERATIOINCOME,
                  TaxRate: incomeObj?.TaxRate,
                  MonthlyTotalIncome: incomeObj?.MonthlyTotalIncome,
                  CurMonthRevenue: incomeObj?.CurMonthRevenue
                }, {
                  ...compareCurrent,
                  MobilePay: sumObj?.MobilePay_Amount || incomeObj?.MOBILEPAY_AMOUNT,
                  CashPay: sumObj?.CashPay_Amount || incomeObj?.CASHPAY_AMOUNT,
                  CashPay_Amount: sumObj?.CashPay_Amount || incomeObj?.CASHPAY_AMOUNT,
                  MOBILEPAY_AMOUNT: sumObj?.MobilePay_Amount || incomeObj?.MOBILEPAY_AMOUNT,
                  MOBILEPAY_CORRECT: compareCurrent?.MOBILEPAY_CORRECT || incomeObj?.MOBILEPAY_CORRECT,
                  CASHPAY_CORRECT: compareCurrent?.CASHPAY_CORRECT || incomeObj?.CASHPAY_CORRECT,
                  type: '精算金额',
                  IndexDesc: compareCurrent?.IndexDesc || `${compareCurrent?.STARTDATE}-${compareCurrent?.ENDDATE}`,
                  REVENUEDAILY_AMOUNTTotal: compareCurrent?.REVENUEDAILY_AMOUNTTotal || incomeObj?.REVENUEDAILY_AMOUNTTotal,
                  ROYALTYTHEORYMUST: type === 'revenueConfirmation' ? compareCurrent?.ROYALTYTHEORYMUST : incomeObj?.ROYALTYTHEORYMUST,
                  ROYALTYTHEORYOK: type === 'revenueConfirmation' ? compareCurrent?.ROYALTYTHEORYOK : incomeObj?.ROYALTYTHEORYOK,
                  ROYALTYTHEORYMONTHLYMUST: type === 'revenueConfirmation' ? compareCurrent?.ROYALTYTHEORYMONTHLYMUST : incomeObj?.ROYALTYTHEORYMONTHLYMUST,
                  GUARANTEERATIO: incomeObj?.GUARANTEERATIO,
                  GUARANTEERATIOAMOUNT: incomeObj?.GUARANTEERATIOAMOUNT,
                  GUARANTEERATIOINCOME: incomeObj?.GUARANTEERATIOINCOME,
                  TaxRate: incomeObj?.TaxRate,
                  MonthlyTotalIncome: incomeObj?.MonthlyTotalIncome,
                  CurMonthRevenue: incomeObj?.CurMonthRevenue
                }]);
                setFirstTableData([{
                  ...compareCurrent,
                  MobilePay: sumObj?.MobilePay_Amount || incomeObj?.MOBILEPAY_AMOUNT,
                  CashPay: sumObj?.CashPay_Amount || incomeObj?.CASHPAY_AMOUNT,
                  CashPay_Amount: sumObj?.CashPay_Amount || incomeObj?.CASHPAY_AMOUNT,
                  MOBILEPAY_AMOUNT: sumObj?.MobilePay_Amount || incomeObj?.MOBILEPAY_AMOUNT,
                  MOBILEPAY_CORRECT: compareCurrent?.MOBILEPAY_CORRECT || incomeObj?.MOBILEPAY_CORRECT,
                  CASHPAY_CORRECT: compareCurrent?.CASHPAY_CORRECT || incomeObj?.CASHPAY_CORRECT,
                  type: '结算金额',
                  IndexDesc: compareCurrent?.IndexDesc || `${compareCurrent?.STARTDATE}-${compareCurrent?.ENDDATE}`,
                  REVENUEDAILY_AMOUNTTotal: compareCurrent?.REVENUEDAILY_AMOUNTTotal || incomeObj?.REVENUEDAILY_AMOUNTTotal,
                  ROYALTYTHEORYMUST: type === 'revenueConfirmation' ? compareCurrent?.ROYALTYTHEORYMUST : incomeObj?.ROYALTYTHEORYMUST,
                  ROYALTYTHEORYOK: type === 'revenueConfirmation' ? compareCurrent?.ROYALTYTHEORYOK : incomeObj?.ROYALTYTHEORYOK,
                  ROYALTYTHEORYMONTHLYMUST: type === 'revenueConfirmation' ? compareCurrent?.ROYALTYTHEORYMONTHLYMUST : incomeObj?.ROYALTYTHEORYMONTHLYMUST,
                  GUARANTEERATIO: incomeObj?.GUARANTEERATIO,
                  GUARANTEERATIOAMOUNT: incomeObj?.GUARANTEERATIOAMOUNT,
                  GUARANTEERATIOINCOME: incomeObj?.GUARANTEERATIOINCOME,
                  TaxRate: incomeObj?.TaxRate,
                  MonthlyTotalIncome: incomeObj?.MonthlyTotalIncome,
                  CurMonthRevenue: incomeObj?.CurMonthRevenue
                }, {
                  ...compareCurrent,
                  MobilePay: sumObj?.MobilePay_Amount || incomeObj?.MOBILEPAY_AMOUNT,
                  CashPay: sumObj?.CashPay_Amount || incomeObj?.CASHPAY_AMOUNT,
                  CashPay_Amount: sumObj?.CashPay_Amount || incomeObj?.CASHPAY_AMOUNT,
                  MOBILEPAY_AMOUNT: sumObj?.MobilePay_Amount || incomeObj?.MOBILEPAY_AMOUNT,
                  MOBILEPAY_CORRECT: compareCurrent?.MOBILEPAY_CORRECT || incomeObj?.MOBILEPAY_CORRECT,
                  CASHPAY_CORRECT: compareCurrent?.CASHPAY_CORRECT || incomeObj?.CASHPAY_CORRECT,
                  type: '精算金额',
                  IndexDesc: compareCurrent?.IndexDesc || `${compareCurrent?.STARTDATE}-${compareCurrent?.ENDDATE}`,
                  REVENUEDAILY_AMOUNTTotal: compareCurrent?.REVENUEDAILY_AMOUNTTotal || incomeObj?.REVENUEDAILY_AMOUNTTotal,
                  ROYALTYTHEORYMUST: type === 'revenueConfirmation' ? compareCurrent?.ROYALTYTHEORYMUST : incomeObj?.ROYALTYTHEORYMUST,
                  ROYALTYTHEORYOK: type === 'revenueConfirmation' ? compareCurrent?.ROYALTYTHEORYOK : incomeObj?.ROYALTYTHEORYOK,
                  ROYALTYTHEORYMONTHLYMUST: type === 'revenueConfirmation' ? compareCurrent?.ROYALTYTHEORYMONTHLYMUST : incomeObj?.ROYALTYTHEORYMONTHLYMUST,
                  GUARANTEERATIO: incomeObj?.GUARANTEERATIO,
                  GUARANTEERATIOAMOUNT: incomeObj?.GUARANTEERATIOAMOUNT,
                  GUARANTEERATIOINCOME: incomeObj?.GUARANTEERATIOINCOME,
                  TaxRate: incomeObj?.TaxRate,
                  MonthlyTotalIncome: incomeObj?.MonthlyTotalIncome,
                  CurMonthRevenue: incomeObj?.CurMonthRevenue
                }])

                // 存一份初始的
                setDefaultFirstTableData({
                  ...compareCurrent,
                  MobilePay: sumObj?.MobilePay_Amount || incomeObj?.MOBILEPAY_AMOUNT,
                  CashPay: sumObj?.CashPay_Amount || incomeObj?.CASHPAY_AMOUNT,
                  MOBILEPAY_CORRECT: compareCurrent?.MOBILEPAY_CORRECT || incomeObj?.MOBILEPAY_CORRECT,
                  CASHPAY_CORRECT: compareCurrent?.CASHPAY_CORRECT || incomeObj?.CASHPAY_CORRECT,
                  type: '结算金额',
                  IndexDesc: compareCurrent?.IndexDesc || `${compareCurrent?.STARTDATE}-${compareCurrent?.ENDDATE}`,
                  REVENUEDAILY_AMOUNTTotal: compareCurrent?.REVENUEDAILY_AMOUNTTotal || incomeObj?.REVENUEDAILY_AMOUNTTotal,
                  ROYALTYTHEORYMUST: type === 'revenueConfirmation' ? compareCurrent?.ROYALTYTHEORYMUST : incomeObj?.ROYALTYTHEORYMUST,
                  ROYALTYTHEORYOK: type === 'revenueConfirmation' ? compareCurrent?.ROYALTYTHEORYOK : incomeObj?.ROYALTYTHEORYOK,
                  ROYALTYTHEORYMONTHLYMUST: type === 'revenueConfirmation' ? compareCurrent?.ROYALTYTHEORYMONTHLYMUST : incomeObj?.ROYALTYTHEORYMONTHLYMUST,
                  GUARANTEERATIO: incomeObj?.GUARANTEERATIO,
                  GUARANTEERATIOAMOUNT: incomeObj?.GUARANTEERATIOAMOUNT,
                  GUARANTEERATIOINCOME: incomeObj?.GUARANTEERATIOINCOME,
                  TaxRate: incomeObj?.TaxRate,
                  MonthlyTotalIncome: incomeObj?.MonthlyTotalIncome,
                  CurMonthRevenue: incomeObj?.CurMonthRevenue
                })
              }
            }


          }
        }
        console.log('sumObj', sumObj);

        // // 补移动支付
        // if (sumObj.CURMOBILEPAY_AMOUNT < sumObj.MobilePay_Amount) {
        //   editFormRef.current?.setFieldsValue({
        //     MobilePayCorrect: sumObj.DifferenceMobile,
        //   })
        //   setShowRecalibration(true)
        // }
        // // 若有日结冲正 则当现金补进去
        // if ((sumObj.CURCASHPAY_AMOUNT < sumObj.CashPay_Amount) || compareCurrent?.PERIOD_STATE === 1) {
        //   editFormRef.current?.setFieldsValue({
        //     CashPayCorrect: (sumObj.DifferenceRowSum - sumObj.DifferenceMobile) + (compareCurrent?.PERIOD_STATE === 1 ? (res.CompareTotal.Correct_Amount || 0) : 0),
        //   })
        //   setShowRecalibration(true)
        // }

        // // 合计出现差额时
        // // 因为会有情况 移动支付 和 现金支付都没差额 但是合计会出现差额
        // if(sumObj.DifferenceRowSum && sumObj.DifferenceRowSum>0){
        //   setShowRecalibration(true)
        //   if(sumObj.DifferenceCash===0 && sumObj.DifferenceMobile===0){
        //     editFormRef.current?.setFieldsValue({
        //       CashPayCorrect:sumObj.DifferenceRowSum - sumObj.DifferenceMobile
        //     })
        //   }
        // }

        if (sumObj.DifferenceRowSum && sumObj.DifferenceRowSum > 0) {
          // 显示
          setShowRecalibration(true)
          // 若有日结冲正 则当现金补进去
          // 一会要把日结冲正加到现金冲正里面 一会不用 先留着
          if (compareCurrent?.PERIOD_STATE === 1) {
            editFormRef.current?.setFieldsValue({
              // + (compareCurrent?.PERIOD_STATE === 1 ? (sumObj?.Correct_Amount || 0) : 0),
              CashPayCorrect: getMoney(sumObj.DifferenceRowSum - sumObj.DifferenceMobile),
              MobilePayCorrect: sumObj.DifferenceMobile
            })
          } else {
            editFormRef.current?.setFieldsValue({
              CashPayCorrect: getMoney(sumObj.DifferenceRowSum - sumObj.DifferenceMobile),
              MobilePayCorrect: sumObj.DifferenceMobile
            })
          }
        }




        console.log('list321321321321321312', res)
        setTableAllData(list)
        // if (res.UnCompares && res.UnCompares.length > 0) {
        //   setTableDifferenceData([{ ...res.CompareTotal }, ...res.UnCompares])
        // } else {
        //   setTableDifferenceData([])
        // }
        if (res.UnCompares && res.UnCompares.length > 0) {
          setHandleHaveDifference(true)
          // 算差异的合计
          let CURCASHPAY_AMOUNTSum: number = 0
          let CURMOBILEPAY_AMOUNTSum: number = 0
          let CashPay_AmountSum: number = 0
          let Cash_CorrectSum: number = 0
          let Correct_AmountSum: number = 0
          let DailyRowSumSum: number = 0
          let DifferenceCashSum: number = 0
          const DifferenceMobileSum: number = 0
          let DifferenceRowSumSum: number = 0
          let MobilePay_AmountSum: number = 0
          let Mobile_CorrectSum: number = 0
          let ProjectRowSumSum: number = 0
          res.UnCompares.forEach((item: any) => {
            CURCASHPAY_AMOUNTSum += item.CURCASHPAY_AMOUNT
            CURMOBILEPAY_AMOUNTSum += item.CURMOBILEPAY_AMOUNT
            CashPay_AmountSum += item.CashPay_Amount
            Cash_CorrectSum += item.Cash_Correct
            Correct_AmountSum += item.Correct_Amount
            DailyRowSumSum += item.DailyRowSum
            DifferenceCashSum += item.DifferenceCash
            DifferenceMobileSum + -item.DifferenceMobile
            DifferenceRowSumSum += item.DifferenceRowSum
            MobilePay_AmountSum += item.MobilePay_Amount
            Mobile_CorrectSum += item.Mobile_Correct
            ProjectRowSumSum += item.ProjectRowSum
          })
          const unSumObj: any = {
            STATISTICS_DATE: '合计',
            CURCASHPAY_AMOUNT: CURCASHPAY_AMOUNTSum,
            CURMOBILEPAY_AMOUNT: CURMOBILEPAY_AMOUNTSum,
            CashPay_Amount: CashPay_AmountSum,
            Cash_Correct: Cash_CorrectSum,
            // Correct_Amount: Correct_AmountSum,
            DailyRowSum: DailyRowSumSum,
            DifferenceCash: DifferenceCashSum,
            DifferenceMobile: DifferenceMobileSum,
            DifferenceRowSum: DifferenceRowSumSum,
            MobilePay_Amount: MobilePay_AmountSum,
            Mobile_Correct: Mobile_CorrectSum,
            ProjectRowSum: ProjectRowSumSum,
            // 日结冲正 只有CompareTotal里面会返回 单行数据里不会返回 差异的合计和全部的合计 都要显示
            Correct_Amount: res.CompareTotal.Correct_Amount
          }

          setTableData([unSumObj, ...res.UnCompares])
          setTableDifferenceData([unSumObj, ...res.UnCompares])
        } else {
          setHandleHaveDifference(false)
          setTableDifferenceData([])
          setTableData([])
        }
      }
      console.log('res.UnCompares', res.UnCompares)
      // 说明数据里面是存在差异的 那么就调用这个接口
      // 到此上面已经让下面的表格有值了的 只不过有了差异去调用新的接口 如果新的接口有内容 那就会重新赋值表格内容



      // && compareCurrent.BusinessType!==2000
      if (res.UnCompares && res.UnCompares.length > 0) {

        const time: any = []
        res.UnCompares.forEach((item: any) => {
          // 差额有不是0的那天 就跑
          if (item.DifferenceCash !== 0 || item.DifferenceMobile !== 0 || item.DifferenceRowSum !== 0) {
            time.push(item.STATISTICS_DATE)
            // if (time) {
            //   time += `,${item.STATISTICS_DATE}`
            // } else {
            //   time = item.STATISTICS_DATE
            // }
          }
        })
        console.log('res', res);
        // setTableDifferenceData(res.UnCompares)

        if (time && time.length > 0) {
          const allLength: number = time.length
          // 要调几次
          const count: number = Math.ceil(allLength / 30)
          console.log('count', count);
          const resultList: any = []
          for (let i = 0; i < count; i++) {
            // 这一次的30条
            const nowList: any = []
            const idStr: string = time.slice(30 * i, 30 * (i + 1)).toString()
            console.log('idStr', idStr);
            const req: any = {
              StatisticsDate: idStr,
              ServerpartId: compareCurrent?.SERVERPART_ID || '',
              ServerpartShopId: compareCurrent?.Id || '',
              BusinessProjectId: compareCurrent?.BUSINESSPROJECT_ID || ''
            }
            const CorrectDataRes = await handleCorrectDailyEndaccount(req)
            const CorrectData = CorrectDataRes.List
            console.log('CorrectData', CorrectData);
            if (CorrectDataRes.OtherData) {
              fatherActionRef.current?.reload()
            }
            if (CorrectData && CorrectData.length > 0) {

              // 只要CorrectData有值 就调用固化数据的内容
              const solidReq: any = {
                StatisticsMonth: compareCurrent?.STATISTICS_MONTH,
                ServerpartId: compareCurrent?.SERVERPART_ID || '',
                ProjectId: compareCurrent?.BUSINESSPROJECT_ID || ''
              }
              const solidData: any = await handleSolidProjectRevenue(solidReq)
              console.log('solidData', solidData);


              let DiffCashPaySum: number = 0
              let DiffMobilePaySum: number = 0
              CorrectData.forEach((item: any) => {
                DiffCashPaySum += Number(item.key)
                DiffMobilePaySum += Number(item.value)
              })
              // res.Compares
              // res.CompareTotal
              res.Compares.forEach((item: any) => {
                CorrectData.forEach((subItem: any) => {
                  if (item.STATISTICS_DATE === subItem.label) {
                    item.MobilePay_Amount += Number(subItem.value)
                    item.Mobile_Correct = Number(subItem.value)
                    item.CashPay_Amount += Number(subItem.key)
                    item.Cash_Correct = Number(subItem.key)
                    item.DailyRowSum = item.DailyRowSum + Number(subItem.key) + Number(subItem.value)
                    item.DifferenceRowSum = item.DifferenceRowSum + Number(subItem.key) + Number(subItem.value)
                  }
                })
              })
              res.CompareTotal.MobilePay_Amount = res.CompareTotal.MobilePay_Amount + Number(DiffMobilePaySum)
              res.CompareTotal.Mobile_Correct = Number(DiffMobilePaySum)
              res.CompareTotal.CashPay_Amount = res.CompareTotal.CashPay_Amount + Number(DiffCashPaySum)
              res.CompareTotal.Cash_Correct = Number(DiffCashPaySum)
              res.CompareTotal.DailyRowSum = res.CompareTotal.DailyRowSum + Number(DiffCashPaySum) + Number(DiffMobilePaySum)
              res.CompareTotal.DifferenceRowSum = res.CompareTotal.DifferenceRowSum + Number(DiffCashPaySum) + Number(DiffMobilePaySum)

              setTableAllData([res.CompareTotal, ...res.Compares])


              res.UnCompares.forEach((item: any) => {
                CorrectData.forEach((subItem: any) => {
                  if (item.STATISTICS_DATE === subItem.label) {
                    item.MobilePay_Amount += Number(subItem.value)
                    item.Mobile_Correct = Number(subItem.value)
                    item.CashPay_Amount += Number(subItem.key)
                    item.Cash_Correct = Number(subItem.key)
                    item.DailyRowSum = item.DailyRowSum + Number(subItem.key) + Number(subItem.value)
                    item.DifferenceRowSum = item.DifferenceRowSum + Number(subItem.key) + Number(subItem.value)
                  }
                })
              })
              // 算差异的合计
              let CURCASHPAY_AMOUNTSum: number = 0
              let CURMOBILEPAY_AMOUNTSum: number = 0
              let CashPay_AmountSum: number = 0
              let Cash_CorrectSum: number = 0
              let Correct_AmountSum: number = 0
              let DailyRowSumSum: number = 0
              let DifferenceCashSum: number = 0
              const DifferenceMobileSum: number = 0
              let DifferenceRowSumSum: number = 0
              let MobilePay_AmountSum: number = 0
              let Mobile_CorrectSum: number = 0
              let ProjectRowSumSum: number = 0
              res.UnCompares.forEach((item: any) => {
                CURCASHPAY_AMOUNTSum += item.CURCASHPAY_AMOUNT
                CURMOBILEPAY_AMOUNTSum += item.CURMOBILEPAY_AMOUNT
                CashPay_AmountSum += item.CashPay_Amount
                Cash_CorrectSum += item.Cash_Correct
                Correct_AmountSum += item.Correct_Amount
                DailyRowSumSum += item.DailyRowSum
                DifferenceCashSum += item.DifferenceCash
                DifferenceMobileSum + -item.DifferenceMobile
                DifferenceRowSumSum += item.DifferenceRowSum
                MobilePay_AmountSum += item.MobilePay_Amount
                Mobile_CorrectSum += item.Mobile_Correct
                ProjectRowSumSum += item.ProjectRowSum
              })
              const unSumObj: any = {
                STATISTICS_DATE: '合计',
                CURCASHPAY_AMOUNT: CURCASHPAY_AMOUNTSum,
                CURMOBILEPAY_AMOUNT: CURMOBILEPAY_AMOUNTSum,
                CashPay_Amount: CashPay_AmountSum,
                Cash_Correct: Cash_CorrectSum,
                // Correct_Amount: Correct_AmountSum,
                DailyRowSum: DailyRowSumSum,
                DifferenceCash: DifferenceCashSum,
                DifferenceMobile: DifferenceMobileSum,
                DifferenceRowSum: DifferenceRowSumSum,
                MobilePay_Amount: MobilePay_AmountSum,
                Mobile_Correct: Mobile_CorrectSum,
                ProjectRowSum: ProjectRowSumSum,
                // 日结冲正 只有CompareTotal里面会返回 单行数据里不会返回 差异的合计和全部的合计 都要显示
                Correct_Amount: res.CompareTotal.Correct_Amount
              }
              setTableData([unSumObj, ...res.UnCompares])
              setTableDifferenceData([unSumObj, ...res.UnCompares])
              console.log('res111', [unSumObj, ...res.UnCompares]);

            }
          }


          console.log('resultList', resultList);
        }

        const CorrectData: any = []
        const isRun: boolean = false
        console.log('time', time)
        // if (time) {
        //   const req: any = {
        //     StatisticsDate: time,
        //     ServerpartId: compareCurrent?.SERVERPART_ID || '',
        //     ServerpartShopId: compareCurrent?.Id || '',
        //     // ProjectId: compareCurrent?.BUSINESSPROJECT_ID || ''
        //   }
        //   CorrectData = await handleCorrectDailyEndaccount(req)
        //   isRun = true
        // }

        // if (CorrectData && CorrectData.length > 0 || isRun) {
        //   const newRes: any = []
        //   res.UnCompares.forEach((item: any) => {
        //     if (item.STATISTICS_DATE !== '合计') {
        //       newRes.push(item)
        //     }
        //   })
        //   console.log('CorrectData', CorrectData)
        //   console.log('newRes', newRes)
        //   // 自然日移动支付合计
        //   let MobilePay_AmountSum: number = 0
        //   // 自然日现金合计
        //   let CashPay_AmountSum: number = 0
        //   // 营业额移动支付合计
        //   let CURMOBILEPAY_AMOUNTSum: number = 0
        //   // 营业额现金合计
        //   let CURCASHPAY_AMOUNTSum: number = 0
        //   // 移动支付补齐差异的合计
        //   let MobliePay_AfterSum: number = 0
        //   // 现金支付补齐差异的合计
        //   let CashPay_AfterSum: number = 0
        //   // 后端给的差额累计
        //   let Mobile_CorrectSum: number = 0
        //   let Cash_CorrectSum: number = 0

        //   // // 移动支付差额合计
        //   // let differenceMobileSum: number = 0
        //   // // 现金差额合计
        //   // let differenceCashSum: number = 0

        //   newRes.forEach((item: any) => {
        //     MobilePay_AmountSum += item.MobilePay_Amount
        //     CashPay_AmountSum += item.CashPay_Amount
        //     CURMOBILEPAY_AMOUNTSum += item.CURMOBILEPAY_AMOUNT
        //     CURCASHPAY_AMOUNTSum += item.CURCASHPAY_AMOUNT

        //     item.differenceCash = item.CashPay_Amount - item.CURCASHPAY_AMOUNT
        //     item.differenceMobile = numeral(item.MobilePay_Amount - item.CURMOBILEPAY_AMOUNT).format('0.00')

        //     MobliePay_AfterSum += Number(item.MobilePay_AmountRect || 0)
        //     CashPay_AfterSum += Number(item.CashPay_AmountRect || 0)
        //     Mobile_CorrectSum += Number(item.Mobile_Correct || 0)
        //     Cash_CorrectSum += Number(item.Cash_Correct || 0)
        //     item.DailyRowSum = item.MobilePay_Amount + item.CashPay_Amount
        //     item.ProjectRowSum = item.CURMOBILEPAY_AMOUNT + item.CURCASHPAY_AMOUNT
        //     const differenceNumber: number = (item?.Mobile_Correct || item?.MobilePay_AmountRect || 0) + (item?.Cash_Correct || item?.CashPay_AmountRect || 0)
        //     // item.DifferenceRowSum = item.DailyRowSum - item.ProjectRowSum
        //     item.DifferenceRowSum = item.DifferenceRowSum
        //   })
        //   // 合计 需要显示老的值+补齐差异的值 但是差额又要新算的值 所以要修改一下合计对象
        //   const Pay_AfterSum: number = MobliePay_AfterSum + CashPay_AfterSum + Mobile_CorrectSum + Cash_CorrectSum

        //   const sumObj: any = {
        //     STATISTICS_DATE: '合计',
        //     // 移动支付交易自然日
        //     MobilePay_Amount: MobilePay_AmountSum,
        //     // 现金支付交易自然日
        //     CashPay_Amount: CashPay_AmountSum,

        //     CURMOBILEPAY_AMOUNT: CURMOBILEPAY_AMOUNTSum,
        //     CURCASHPAY_AMOUNT: CURCASHPAY_AMOUNTSum,
        //     // 移动支付差额
        //     differenceMobile: MobilePay_AmountSum + (MobliePay_AfterSum || 0) - CURMOBILEPAY_AMOUNTSum,
        //     // 现金支付差额
        //     differenceCash: CashPay_AmountSum + (CashPay_AfterSum || 0) - CURCASHPAY_AMOUNTSum,
        //     // 合计自然日
        //     DailyRowSum: MobilePay_AmountSum + (MobliePay_AfterSum || 0) + CashPay_AmountSum + (CashPay_AfterSum || 0),

        //     ProjectRowSum: CURMOBILEPAY_AMOUNTSum + CURCASHPAY_AMOUNTSum,
        //     // 合计差额
        //     // DifferenceRowSum: (MobilePay_AmountSum + CashPay_AmountSum) - (CURMOBILEPAY_AMOUNTSum + CURCASHPAY_AMOUNTSum),
        //     DifferenceRowSum: res.CompareTotal.DifferenceRowSum,

        //     MobilePay_AmountRect: MobliePay_AfterSum || 0,
        //     CashPay_AmountRect: CashPay_AfterSum || 0,
        //     Mobile_Correct: res.CompareTotal.Mobile_Correct,
        //     Cash_Correct: res.CompareTotal.Cash_Correct,
        //     Correct_Amount: res.CompareTotal.Correct_Amount,
        //   }

        //   let MobilePayCorrectDesc: string = ''
        //   let CashPayCorrectDesc: string = ''
        //   if (MobilePay_AmountSum < CURMOBILEPAY_AMOUNTSum) {
        //     MobilePayCorrectDesc = '自然日移动支付小于项目拆分移动支付，以项目拆分为准，无需补齐'
        //   } else if (MobilePay_AmountSum === CURMOBILEPAY_AMOUNTSum) {
        //     MobilePayCorrectDesc = '自然日移动支付等于项目拆分移动支付，补齐金额为0'
        //   } else {
        //     MobilePayCorrectDesc = `自然日移动支付大于项目拆分移动支付，建议补齐金额${numeral(MobilePay_AmountSum - CURMOBILEPAY_AMOUNTSum).format('0.00')}`
        //   }

        //   if (CashPay_AmountSum < CURCASHPAY_AMOUNTSum) {
        //     CashPayCorrectDesc = '自然日现金支付小于项目拆分现金支付，以项目拆分为准，无需补齐'
        //   } else if (CashPay_AmountSum === CURCASHPAY_AMOUNTSum) {
        //     CashPayCorrectDesc = '自然日现金支付小于项目拆分现金支付，补齐金额为0'
        //   } else {
        //     CashPayCorrectDesc = `自然日现金支付大于项目拆分现金支付，建议补齐金额${numeral(CashPay_AmountSum - CURCASHPAY_AMOUNTSum).format('0.00')}`
        //   }


        //   // CashPayCorrectDesc: `建议补齐移动支付差额${numeral(sumObj.MobilePay_Amount - sumObj.CURMOBILEPAY_AMOUNT).format('0.00')}元`
        //   // CashPayCorrectDesc: `建议补齐现金支付差额${numeral(sumObj.CashPay_Amount - sumObj.CURCASHPAY_AMOUNT).format('0.00')}元`
        //   editFormRef.current?.setFieldsValue({
        //     MobilePayCorrectDesc,
        //     CashPayCorrectDesc,
        //   })

        //   newRes.unshift(sumObj)

        //   setTableDifferenceData(newRes)
        //   setTableData(newRes)
        // }
      }
    }
    setCompareTableLoading(false)

  }

  // oldObj 结算金额的全部值

  const getCalibrationTableData = async (MobilePayCorrect: number, CashPayCorrect: number, cumulativeValue?: any, oldObj?: any) => {
    console.log('MobilePayCorrect', MobilePayCorrect);
    console.log('CashPayCorrect', CashPayCorrect);


    // cumulativeValue 为累计值
    setTableSecondLoading(true)
    setMobilePayCorrectNumber(MobilePayCorrect)
    setCashPayCorrectNumber(CashPayCorrect)
    const req: any = {
      BusinessProjectId: compareCurrent?.BUSINESSPROJECT_ID,
      StatisticsMonth: compareCurrent?.STATISTICS_MONTH ? moment(compareCurrent?.STATISTICS_MONTH).format('YYYYMM') : monthTime ? moment(monthTime).format('YYYYMM') : '',
      ShopRoyaltyId: compareCurrent?.ShopRoyaltyId,
      MobilePayCorrect: MobilePayCorrect || 0,
      CashPayCorrect: CashPayCorrect || 0
    }
    console.log('reqreqrsdasda', req);

    const data = await handleGetProjectPeriodIncome(req)
    console.log('data3232', data)
    console.log('compareCurrent3232', compareCurrent)
    if (data && data.length > 0) {
      const secondItem: any = data[0]

      // secondItem.type='精算金额'
      if (compareCurrent?.Approvalstate === 9) {
        console.log('setFirstTableData7');
        setFirstTableData([{
          // ...compareCurrent,
          ...secondItem,
          // IndexDesc:compareCurrent?.IndexDesc,
          IndexDesc: `${compareCurrent?.STARTDATE}-${compareCurrent?.ENDDATE}`,
          MOBILEPAY_CORRECT: '',
          CASHPAY_CORRECT: '',
          MobilePay: cumulativeValue?.CURMOBILEPAY_AMOUNT - (compareCurrent?.MOBILEPAY_CORRECT || 0),
          CashPay: cumulativeValue?.CURCASHPAY_AMOUNT - (compareCurrent?.CASHPAY_CORRECT || 0),

          type: '结算金额'
        }, {
          // ...secondItem,
          ...compareCurrent,
          type: '精算金额',
          // IndexDesc: compareCurrent.IndexDesc,
          IndexDesc: `${compareCurrent?.STARTDATE}-${compareCurrent?.ENDDATE}`,
          MOBILEPAY_CORRECT: compareCurrent?.MOBILEPAY_CORRECT,
          CASHPAY_CORRECT: compareCurrent?.CASHPAY_CORRECT,
          RevenueTrend: compareCurrent?.REVENUEDAILY_AMOUNTTotal > secondItem?.REVENUEDAILY_AMOUNTTotal ? true : compareCurrent?.REVENUEDAILY_AMOUNTTotal < secondItem?.REVENUEDAILY_AMOUNTTotal ? false : null,
          REVENUEDAILY_AMOUNTTotal: compareCurrent?.REVENUEDAILY_AMOUNTTotal,
          MobilePay: cumulativeValue?.CURMOBILEPAY_AMOUNT,
          CashPay: cumulativeValue?.CURCASHPAY_AMOUNT,

          ROYALTYTrend: compareCurrent?.ROYALTYTHEORYMONTHLYMUST > secondItem?.ROYALTYTHEORYMONTHLYMUST ? true : compareCurrent?.ROYALTYTHEORYMONTHLYMUST < secondItem?.ROYALTYTHEORYMONTHLYMUST ? false : null
        }])
      } else {
        console.log('compareCurrent', compareCurrent);

        if (compareCurrent?.CASHPAY_CORRECT || compareCurrent?.MOBILEPAY_CORRECT || (compareCurrent?.Approvalstate > 0 && compareCurrent?.Approvalstate < 9)) {
          // 老的值
          const req: any = {
            BusinessProjectId: compareCurrent?.BUSINESSPROJECT_ID,
            StatisticsMonth: compareCurrent?.STATISTICS_MONTH ? moment(compareCurrent?.STATISTICS_MONTH).format('YYYYMM') : monthTime ? moment(monthTime).format('YYYYMM') : '',
            ShopRoyaltyId: compareCurrent?.ShopRoyaltyId,
          }
          const income = await handleGetProjectPeriodIncome(req)
          console.log('income2', income);
          setMonthId(income[0].bizpsplitMonthId)
          console.log('oldObj', oldObj);
          // 精算金额
          let actuaryObj: any = {}
          if (income && income.length > 0) {
            actuaryObj = income[0]
          }
          setClickCalibration(true)
          console.log('setFirstTableData8');
          setFirstTableData([
            {
              ...actuaryObj,
              ...oldObj,
              type: '结算金额',
              CASHPAY_CORRECT: compareCurrent?.CASHPAY_CORRECT,
              MOBILEPAY_CORRECT: compareCurrent?.MOBILEPAY_CORRECT,
              MobilePay: oldObj?.MOBILEPAY_AMOUNT || actuaryObj?.MOBILEPAY_AMOUNT,
              CashPay: oldObj?.CASHPAY_AMOUN || actuaryObj?.CASHPAY_AMOUNT,
              IndexDesc: compareCurrent?.IndexDesc || `${compareCurrent?.STARTDATE}-${compareCurrent?.ENDDATE}`,
            },
            {

              ...secondItem,
              type: '精算金额',
              IndexDesc: compareCurrent?.IndexDesc || `${compareCurrent?.STARTDATE}-${compareCurrent?.ENDDATE}`,
              // IndexDesc: secondItem?.IndexDesc,
              MOBILEPAY_CORRECT: MobilePayCorrect,
              CASHPAY_CORRECT: CashPayCorrect,
              MobilePay: secondItem?.MOBILEPAY_AMOUNT,
              CashPay: secondItem?.CASHPAY_AMOUNT,
              // REVENUEDAILY_AMOUNTTotal:actuaryObj?.ACCREVENUE_AMOUNT,
              // REVENUEDAILY_AMOUNTTotal: cumulativeValue?.CURMOBILEPAY_AMOUNT + (compareCurrent?.MOBILEPAY_CORRECT || 0) + cumulativeValue?.CURCASHPAY_AMOUNT + (compareCurrent?.CASHPAY_CORRECT || 0),
              RevenueTrend: actuaryObj?.REVENUEDAILY_AMOUNTTotal > secondItem?.REVENUEDAILY_AMOUNTTotal ? false : actuaryObj?.REVENUEDAILY_AMOUNTTotal < secondItem?.REVENUEDAILY_AMOUNTTotal ? true : null,
              ROYALTYTrend: actuaryObj?.ROYALTYTHEORYMONTHLYMUST > secondItem?.ROYALTYTHEORYMONTHLYMUST ? false : actuaryObj?.ROYALTYTHEORYMONTHLYMUST < secondItem?.ROYALTYTHEORYMONTHLYMUST ? true : null
            }])
        } else {
          setClickCalibration(true)
          const formRes = editFormRef.current?.getFieldValue()

          if (handleHaveDifference) {
            setFirstTableData([{
              ...defaultFirstTableData,
            }, {
              ...secondItem,
              type: '精算金额',
              IndexDesc: defaultFirstTableData?.IndexDesc,
              MOBILEPAY_CORRECT: formRes?.MobilePayCorrect,
              CASHPAY_CORRECT: formRes?.CashPayCorrect,
              RevenueTrend: secondItem?.REVENUEDAILY_AMOUNTTotal > defaultFirstTableData?.REVENUEDAILY_AMOUNTTotal ? true : secondItem?.REVENUEDAILY_AMOUNTTotal < defaultFirstTableData?.REVENUEDAILY_AMOUNTTotal ? false : null,
              MobilePay: bottomTableSum?.CURMOBILEPAY_AMOUNT + (formRes?.MobilePayCorrect || 0),
              CashPay: bottomTableSum?.CURCASHPAY_AMOUNT + (formRes?.CashPayCorrect || 0),
              ROYALTYTrend: secondItem?.ROYALTYTHEORYMONTHLYMUST > defaultFirstTableData?.ROYALTYTHEORYMONTHLYMUST ? true : secondItem?.ROYALTYTHEORYMONTHLYMUST < defaultFirstTableData?.ROYALTYTHEORYMONTHLYMUST ? false : null
            }])
          }

        }
      }
    }
    if (handleGetRefreshTableData) {
      handleGetRefreshTableData()
    }
    setTableSecondLoading(false)
  }

  // 分月份去交易精算 递归
  const handleGetOnceMonth = async (now: number, all: number, compareCurrent?: any) => {
    console.log('now', now);
    console.log('all', all);
    if (now > all) {
      return true
    }
    let req: any = {}
    if (new Date(moment(compareCurrent?.startTime).add(now - 1, 'month').endOf('month').format('YYYY-MM-DD')).getTime() <= new Date(moment(compareCurrent?.STATISTICS_MONTH).endOf('month').format('YYYY-MM-DD')).getTime()) {
      if (new Date(moment(compareCurrent?.startTime).add(now - 1, 'month').endOf('month').format('YYYY-MM-DD')).getTime() > new Date(moment(compareCurrent?.endTime).format('YYYY-MM-DD')).getTime()) {
        req = {
          StartDate: moment(compareCurrent?.startTime).add(now - 1, 'month').startOf('month').format('YYYY-MM-DD'),
          EndDate: moment(compareCurrent?.endTime).format('YYYY-MM-DD'),
          ProjectId: compareCurrent?.BUSINESSPROJECT_ID,
          // OutBusinessType: 1000
        }
      } else {
        req = {
          StartDate: moment(compareCurrent?.startTime).add(now - 1, 'month').startOf('month').format('YYYY-MM-DD'),
          EndDate: moment(compareCurrent?.startTime).add(now - 1, 'month').endOf('month').format('YYYY-MM-DD'),
          ProjectId: compareCurrent?.BUSINESSPROJECT_ID,
          // OutBusinessType: 1000
        }
      }
    } else {
      return true
    }

    setLoadingText(`正在精算${moment(compareCurrent?.startTime).add(now - 1, 'month').format('YYYYMM')}月数据，请稍后...`)
    const data = await handleAgain(req)
    // const data = await handleTest()
    // let num: number = now + 1
    // return handleGetOnceMonth(num, all, compareCurrent)
    if (data.Result_Code === 100) {
      const num: number = now + 1
      return handleGetOnceMonth(num, all, compareCurrent)
    }
    message.error(data.Result_Desc)
    return false


  }
  const handleTest = async () => {
    setTimeout(() => {
      return { Result_Code: 100 }
    }, 1000)
  }


  // 先等第三个表格的水电物业费拿到数据之后 再去拿第一个表格的数据
  const handleGetFirstTableData = async (params?: any) => {
    setTopTableLoading(true)
    const res: any = []
    const req: any = {
      ServerpartIds: compareCurrent?.SERVERPART_ID,
      ShopRoyaltyId: compareCurrent?.ShopRoyaltyId,
      BusinessProjectId: compareCurrent?.BUSINESSPROJECT_ID,
      startDate: compareCurrent.STATISTICS_MONTH ? moment(compareCurrent.STATISTICS_MONTH).format('YYYYMM') : '',
      endDate: compareCurrent.STATISTICS_MONTH ? moment(compareCurrent.STATISTICS_MONTH).format('YYYYMM') : '',
    }
    console.log('req', req);

    const data = await handleGetTableRevenueRecognition(req)
    console.log('data21dwqjfhsajkfhdksja', data);
    if (data && data.length > 0) {
      const list: any = wrapTreeNode(data)
      console.log('list', list);
      let obj: any = {}
      if (list && list.length > 0) {
        obj = list[0].children[0].children[0]
      }
      obj.currentMonth = compareCurrent.STATISTICS_MONTH ? moment(compareCurrent.STATISTICS_MONTH).format('YYYYMM') : '',
        obj.CASHPAY_AMOUNT = params?.CASHPAY_AMOUNT
      obj.MOBILEPAY_AMOUNT = params?.MOBILEPAY_AMOUNT
      obj.IndexDesc = params?.IndexDesc
      res.push(obj)
    }
    setTopTableLoading(false)
    setTopTable(res)
    console.log('reqrewrw', res);
  }

  // 拿到附件列表
  const handleGetFile = async () => {
    if (!compareCurrent?.BUSINESSAPPROVAL_ID) {
      return
    }
    const req: any = {
      TableId: compareCurrent?.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 printColumns: any = [
    {
      title: <div style={{ textAlign: 'center' }}>期限</div>,
      dataIndex: 'PeriodDescBig',
      children: [
        {
          dataIndex: 'IndexStr',
          title: <div style={{ textAlign: 'center' }}>期数</div>,
          align: 'center',
          hideInSearch: true
        },
        {
          title: <div style={{ textAlign: 'center' }}>期限</div>,
          dataIndex: 'IndexDesc',
          align: 'left',
          hideInSearch: true,
          // render: (_, record) => {
          //   return record?.IndexDesc !== '合计' && record?.IndexDesc === '精算数据' ?
          //     <span>{`${record?.StartDate}-${record?.EndDate}`}</span> :
          //     <span>{`${record?.IndexDesc}`}</span>
          // }
        }
      ]
    },
    {
      title: <div style={{ textAlign: 'center' }}>租金信息</div>,
      dataIndex: 'PeriodDescBig',
      hideInSearch: true,
      children: [
        {
          title: <div style={{ textAlign: 'center' }}>保底/固定租金</div>,
          dataIndex: 'RENTFEE',
          valueType: 'digit',
          align: 'right',
          hideInSearch: true,
        },
        {
          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: 'CASHPAY_AMOUNT',
          valueType: 'digit',
          align: 'right',
          hideInSearch: true,
        },
        {
          title: <div style={{ textAlign: 'center' }}>微支付</div>,
          dataIndex: 'MOBILEPAY_AMOUNT',
          valueType: 'digit',
          align: 'right',
          hideInSearch: true,
        },
        {
          title: <div style={{ textAlign: 'center' }}>小计</div>,
          dataIndex: 'REVENUEDAILY_AMOUNTTotal',
          valueType: 'digit',
          align: 'right',
          hideInSearch: true,
          render: (_, record) => {
            return <span>{record?.REVENUEDAILY_AMOUNTTotal ? numeral(getMoney(record?.REVENUEDAILY_AMOUNTTotal)).format('0,0.00') : ''}</span>
          }
        },
        {
          title: <div style={{ textAlign: 'center' }}>提成金额</div>,
          dataIndex: 'GUARANTEERATIOAMOUNT',
          valueType: 'digit',
          align: 'right',
          hideInSearch: true,
          // render: (_, record) => {
          //   return record.RevenueAmount * (record.GuaranteeRatio / 100)
          // }
        },
      ]
    },
    {
      title: <div style={{ textAlign: 'center' }}>业主收款</div>,
      dataIndex: 'BANKACCOUNT_AMOUNT',
      valueType: 'digit',
      align: 'right',
      hideInSearch: true,
    },
    {
      title: <div style={{ textAlign: 'center' }}>应收租金</div>,
      dataIndex: 'ROYALTYTHEORYMUST',
      valueType: 'digit',
      align: 'right',
      hideInSearch: true,
    },
    {
      title: <div style={{ textAlign: 'center' }}>应收费用</div>,
      dataIndex: 'SHOPEXPENSE_AMOUNT',
      valueType: 'digit',
      align: 'right',
      hideInSearch: true,
      render: (_, record) => {
        return numeral(record?.SHOPEXPENSE_AMOUNT).format('0,0.00')
      }
    },
    {
      title: <div style={{ textAlign: 'center' }}>已缴费用</div>,
      dataIndex: 'PAID_AMOUNTSum',
      valueType: 'digit',
      align: 'right',
      hideInSearch: true,
      // render: (_, record) => {
      //   return record?.PAID_AMOUNT || ''
      // },
      children: [
        {
          title: <div style={{ textAlign: 'center' }}>合计</div>,
          dataIndex: 'PAID_AMOUNT',
          valueType: 'digit',
          align: 'right',
          hideInSearch: true,
          render: (_, record) => {
            return record?.PAID_AMOUNT ? numeral(getMoney(record?.PAID_AMOUNT)).format('0,0.00') : '0'
          }
        },
        {
          title: <div style={{ textAlign: 'center' }}>水费</div>,
          dataIndex: 'PAID_AMOUNT_9010',
          valueType: 'digit',
          align: 'right',
          hideInSearch: true,
          render: (_, record) => {
            return record?.PAID_AMOUNT_9010 ?
              numeral(getMoney(record?.PAID_AMOUNT_9010)).format('0,0.00')
              : record?.PAID_AMOUNT_9010 === 0 ? <span style={{ color: 'red' }}>0</span> : ''
          }
        },
        {
          title: <div style={{ textAlign: 'center' }}>电费</div>,
          dataIndex: 'PAID_AMOUNT_9020',
          valueType: 'digit',
          align: 'right',
          hideInSearch: true,
          render: (_, record) => {
            return record?.PAID_AMOUNT_9020 ?
              numeral(getMoney(record?.PAID_AMOUNT_9020)).format('0,0.00')
              : record?.PAID_AMOUNT_9020 === 0 ? <span style={{ color: 'red' }}>0</span> : ''
          }
        },
        {
          title: <div style={{ textAlign: 'center' }}>房租</div>,
          dataIndex: 'PAID_AMOUNT_9030',
          valueType: 'digit',
          align: 'right',
          hideInSearch: true,
        },
        {
          title: <div style={{ textAlign: 'center' }}>物业费</div>,
          dataIndex: 'PAID_AMOUNT_9050',
          valueType: 'digit',
          align: 'right',
          hideInSearch: true,
          render: (_, record) => {
            return record?.PAID_AMOUNT_9050 ?
              numeral(getMoney(record?.PAID_AMOUNT_9050)).format('0,0.00')
              : record?.PAID_AMOUNT_9050 === 0 ? <span style={{ color: 'red' }}>0</span> : ''
          }
        }
      ]
    },
    {
      title: <div style={{ textAlign: 'center' }}>退补款</div>,
      dataIndex: 'RefundSupplement',
      valueType: 'digit',
      align: 'right',
      hideInSearch: true,
      render: (_, record) => {
        const number: number = record?.BANKACCOUNT_AMOUNT - record?.RECEIVABLEAMOUNT - record?.SHOPEXPENSE_AMOUNT + record?.PAID_AMOUNT
        return <span>{number ? numeral(number).format('0,0.00') : '-'}</span>
      }
    },
    {
      title: <div style={{ textAlign: 'center' }}>备注</div>,
      width: 100,
      dataIndex: 'desc',
      valueType: 'digit',
      align: 'right',
      hideInSearch: true,
    }
  ]

  // 拿到打印结算表的数据
  const handleGetPrintData = async () => {
    let res: any = []
    const otherReq: any = {
      ServerpartIds: compareCurrent?.SERVERPART_ID,
      ShopRoyaltyId: compareCurrent?.ShopRoyaltyId,
      BusinessProjectId: compareCurrent?.BUSINESSPROJECT_ID,
      startDate: compareCurrent.STATISTICS_MONTH ? moment(compareCurrent.STATISTICS_MONTH).format('YYYYMM') : '',
      endDate: compareCurrent.STATISTICS_MONTH ? moment(compareCurrent.STATISTICS_MONTH).format('YYYYMM') : '',
    }
    console.log('otherReq', otherReq);

    const data = await handleGetTableRevenueRecognition(otherReq)
    console.log('otherData', data);
    if (data && data.length > 0) {
      const list: any = wrapTreeNode(data)
      let obj: any = {}
      if (list && list.length > 0) {
        obj = list[0].children[0].children[0]
      }
      console.log('obj', obj);
      const [start, end] = obj.IndexDesc.split('-')
      let newIndexDesc: string = ''
      let newEnd: string = ''
      if (moment(obj.STATISTICS_MONTH).format('YYYYMM') === moment(end).format('YYYYMM')) {
        newEnd = moment(end).format('YYYY/MM/DD')
      } else {
        newEnd = moment(obj.STATISTICS_MONTH).endOf('month').format('YYYY/MM/DD')
      }
      newIndexDesc = `${start}-${newEnd}`
      obj.IndexDesc = newIndexDesc
      // 取现金 微支付 应收租金  应收费用  已缴费用
      const incomeReq: any = {
        BusinessProjectId: compareCurrent?.BUSINESSPROJECT_ID,
        StatisticsMonth: compareCurrent?.STATISTICS_MONTH ? moment(compareCurrent?.STATISTICS_MONTH).format('YYYYMM') : '',
        ShopRoyaltyId: compareCurrent?.ShopRoyaltyId,
      }
      const income = await handleGetProjectPeriodIncome(incomeReq)
      console.log('income', income);
      const incomObj: any = income[0]
      obj.CASHPAY_AMOUNT = incomObj.CASHPAY_AMOUNT
      obj.MOBILEPAY_AMOUNT = incomObj.MOBILEPAY_AMOUNT
      obj.ROYALTYTHEORYMUST = incomObj.RECEIVABLEAMOUNT
      // obj.SHOPEXPENSE_AMOUNT = incomObj.SHOPEXPENSE_AMOUNT
      // obj.PAID_AMOUNT = incomObj.PAID_AMOUNT

      // 取水电物业费
      // let expenseReq: any = {
      //   BusinessProjectId: compareCurrent?.BUSINESSPROJECT_ID,
      //   ShopRoyaltyId: compareCurrent?.ShopRoyaltyId,
      //   StartMonth: compareCurrent?.STATISTICS_MONTH ? moment(compareCurrent?.STATISTICS_MONTH).format('YYYYMM') : '',
      //   EndMonth: compareCurrent?.STATISTICS_MONTH ? moment(compareCurrent?.STATISTICS_MONTH).format('YYYYMM') : '',
      // }
      // console.log('expenseReq', expenseReq)
      // const expenseData: any = await handleGetProjectExpenseList(expenseReq)
      // console.log('expenseData', expenseData);
      // let expenseObj: any = expenseData[0]
      // obj.PaidFee_9010 = expenseObj.PAID_AMOUNT_9010
      // obj.PaidFee_9020 = expenseObj.PAID_AMOUNT_9020
      // obj.PaidFee_9030 = expenseObj.PAID_AMOUNT_9030
      // obj.PaidFee_9050 = expenseObj.PAID_AMOUNT_9050

      res = [obj]
    }
    console.log('res', res);

    setPrintData(res)

    const reqProgress: any = {
      BUSINESSAPPROVALId: compareCurrent?.BUSINESSAPPROVAL_ID || compareCurrent?.BusinessApprovalId
    }
    const dataProgress = await handleGetGetBUSINESSAPPROVALDetail(reqProgress)
    console.log('datahandleGetProcessProgress', dataProgress);

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

    if (dataProgress.approveList && dataProgress.approveList.length > 0) {
      dataProgress.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) {
          signatureObj.confirmationName = item.STAFF_NAME
          signatureObj.confirmationRealName = `${item.STAFF_NAME.split('【')[0]} ${item.APPLYAPPROVE_DATE}`
        } else if (item.APPLYAPPROVE_TYPE === 2010) {
          signatureObj.areaManagerName = item.STAFF_NAME
          signatureObj.areaManagerRealName = `${item.STAFF_NAME.split('【')[0]} ${item.APPLYAPPROVE_DATE}`
        } else if (item.APPLYAPPROVE_TYPE === 2020) {
          signatureObj.operationsSuperName = item.STAFF_NAME
          signatureObj.operationsSuperRealName = `${item.STAFF_NAME.split('【')[0]} ${item.APPLYAPPROVE_DATE}`
        } else if (item.APPLYAPPROVE_TYPE === 2030) {
          signatureObj.centralFinanceName = item.STAFF_NAME
          signatureObj.centralFinanceRealName = `${item.STAFF_NAME.split('【')[0]} ${item.APPLYAPPROVE_DATE}`
        } else if (item.APPLYAPPROVE_TYPE === 2040) {
          signatureObj.directorName = item.STAFF_NAME
          signatureObj.directorRealName = `${item.STAFF_NAME.split('【')[0]} ${item.APPLYAPPROVE_DATE}`
        } else if (item.APPLYAPPROVE_TYPE === 2050) {
          signatureObj.developmentName = item.STAFF_NAME
          signatureObj.developmentRealName = `${item.STAFF_NAME.split('【')[0]} ${item.APPLYAPPROVE_DATE}`
        } else if (item.APPLYAPPROVE_TYPE === 2060) {
          signatureObj.financeName = item.STAFF_NAME
          signatureObj.financeRealName = `${item.STAFF_NAME.split('【')[0]} ${item.APPLYAPPROVE_DATE}`
        }
      })
    }
    console.log('signature', signatureObj);

    setSignatureObj(signatureObj)

  }



  useEffect(() => {
    if (compareCurrent) {
      console.log('compareCurrent', compareCurrent)
      console.log('onlyRead', onlyRead)
      if (compareCurrent?.Approvalstate === 0) {
        setShowMoreBtn(true)
      } else if (compareCurrent?.Approvalstate === 9) {
        handleGetPrintData()
      }
      handleGetTableData()
    }
  }, [compareCurrent]);

  // useEffect(() => {
  //   if (!tableSecondLoading) {
  //     console.log('firstTableData', firstTableData);
  //     let obj: any = {}
  //     if (firstTableData && firstTableData.length > 0) {
  //       obj = {
  //         CASHPAY_AMOUNT: firstTableData[0].CASHPAY_AMOUNT,
  //         MOBILEPAY_AMOUNT: firstTableData[0].MOBILEPAY_AMOUNT,
  //         IndexDesc: firstTableData[0].IndexDesc,
  //       }
  //     }
  //     handleGetFirstTableData(obj)
  //   }
  // }, [tableSecondLoading])

  return <div style={{ background: '#fff' }}>


    {/* <div className={'titleBox'}>初始月度结算表</div> */}
    {

      come !== 'ConfirmationDifference' ?
        showMoreBtn ?
          <ProTable
            columns={come === 'revenueDifference' ? comeColumns : defaultColumns}
            bordered
            style={{ background: '#fff', paddingTop: '10px' }}
            // scroll={{x: 1100}}
            scroll={{ x: 'max-content' }}
            search={false}
            // options={false}
            pagination={false}
            loading={tableSecondLoading}
            dataSource={come === 'revenueDifference' ? [compareCurrent] : firstTableData}
            columnsState={{
              value: defaultColumnsStateMap,
              onChange: setDefaultColumnsStateMap,
            }}
            tableExtraRender={(_, data) => {
              return <div className={'extraRenderBox'} style={{ paddingLeft: 30, paddingBottom: 0, paddingTop: '15px', background: '#fff' }}>
                <div style={{ width: '100%', display: 'flex', alignItems: 'center', justifyContent: 'space-between', boxSizing: 'border-box', paddingRight: '20%', marginBottom: '8px' }}>
                  <div style={{ fontSize: '20px', fontWeight: 600, marginBottom: '16px' }}>
                    {`${compareCurrent?.Serverpart_Name || compareCurrent?.SERVERPART_NAME || ''}-${topProjectDetail?.SERVERPARTSHOP_NAME || ''}-${compareCurrent?.STATISTICS_MONTH || monthTime || ''}月度结算`}
                  </div>
                  <Button type="primary" onClick={() => {
                    setShowMoreBtn(false)
                  }}>点击隐藏</Button>
                </div>

                <Row align="middle">
                  <Col span={14}>
                    <ProDescriptions column={3}>
                      {/* <ProDescriptions.Item label="经营商户">{topProjectDetail?.MERCHANTS_NAME}</ProDescriptions.Item> */}
                      {/* <ProDescriptions.Item label="合同起止日期">{`${topProjectDetail?.COMPACT_STARTDATE ? moment(topProjectDetail?.COMPACT_STARTDATE).format('YYYY/MM/DD') : ''}${topProjectDetail?.COMPACT_ENDDATE ? `-${moment(topProjectDetail?.COMPACT_ENDDATE).format('YYYY/MM/DD')}` : ''}`}</ProDescriptions.Item> */}
                      <ProDescriptions.Item label="开始日期">{`${topProjectDetail?.COMPACT_STARTDATE ? moment(topProjectDetail?.COMPACT_STARTDATE).format('YYYY/MM/DD') : ''}`}</ProDescriptions.Item>
                      <ProDescriptions.Item label="结束日期">{`${topProjectDetail?.COMPACT_ENDDATE ? moment(topProjectDetail?.COMPACT_ENDDATE).format('YYYY/MM/DD') : ''}`}</ProDescriptions.Item>
                      <ProDescriptions.Item label="结算模式">{SETTLEMENT_MODESObj[topProjectDetail?.SettlementModes]}</ProDescriptions.Item>
                    </ProDescriptions>
                    <ProDescriptions column={3}>
                      <ProDescriptions.Item label="项目期数">{topProjectDetail?.IndexStr}</ProDescriptions.Item>
                      <ProDescriptions.Item label="装修期">{topProjectDetail?.DecorateDesc}</ProDescriptions.Item>
                      <ProDescriptions.Item label="履约保证金"
                      >{topProjectDetail?.SECURITYDEPOSIT ? `${getMoney(topProjectDetail?.SECURITYDEPOSIT / 10000)}万元` : ''}</ProDescriptions.Item>
                    </ProDescriptions>
                    <ProDescriptions column={3}>
                      {/* <ProDescriptions.Item label="保底/固定租金"
                >{topProjectDetail?.RENTFEE?`${getMoney(topProjectDetail?.RENTFEE / 10000)}万元`:''}</ProDescriptions.Item> */}
                      <ProDescriptions.Item label="提成比例">{topProjectDetail?.GUARANTEERATIO ? `${topProjectDetail?.GUARANTEERATIO}%` : '-'}</ProDescriptions.Item>
                      <ProDescriptions.Item label="税率">{topProjectDetail?.TaxRate ? `${topProjectDetail?.TaxRate}%` : '-'}</ProDescriptions.Item>
                      <ProDescriptions.Item label="期除税收入">{topProjectDetail?.MINTURNOVER ? `${getMoney(topProjectDetail?.MINTURNOVER / 10000)}万元` : ''}</ProDescriptions.Item>
                    </ProDescriptions>
                    {/* <ProDescriptions column={3}> */}
                    {/* <ProDescriptions.Item label="月收入" valueType="money">{topProjectDetail?.MonthlyIncome}</ProDescriptions.Item> */}
                    {/* <ProDescriptions.Item label="累计月数">{topProjectDetail?.MonthlyCount}</ProDescriptions.Item> */}
                    {/* <ProDescriptions.Item label="经营门店">{compareCurrent?.SERVERPARTSHOP_NAME}</ProDescriptions.Item> */}

                    {/* </ProDescriptions> */}
                    {/* <ProDescriptions column={3}> */}
                    {/* <ProDescriptions.Item label="累计月收入" valueType="money">{topProjectDetail?.MonthlyTotalIncome}</ProDescriptions.Item> */}
                    {/* </ProDescriptions> */}
                  </Col>

                  <Col span={3}>
                    <Statistic className="contract-static-card"
                      title={topProjectDetail?.RENTFEE ? amountDom(topProjectDetail?.RENTFEE / 10000) : <Text type="warning" style={{
                        fontSize: 36, lineHeight: 1,
                        fontFamily: "Bahnschrift Regular"
                      }}>-</Text>}
                      valueStyle={{ color: "#00000075", fontSize: 14 }}
                      value={'项目金额'}
                    />
                  </Col>

                  <Col span={7}>
                    <Statistic className="contract-static-card" title={<span style={{ fontSize: 20, color: "#262626" }}>{topProjectDetail?.MERCHANTS_NAME}</span>}
                      valueStyle={{ color: "#00000075", fontSize: 14, marginTop: 10 }}
                      value={"经营商户"}
                    />
                  </Col>
                  {/* <Col>
            <Descriptions column={7}>
              <Descriptions.Item label="备注说明">{topProjectDetail?.Remark}</Descriptions.Item>
            </Descriptions>
          </Col> */}
                </Row>
                {
                  noticeRowData ?
                    <div style={{ color: '#00000073' }}>
                      项目拆分移动支付
                      {noticeRowData?.CURMOBILEPAY_AMOUNT ? `（${numeral(getMoney(noticeRowData?.CURMOBILEPAY_AMOUNT)).format('0,0.00')}）` : ''}
                      {noticeRowData?.CURMOBILEPAY_AMOUNT > noticeRowData?.MobilePay_Amount ? '>' : noticeRowData?.CURMOBILEPAY_AMOUNT === noticeRowData?.MobilePay_Amount ? '=' : '<'}
                      {'自然日移动支付'}
                      {noticeRowData?.MobilePay_Amount ? `（${numeral(getMoney(noticeRowData?.MobilePay_Amount)).format('0,0.00')}）` : ''}
                      ，以
                      {noticeRowData?.CURMOBILEPAY_AMOUNT >= noticeRowData?.MobilePay_Amount ? '项目拆分移动支付' : '自然日拆分移动支付'}
                      为准；
                      自然日现金支付
                      {noticeRowData?.CashPay_Amount ? `（${numeral(getMoney(noticeRowData?.CashPay_Amount)).format('0,0.00')}）` : ''}
                      {noticeRowData?.CashPay_Amount > noticeRowData?.CURCASHPAY_AMOUNT ? '>' : noticeRowData?.CashPay_Amount === noticeRowData?.CURCASHPAY_AMOUNT ? '=' : '<'}
                      {'项目拆分现金支付'}
                      {noticeRowData?.CURCASHPAY_AMOUNT ? `（${numeral(getMoney(noticeRowData?.CURCASHPAY_AMOUNT)).format('0,0.00')}）` : ''}
                      ，以
                      {noticeRowData?.CashPay_Amount >= noticeRowData?.CURCASHPAY_AMOUNT ? '项目拆分现金支付' : '自然日现金支付'}
                      为准，
                      {noticeRowData?.CashPay_Amount && noticeRowData?.CURCASHPAY_AMOUNT && noticeRowData?.CashPay_Amount - noticeRowData?.CURCASHPAY_AMOUNT > 0 ? `建议现金冲正${numeral(getMoney(noticeRowData?.CashPay_Amount - noticeRowData?.CURCASHPAY_AMOUNT)).format('0,0.00')}元` : ''}
                    </div> : ''
                }
              </div>
            }}
          />
          :
          <div>
            <div style={{ width: '100%', display: 'flex', alignItems: 'center', justifyContent: 'space-between', boxSizing: 'border-box', paddingTop: '16px', paddingLeft: '30px', paddingRight: '20%', marginBottom: '8px' }}>
              <div style={{ fontSize: '20px', fontWeight: 600, marginBottom: '16px' }}>
                {`${compareCurrent?.Serverpart_Name || compareCurrent?.SERVERPART_NAME || ''}-${topProjectDetail?.SERVERPARTSHOP_NAME || ''}-${compareCurrent?.STATISTICS_MONTH || monthTime || ''}月度结算`}
              </div>
              <Button type="primary" onClick={() => {
                setShowMoreBtn(true)
              }}>展开更多</Button>
            </div>
          </div> : ""
    }

    {
      showTopTable ?
        <MonthTopTable compareCurrent={compareCurrent} newData={firstTableData} reload={tableSecondLoading} headerTitle={`${topProjectDetail?.MERCHANTS_NAME || ''}${compareCurrent?.STATISTICS_MONTH || monthTime || ''}月度累计结算表`} />
        : ''
    }
    {/* <ProTable
      search={false}
      columns={topColumns}
      pagination={false}
      bordered
      loading={topTableLoading}
      dataSource={topTable}
      scroll={{ x: 'max-content' }}
    /> */}


    {
      come !== 'ConfirmationDifference' ?
        <MonthSettlement onRef={MonthSettlementRef} detail={compareCurrent} noTitle={true} />
        : ""
    }



    <div style={{
      width: '100%',
      // display: 'flex',
      // alignItems: 'center',
      // justifyContent: 'flex-end',
      boxSizing: 'border-box',
      paddingLeft: '30px'
    }}>

      {/* || !handleHaveDifference */}
      {
        // compareCurrent.BusinessType===2000 || !handleHaveDifference? compareCurrent.BusinessType === 2000 ?
        //      '' : '' :
        //   compareCurrent?.Approvalstate > 0 && compareCurrent?.Approvalstate < 9  ? <span style={{color:'red'}}>审核中</span> : compareCurrent?.Approvalstate === 9 ?
        //   <span style={{color: 'red'}}>{''}</span> :


        // compareCurrent?.Approvalstate > 0 && compareCurrent?.Approvalstate < 9 ?
        //   <span style={{color: 'red',cursor:'pointer'}} onClick={()=>{
        //     setShowReviewProcess(true)
        //   }}>审核中</span> :
        compareCurrent?.Approvalstate === 9 ? <span style={{ color: 'red' }}></span> :
          <div style={{ boxSizing: 'border-box' }}>
            {
              compareCurrent?.BusinessType === 2000 ? <span style={{ color: 'red' }}>固定租金</span> : ''
            }
            {/* { */}
            {/*   compareCurrent.SettlementModes!==3000 && compareCurrent.SettlementModes!==4000? */}
            {/*     <span style={{color: 'red',marginLeft:'12px',display:'inline-block',marginBottom:'8px'}}>当前项目为非营收分润项目，以日结营收口径结算</span> */}
            {/*     :'' */}
            {/* } */}
            <ProForm
              layout={'horizontal'}
              formRef={editFormRef}
              submitter={false}
            >
              {
                onlyRead ? '' :
                  <Row gutter={16} className={'formBox'}>
                    {
                      handleHaveDifference || (compareCurrent?.Approvalstate > 0 && compareCurrent.PEND_STATE === 0) ?
                        showRecalibration || (compareCurrent?.Approvalstate > 0 && compareCurrent.PEND_STATE === 0) ?
                          <Col span={6}>
                            <ProFormDigit
                              name={'MobilePayCorrect'}
                              label={'移动支付差额'}
                              fieldProps={{
                                precision: 2,
                                min: -Infinity,
                                onChange: (e: any) => {
                                  const res = editFormRef.current?.getFieldValue()
                                  // if (e || res.CashPayCorrect) {
                                  //   setShowRecalibration(true)
                                  // } else {
                                  //   setShowRecalibration(false)
                                  // }
                                }
                              }}
                            />
                            <span style={{
                              fontSize: '14px',
                              display: 'inline-block',
                              color: '#00000073', marginTop: '8px'
                            }}>{editFormRef.current?.getFieldValue('MobilePayCorrectDesc')}</span>
                          </Col> : '' : ''
                    }
                    {
                      handleHaveDifference || (compareCurrent?.Approvalstate > 0 && compareCurrent.PEND_STATE === 0) ?
                        showRecalibration || (compareCurrent?.Approvalstate > 0 && compareCurrent.PEND_STATE === 0) ?
                          <Col span={6}>
                            <ProFormDigit
                              name={'CashPayCorrect'}
                              label={'现金支付差额'}
                              fieldProps={{
                                precision: 2,
                                min: -Infinity,
                                onChange: (e: any) => {
                                  const res = editFormRef.current?.getFieldValue()
                                  // if (e || res?.MobilePayCorrect) {
                                  //   setShowRecalibration(true)
                                  // } else {
                                  //   setShowRecalibration(false)
                                  // }
                                }
                              }}
                            />
                            {/* CashPayCorrectDesc */}
                            <span style={{ fontSize: '14px', display: 'inline-block', color: '#00000073', marginTop: '8px' }}>{editFormRef.current?.getFieldValue('CashPayCorrectDesc')}</span>
                          </Col> : '' : ''
                    }
                    <Col span={8}>
                      {
                        onlyRead || !handleHaveDifference ? '' :
                          showRecalibration ?
                            <Button style={{ marginRight: '8px' }} type={'primary'} onClick={() => {
                              const res = editFormRef.current?.getFieldValue()
                              if (res) {
                                getCalibrationTableData(res?.MobilePayCorrect, res?.CashPayCorrect, null, compareCurrent)
                              }
                            }}>
                              重新校准
                            </Button> : ''
                      }

                      {/* 如果已经参与了审批 就不可能出现月度结算了 */}
                      {/* {handleHaveDifference} */}
                      {
                        onlyRead ? '' :
                          <>
                            {
                              compareCurrent?.Approvalstate > 0 && compareCurrent?.PEND_STATE === 0 ? <Button loading={reapply} type='primary' style={{ marginBottom: '8px' }} onClick={async () => {
                                setReapply(true)
                                const res = editFormRef.current?.getFieldValue()
                                console.log('clickCalibration', clickCalibration);

                                // if (!clickCalibration) {
                                await getCalibrationTableData(res?.MobilePayCorrect, res?.CashPayCorrect)
                                // }
                                console.log('compareCurrent', compareCurrent)
                                console.log('firstTableData[1]', firstTableData)
                                console.log('resresres', res)
                                setModalFormValue(res)
                                setSettlementModal(true)
                                setReapply(false)
                              }}>
                                重新申请
                              </Button> :
                                compareCurrent?.PEND_STATE === 0 ?
                                  <Popconfirm
                                    title="确认提交结算?"
                                    onConfirm={async () => {
                                      console.log('compareCurrent', compareCurrent);
                                      console.log('lastMonthIsOverlastMonthIsOverlastMonthIsOver', lastMonthIsOver);
                                      console.log('MonthSettlementRefMonthSettlementRefMonthSettlementRef', MonthSettlementRef);
                                      if (lastMonthIsOver) {
                                        // 是否显示下面四项为0的时候的询问框
                                        let showNotice: any = false
                                        const unData: any = []
                                        if (MonthSettlementRef) {
                                          const data = MonthSettlementRef.current?.tableData
                                          console.log('data', data);
                                          if (data && data.length > 0) {
                                            data.forEach((item: any) => {
                                              if (item.SHOPEXPENSE_AMOUNT === 0) {
                                                unData.push('应缴合计')
                                              }
                                              if (item.SHOPEXPENSE_AMOUNT_1000 === 0) {
                                                unData.push('应缴水费')
                                              }
                                              if (item.SHOPEXPENSE_AMOUNT_2000 === 0) {
                                                unData.push('应缴电费')
                                              }
                                              if (item.SHOPEXPENSE_AMOUNT_5000 === 0) {
                                                unData.push('应缴物业费')
                                              }
                                            })
                                          }
                                          if (unData && unData.length > 0) {
                                            showNotice = true
                                          }
                                        }
                                        if (showNotice) {
                                          let text: string = ''
                                          unData.forEach((item: any) => {
                                            if (text) {
                                              text += `、${item}`
                                            } else {
                                              text = item
                                            }
                                          })
                                          confirm({
                                            width: 500,
                                            title: '系统检测：',
                                            content: <div>
                                              {`本月${text}未填写，是否确认审批？`}
                                            </div>,
                                            onOk: async () => {
                                              const res = editFormRef.current?.getFieldValue()
                                              if (!clickCalibration) {
                                                await getCalibrationTableData(res?.MobilePayCorrect, res?.CashPayCorrect)
                                              }
                                              console.log('compareCurrent', compareCurrent)
                                              console.log('firstTableData[1]', firstTableData)
                                              setModalFormValue(res)
                                              setSettlementModal(true)
                                            }
                                          })
                                        } else {
                                          const res = editFormRef.current?.getFieldValue()
                                          if (!clickCalibration) {
                                            await getCalibrationTableData(res?.MobilePayCorrect, res?.CashPayCorrect)
                                          }
                                          console.log('compareCurrent', compareCurrent)
                                          console.log('firstTableData[1]', firstTableData)
                                          setModalFormValue(res)
                                          setSettlementModal(true)
                                        }

                                      } else {
                                        // message.error(`${LastSettlementMonth || ''}`)
                                        confirm({
                                          // title: `确认是否跳转到${settlementObj?.LastSettlementMonth}月进行审批？`,
                                          // content: '跳转会刷新页面',
                                          width: 500,
                                          title: '系统检测：',
                                          content: <div>
                                            <div style={{ fontSize: '16px' }}>{`${compareCurrent?.SERVERPART_NAME}-${topProjectDetail?.SERVERPARTSHOP_NAME},项目期数内存在未审批月度结算！`}</div>
                                            <div style={{ fontSize: '16px' }}>点击确定自动为您调整到<span style={{ color: 'red' }}>{`${settlementObj?.LastSettlementMonth}`}</span>月进行审批？</div>
                                          </div>,
                                          onOk: async () => {
                                            if (handleGetNewMonth) {
                                              return new Promise(async (resolve) => {
                                                await handleGetNewMonth(compareCurrent, settlementObj?.LastSettlementMonth)
                                                resolve(() => {
                                                })
                                              }).then(() => {
                                                console.log('2');
                                                // handleGetTableData()
                                              })
                                            }
                                          }
                                        });
                                      }
                                    }}
                                  >
                                    <Button type={'primary'}>发起结算</Button>
                                  </Popconfirm> : ''

                            }
                          </>
                      }
                    </Col>
                  </Row>
              }

            </ProForm>
          </div>
      }

      {
        compareCurrent?.BUSINESSAPPROVAL_ID ?
          <Button style={{ marginBottom: '8px' }} type="primary" onClick={() => {
            setShowSearchFile(true)
          }}>查看月度结算单</Button> : ''
      }
      {
        compareCurrent?.Approvalstate === 9 && come !== 'ConfirmationDifference' ?
          <Button key="new" style={{ marginLeft: '8px' }} onClick={() => {
            console.log('compareCurrent', compareCurrent);
            console.log('topProjectDetail', topProjectDetail);
            const printName: string = `${compareCurrent?.Serverpart_Name || compareCurrent?.SERVERPART_NAME || ''}-${topProjectDetail?.SERVERPARTSHOP_NAME || ''}-${compareCurrent?.STATISTICS_MONTH || monthTime || ''}月度结算`

            const neckList: any = [
              { label: '管理中心', value: compareCurrent?.SPREGIONTYPE_NAME },
              { label: '服务区', value: compareCurrent?.SERVERPART_NAME },
              { label: '经营商户', value: compareCurrent?.MERCHANTS_NAME },
              { label: '门店名称', value: compareCurrent?.SERVERPARTSHOP_NAME },
              { label: '合同期限', value: `${compareCurrent?.PROJECT_STARTDATE ? `${moment(compareCurrent?.PROJECT_STARTDATE).format('YYYY.MM.DD')}` : ''}${compareCurrent?.PROJECT_ENDDATE ? `-${moment(compareCurrent?.PROJECT_ENDDATE).format('YYYY.MM.DD')}` : ''}` },
            ]

            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('compareListTestTable')[0] // 拿到要打印的数据表格
            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;">财务部：</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;">经发部：</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, `${compareCurrent?.BUSINESSPROJECT_NAME}结算表(${compareCurrent?.STATISTICS_MONTH || monthTime || ''})月`, neckList, styles, clonedHTML, footer)
          }}>打印结算表</Button> : ''
      }
    </div>

    <PrintContent pageName={'compareList'} exportColumns={printColumns} exportData={printData} type={'month'} />


    {/* <ProTable
      style={{ display: "none" }}
      className="testTable"
      columns={printColumns}
      dataSource={printData}
      pagination={false}
      bordered
      expandable={{
        defaultExpandAllRows: true
      }}
    /> */}

    {/* <div className={'titleBox'} style={{marginTop: '16px'}}></div> */}

    {/* <ProTable */}
    {/*   columns={defaultColumns} */}
    {/*   bordered */}
    {/*   style={{background: '#fff'}} */}
    {/*   search={false} */}
    {/*   options={false} */}
    {/*   pagination={false} */}
    {/*   scroll={{x: 1100}} */}
    {/*   loading={tableSecondLoading} */}
    {/*   dataSource={secondTableData} */}
    {/* /> */}
    {
      compareCurrent?.Approvalstate > 0 && come !== 'ConfirmationDifference' ? '' :
        <div className={'titleBox'} style={{ marginTop: '16px' }}>
          <div className={'leftBox'}>


          </div>
          <div className={'rightBox'}>
            {
              handleHaveDifference ?
                <span style={{
                  marginRight: '8px',
                  color: '#00000073'
                }}>如项目建立或数据上传出现延迟，会出现结算金额偏差，请点击【交易精算】按钮进行数据修正！</span> : ''
            }
            {
              (onlyRead && type !== 'settlementAccount') || compareCurrent?.Approvalstate === 9 ? '' :
                <Button style={{ marginRight: '8px' }} type={'primary'} onClick={async () => {
                  handleClickAgain.current = true
                  setCompareTableLoading(true)
                  // const req = {
                  //   StartDate: moment(compareCurrent?.startTime).format('YYYY-MM-DD'),
                  //   EndDate: moment(compareCurrent?.endTime).format('YYYY-MM-DD'),
                  //   ProjectId: compareCurrent?.BUSINESSPROJECT_ID,
                  //   // OutBusinessType: 1000
                  // }
                  console.log('compareCurrent', compareCurrent);

                  const howMonth: number = moment(compareCurrent?.endTime).diff(compareCurrent?.startTime, 'month') + 2

                  const data = await handleGetOnceMonth(1, howMonth, compareCurrent)
                  console.log('data', data);

                  if (data) {
                    setLoadingText('')
                    handleGetTableData()
                  } else {
                    setCompareTableLoading(false)
                  }

                  // const data = await handleAgain(req)
                  // handleClickAgain.current = false
                  // if (data.Result_Code === 100) {
                  //   setTableData([])
                  //   handleGetTableData()
                  //   message.success(data.Result_Desc)
                  // } else {
                  //   setCompareTableLoading(false)
                  //   message.error(data.Result_Desc)
                  // }
                }}>交易精算</Button>
            }
            <>
              {
                showBigTableDifference || come === 'ConfirmationDifference' ?
                  <Button type="primary" onClick={() => {
                    console.log('tableAllData', tableAllData);
                    setShowBigTableDifference(false)
                    handleClickAgain.current = true
                    setTableData([])
                    setLoadingText('正在加载全部数据...')
                    setCompareTableLoading(true)
                    setTimeout(() => {
                      setTableData(tableAllData)
                      setCompareTableLoading(false)
                      handleClickAgain.current = false
                    }, 100)
                  }}>显示全部</Button> :
                  <Button type="primary" onClick={() => {
                    console.log('tableDifferenceData', tableDifferenceData);
                    setShowBigTableDifference(true)
                    handleClickAgain.current = true
                    setTableData([])
                    setLoadingText('正在加载差异数据...')
                    setCompareTableLoading(true)
                    setTimeout(() => {
                      setTableData(tableDifferenceData)
                      setCompareTableLoading(false)
                      handleClickAgain.current = false
                    }, 100)
                  }}>显示差异</Button>
              }
            </>
          </div>
        </div>
    }


    {
      compareCurrent?.Approvalstate > 0 && come !== 'ConfirmationDifference' ?
        <div style={{ width: '100%', boxSizing: 'border-box', padding: '0 30px' }}>
          <ReviewProcess showReviewProcess={compareCurrent} compareCurrent={{
            ...compareCurrent,
            BusinessApprovalId: compareCurrent?.BUSINESSAPPROVAL_ID
          }} />
        </div>
        :
        <ProTable
          formRef={formRef}
          actionRef={actionRef}
          columns={columns}
          bordered
          style={{ background: '#fff', paddingTop: '10px' }}
          dataSource={tableData}
          search={false}
          // loading={compareTableLoading}
          loading={compareTableLoading ? {
            spinning: compareTableLoading,
            tip: handleClickAgain.current ? loadingText || '数据重新生成中,请稍后...' : '正在对项目交易流水进行自动排查，请稍后...'
          } : false}
          className={'tableBox'}
          // rowClassName={(record) =>
          //   record?.STATISTICS_DATE === '合计'?'topBg':''
          // }

          // rowClassName={(record) =>
          //   record?.STATISTICS_DATE==='合计'?'':record?.MobilePay_Amount !== record?.CURMOBILEPAY_AMOUNT || record?.CashPay_Amount !== record?.CURCASHPAY_AMOUNT ? 'redRow' : ''
          // }
          options={false}
          pagination={false}
        // toolbar={{
        //   actions:
        // }}
        // onRow={(record)=>{
        //   return{
        //     onClick:(e)=>{
        //       if (record?.MobilePay_Amount !== record?.CURMOBILEPAY_AMOUNT || record?.CashPay_Amount !== record?.CURCASHPAY_AMOUNT){
        //         if (record?.STATISTICS_DATE!=='合计'){
        //           setSelectRow(record)
        //           setDailyDetailSales(true)
        //         }
        //       }
        //     },
        //   }
        // }}
        />
    }



    {/* 当金额对不上 查看当天的详细流水 */}
    <Drawer
      width="80%"
      className="project-drawer"
      visible={dailyDetailSales} // 抽屉弹框是否显示状态
      onClose={() => { // 关闭抽屉 则在清空选中行数据 并 设置抽屉状态为关闭
        setDifferenceType(0)
        setDailyDetailSales(false);
        setSelectRow(undefined);
        setLeftTableData([]);
        setRightTableData([]);
        setShowLeftText(false)
      }}
      destroyOnClose
      bodyStyle={{ backgroundColor: "#f9f9f9", padding: 0 }}
      closable={false}
    >
      <div style={{ width: '100%', background: '#fff', boxSizing: 'border-box', padding: '16px 0' }}>
        <div style={{
          width: '100%',
          boxSizing: 'border-box',
          padding: '0 16px',
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'space-between'
        }}>
          {
            DifferenceType === 1 ? <span style={{ fontSize: '16px' }}>
              {selectRow?.STATISTICS_DATE}
              移动支付交易，本地自然日流水
              <span style={{ color: 'red' }}>{selectRow?.MobilePay_Amount || '-'}</span>元，项目拆分流水
              <span style={{ color: 'red' }}>{selectRow?.CURMOBILEPAY_AMOUNT || '-'}</span>元
              {
                selectRow?.Mobile_Correct ?
                  <span>
                    ，移动支付冲正<span style={{ color: 'red' }}>{selectRow?.Mobile_Correct || ''}</span>元
                  </span> : <span>
                    {
                      selectRow?.MobilePay_Amount - selectRow?.CURMOBILEPAY_AMOUNT ?
                        <span>，差额<span
                          style={{ color: 'red' }}>{numeral(selectRow?.MobilePay_Amount - selectRow?.CURMOBILEPAY_AMOUNT).format('0.00')}</span>元</span> : ''
                    }
                  </span>
              }

              {/* {`${selectRow?.STATISTICS_DATE}移动支付交易，本地自然日流水${selectRow?.MobilePay_Amount || '-'}元，项目拆分流水${selectRow?.CURMOBILEPAY_AMOUNT || '-'}元，差额${(selectRow?.MobilePay_Amount - selectRow?.CURMOBILEPAY_AMOUNT) || '-'}元`} */}
            </span> : <span>
              {selectRow?.STATISTICS_DATE}
              现金支付交易，本地自然日流水
              <span style={{ color: 'red' }}>{selectRow?.CashPay_Amount || '-'}</span>元，项目拆分流水
              <span style={{ color: 'red' }}>{selectRow?.CURCASHPAY_AMOUNT || '-'}</span>元
              {
                selectRow?.Cash_Correct ?
                  <span>
                    ，现金支付冲正<span style={{ color: 'red' }}>{selectRow?.Cash_Correct || ''}</span>元
                  </span> : <span>
                    {
                      selectRow?.CashPay_Amount - selectRow?.CURCASHPAY_AMOUNT ?
                        <span>，差额<span
                          style={{ color: 'red' }}>{numeral(selectRow?.CashPay_Amount - selectRow?.CURCASHPAY_AMOUNT).format('0.00')}</span>元</span> : ''
                    }
                  </span>
              }

              {/* {`${selectRow?.STATISTICS_DATE}移动支付交易，本地自然日流水${selectRow?.MobilePay_Amount || '-'}元，项目拆分流水${selectRow?.CURMOBILEPAY_AMOUNT || '-'}元，差额${(selectRow?.MobilePay_Amount - selectRow?.CURMOBILEPAY_AMOUNT) || '-'}元`} */}
            </span>
          }

          {
            DifferenceType === 1 ?
              <div>
                {
                  showTableDifference ?
                    <Button type="primary" onClick={() => {
                      setShowTableDifference(false)
                      setLeftTableData(drawerLeftTableAllData)
                      setRightTableData(drawerRightTableAllData)
                    }}>显示全部</Button> :
                    <Button type="primary" onClick={() => {
                      setShowTableDifference(true)
                      setLeftTableData(leftDifferenceTableData)
                      setRightTableData(rightDifferenceTableData)
                    }}>显示差异</Button>
                }
              </div> : ''
          }

        </div>
        <div style={{ width: '100%', display: 'flex' }}>
          <div style={{ width: DifferenceType === 1 ? '50%' : '100%' }}>
            <div style={{ display: 'flex', width: '100%', height: DifferenceType === 1 ? '100px' : '60px', boxSizing: 'border-box', padding: '16px 16px 0', color: 'red' }}>
              {
                showLeftText ?
                  <div>
                    <span style={{ display: 'block' }}>{`收银人员人工确认交易但实际交易失败，为了符合业主财务准则（长款没收，短款补齐），系统默认交易已发生并做为有效营收计入商家账户；`}</span>
                    <span style={{ display: 'block' }}>{`因此为了保障报表最终拆分结果的一致性，会对自然日报表进行流水冲正（实际交易失败的流水金额），此金额计入商家现金收款部分。`}</span>
                  </div> : ''
              }
            </div>

            <ProTable
              formRef={formRef}
              actionRef={actionRef}
              className={'leftTableBox'}
              search={false}
              columns={detailColumns}
              loading={twoTableLoading}
              bordered
              request={async () => {
                setTwoTableLoading(true)
                const req: any = {
                  SearchParameter: {
                    SERVERPARTSHOP_ID: compareCurrent?.Id || '',
                    SELLMASTER_DATE: selectRow?.STATISTICS_DATE || ''
                  },
                  PageIndex: 1,
                  PageSize: 999999,
                  SortStr: 'SELLMASTER_DATE desc'
                }
                const reqSub: any = {
                  SearchParameter: {
                    ServerpartShop_IDS: compareCurrent?.Id || '',
                    Pay_Date: selectRow?.STATISTICS_DATE || '',
                    Record_State: 1
                  },
                  PageIndex: 1,
                  pagesize: 999999,
                  SortStr: "Pay_Date desc",
                }
                const data = await handleGetYSSellMasterList(req);
                if (DifferenceType === 1) {
                  const subData = await handleGetRoyaltyRecordList(reqSub);
                  if (data && data.length > 0 && subData && subData.length > 0) {
                    const indexFirst: any = []
                    const indexSecond: any = []
                    data.forEach((item: any) => {
                      indexFirst.push(item.SELLMASTER_CODE)
                    })
                    subData.forEach((item: any) => {
                      item.SELLMASTER_CODE = item.Ticket_Code
                      indexSecond.push(item.SELLMASTER_CODE)
                    })

                    const listLeft: any = []
                    const listRight: any = []
                    let leftSum: number = 0
                    let rightSum: number = 0
                    if (data && data.length > 0) {
                      data.forEach((item: any) => {
                        if (item.PAYMENT_TYPE_TEXT !== '现金') {
                          if (item.SELLMASTER_STATE === 0) {
                            item.SELLMASTER_STATETEXT = '失败'
                          } else if (item.SELLMASTER_STATE === 1) {
                            item.SELLMASTER_STATETEXT = '人工确认'
                          } else {
                            item.SELLMASTER_STATETEXT = '成功'
                          }
                          listLeft.push(item)
                          leftSum += item.SELLMASTER_AMOUNT
                        }
                      })
                    }
                    if (subData && subData.length > 0) {
                      subData.forEach((item: any) => {
                        if (item.PAYMENT_TYPE_TEXT !== '现金') {
                          listRight.push(item)
                          rightSum += item.Ticket_Price
                        }
                      })
                    }

                    // listRight.unshift({
                    //   Pay_Date: '合计',
                    //   Ticket_Price: rightSum
                    // })


                    // 把左边和右边订单号对的上的 右边表格就不再显示
                    const resRight: any = []
                    // 右边和左边对的上的内容添加合计
                    let resRightSum: number = 0
                    // 右边和左边公共的订单编号数组
                    const rightCodeList: any = []
                    // 左边表格有差异行的数据
                    const leftDifferenceList: any = []

                    if (listLeft && listLeft.length > 0) {
                      listLeft.forEach((item: any, index: number) => {
                        let num: number = 0
                        item.index = index + 1
                        if (listRight && listRight.length > 0) {
                          listRight.forEach((subItem: any, subIndex: number) => {
                            subItem.index = subIndex + 1
                            if (item.SELLMASTER_CODE === subItem.Ticket_Code) {
                              num = subItem.Ticket_Price
                              resRightSum += subItem.Ticket_Price
                              rightCodeList.push(subItem.Ticket_Code)
                            }
                          })
                        }
                        item.Ticket_Price = num
                        if (item.Ticket_Price !== item.SELLMASTER_AMOUNT) {
                          leftDifferenceList.push(item)
                        }
                      })
                    }

                    listLeft.unshift({
                      SELLMASTER_DATE: '合计',
                      SELLMASTER_AMOUNT: leftSum,
                      Ticket_Price: resRightSum
                    })
                    if (listRight && listRight.length > 0) {
                      listRight.forEach((item: any) => {
                        if (rightCodeList.indexOf(item.Ticket_Code) === -1) {
                          resRight.push(item)
                        }
                      })
                    }

                    listRight.unshift({
                      Pay_Date: '合计',
                      Ticket_Price: rightSum
                    })

                    // 拿到全部的数据 不止差异的
                    setDrawerLeftTableAllData(listLeft)
                    setDrawerRightTableAllData(listRight)

                    if (leftDifferenceList && leftDifferenceList.length > 0) {
                      leftDifferenceList.unshift({
                        SELLMASTER_DATE: '合计',
                        SELLMASTER_AMOUNT: leftSum,
                        Ticket_Price: resRightSum
                      })
                      console.log('leftDifferenceList', leftDifferenceList);
                      leftDifferenceList.forEach((item: any) => {
                        if (item.SELLMASTER_STATETEXT === '人工确认') {
                          setShowLeftText(true)
                        }
                      })
                    }
                    if (resRight && resRight.length > 0) {
                      resRight.unshift({
                        Pay_Date: '合计',
                        Ticket_Price: rightSum
                      })
                    }

                    setLeftDifferenceTableData(leftDifferenceList)
                    setRightDifferenceTableData(resRight)
                    setLeftTableData(leftDifferenceList)
                    setRightTableData(resRight)
                  }
                  setTwoTableLoading(false)
                  return { data: [], success: true }
                }
                if (DifferenceType === 2) {
                  const list: any = []
                  if (data && data.length > 0) {
                    let index: number = 1
                    let SELLMASTER_COUNTSUM: number = 0
                    let SELLMASTER_AMOUNTSUM: number = 0
                    let SELLMASTER_OFFPRICESUM: number = 0
                    data.forEach((item: any) => {
                      if (item.PAYMENT_TYPE_TEXT === '现金') {
                        item.index = index
                        SELLMASTER_COUNTSUM += item.SELLMASTER_COUNT
                        SELLMASTER_AMOUNTSUM += item.SELLMASTER_AMOUNT
                        SELLMASTER_OFFPRICESUM += item.SELLMASTER_OFFPRICE
                        index += 1
                        list.push(item)
                      }
                    })
                    const sumObj: any = {
                      SELLMASTER_DATE: '合计',
                      SELLMASTER_COUNT: SELLMASTER_COUNTSUM,
                      SELLMASTER_AMOUNT: SELLMASTER_AMOUNTSUM,
                      SELLMASTER_OFFPRICE: SELLMASTER_OFFPRICESUM,
                      PAYMENT_TYPE_TEXT: '现金'
                    }
                    list.unshift(sumObj)
                    setLeftTableData(list)

                  }
                  setTwoTableLoading(false)
                  return { data: list, success: true }
                }
              }}
              pagination={false}
              dataSource={leftTableData}
              columnsState={DifferenceType === 1 ? {
                value: columnsStateMap,
                onChange: setColumnsStateMap,
              } : {
                value: columnsStateMapSecond,
                onChange: setColumnsStateMapSecond,
              }}

            // rowClassName={(record)=>!record.Ticket_Price || record?.Ticket_Price===0?'redRow':''}
            />
          </div>
          {
            DifferenceType === 2 ? '' :
              <div style={{ width: '50%' }}>
                <div style={{ display: 'flex', width: '100%', height: '100px', boxSizing: 'border-box', padding: '16px 16px 0', color: 'red' }}>
                  {
                    rightTableData && rightTableData.length > 0 ?
                      <div>
                        <span style={{ display: 'block' }}>{`通道返回出现单独记录，代表本地自然日流水缺失，系统会自动补齐自然日交易数据；`}</span>
                        <span style={{ display: 'block' }} >{`如收银机损坏或未结账，只能靠通道返回信息溯源核对，冲正后自然日报表会发生变化`}</span>
                      </div>
                      : ''
                  }
                </div>
                <ProTable
                  formRef={formRef}
                  actionRef={actionRef}
                  search={false}
                  columns={recordColumns}
                  loading={twoTableLoading}
                  bordered
                  pagination={false}
                  dataSource={rightTableData}
                  columnsState={{
                    value: recordColumnsStateMap,
                    onChange: setRecordColumnsStateMap,
                  }}
                />
              </div>
          }

        </div>
      </div>
    </Drawer>


    {/*   提交结算的备注 */}
    <Modal
      title={
        <div
          style={{
            width: '100%',
            cursor: 'move',
          }}
          onMouseOver={() => {
            if (disabled) {
              setDraggleDisabled(false)
            }
          }}
          onMouseOut={() => {
            setDraggleDisabled(true)
          }}
          onFocus={() => { }}
          onBlur={() => { }}
        >
          {`${compareCurrent?.Serverpart_Name || compareCurrent?.SERVERPART_NAME || ''}-${topProjectDetail?.SERVERPARTSHOP_NAME || ''}-${compareCurrent?.STATISTICS_MONTH || monthTime || ''}月度结算表 `}
        </div>
      }
      okText={'审核确定'}
      open={settlementModal}
      width={1550}
      confirmLoading={monthModalLoading}
      destroyOnClose
      onOk={() => {
        formDescRef.current?.validateFields().then(async (res) => {
          setMonthModalLoading(true)
          const formRes = editFormRef.current?.getFieldValue()
          let [APPOVED_IDS, APPOVED_NAME] = []
          if (res.APPROVALSTAFF_ID) {
            [APPOVED_NAME, APPOVED_IDS] = res.APPROVALSTAFF_ID.split('-')
          }
          console.log('compareCurrent', compareCurrent);
          console.log('topProjectDetail', topProjectDetail);
          console.log('firstTableData', firstTableData);
          const req: any = {
            BusinessapprovalModel: {
              OPERATION_TYPE: 12,
              BUSINESSAPPROVAL_ID: compareCurrent.BUSINESSAPPROVAL_ID || '',
              BUSINESSPROCESS_NAME: `【${compareCurrent?.SETTLEMENT_DATE}】${compareCurrent?.BUSINESSPROJECT_NAME}月度结算`,
              PROINST_ID: compareCurrent?.BUSINESSPROJECT_ID,
              SERVERPART_ID: compareCurrent?.SERVERPART_ID,
              SERVERPART_NAME: compareCurrent?.Serverpart_Name || compareCurrent?.SERVERPART_NAME,
              STAFF_ID: currentUser.ID,
              STAFF_NAME: currentUser.Name,
              BUSINESS_STARTDATE: compareCurrent.BUSINESSAPPROVAL_ID ? compareCurrent?.BusinessProcess_StartDate : moment().format('YYYY-MM-DD HH:mm:ss'),
              // BUSINESS_ENDDATE: compareCurrent?.endTime,
              BUSINESSAPPROVAL_STATE: 1000,
              BUSINESSAPPROVAL_DESC: res.desc,
              SERVERPART_IDS: compareCurrent?.SERVERPART_ID,
              MERCHANTS_ID: topProjectDetail?.MERCHANTS_ID,
              MERCHANTS_NAME: topProjectDetail?.MERCHANTS_NAME,
              SERVERPARTSHOP_ID: compareCurrent?.Id,
              SERVERPARTSHOP_NAME: compareCurrent?.Name,
              APPOVED_IDS,
              APPOVED_NAME
            },
            bizpsplitMonthModel: {
              // topProjectDetail
              // MERCHANTS_ID
              // MERCHANTS_NAME

              ...compareCurrent,
              ...firstTableData[1],
              STATISTICS_MONTH: monthTime || moment(compareCurrent?.SETTLEMENT_DATE).format('YYYY/MM'),
              SHOPROYALTY_ID: compareCurrent?.ShopRoyaltyId,
              SERVERPARTSHOP_ID: compareCurrent?.Id,
              SERVERPARTSHOP_NAME: compareCurrent?.Name,
              BUSINESS_TYPE: compareCurrent?.BusinessType,
              Serverpart_Name: compareCurrent?.SERVERPART_NAME,
              STARTDATE: compareCurrent?.startTime,
              ENDDATE: compareCurrent?.endTime,
              REVENUE_AMOUNT: firstTableData[1].CurMonthRevenue,
              // REVENUEDAILY_AMOUNT:'',
              // DIFDAILY_REVENUE:'',
              ROYALTY_PRICE: firstTableData[1].GUARANTEERATIOAMOUNT,
              // SUBROYALTY_PRICE:'',
              // TICKET_FEE:'',
              ROYALTY_THEORY: firstTableData[1].GUARANTEERATIOINCOME,
              // SUBROYALTY_THEORY:'',
              // MINTURNOVER:'',
              // GUARANTEERATIO:'',
              // NATUREDAY:'',
              // BUSINESSDAYS:'',
              MOBILEPAY_AMOUNT: firstTableData[0].MobilePay,
              CASHPAY_AMOUNT: firstTableData[0].CashPay,
              // OTHERPAY_AMOUNT:'',
              // DIFFERENT_AMOUNT:'',
              // CORRECT_AMOUNT:'',
              ACCREVENUE_AMOUNT: firstTableData[1].REVENUEDAILY_AMOUNTTotal,
              ACCROYALTY_PRICE: firstTableData[1].ROYALTYTHEORYMUST,
              // ACCSUBROYALTY_PRICE:'',
              // ACCTICKET_FEE:'',
              ACCROYALTY_THEORY: firstTableData[1].ROYALTYTHEORYOK,
              // ACCSUBROYALTY_THEORY: '',
              MOBILEPAY_CORRECT: formRes?.MobilePayCorrect || 0,
              CASHPAY_CORRECT: formRes?.CashPayCorrect || 0,
              ACCOUNT_TYPE: 1000,
              BIZPSPLITMONTH_STATE: 2,
              BIZPSPLITMONTH_ID: monethId || ''
            },
            nextApproveState: nextState || ''
          }
          console.log('req', req);
          const data = await handleGetApplyMonthAccountProinst(req)
          if (data.Result_Code === 100) {
            formDescRef.current?.resetFields()
            message.success(data.Result_Desc)

            if (fileList && fileList.length > 0) {
              console.log('fileList', fileList);
              console.log('data', data);
              const detail: any = data.Result_Data

              const formData = new FormData();
              fileList.forEach((item: any) => {
                console.log('item', item);
                formData.append('files[]', item.originFileObj);
                // formData.append('ImageName', item.name);
              })
              formData.append('TableType', '1130');
              formData.append('TableId', detail?.BUSINESSAPPROVAL_ID);
              const success = await uploadAHYDPicture(formData)
              console.log('success', success);
            }


            setSettlementModal(false)
            if (fatherActionRef) {
              setShowCompareDrawer(false)
              fatherActionRef.current?.reload()
            }
          } else {
            message.error(data.Result_Desc)
          }
          setMonthModalLoading(false)
        })

      }}
      onCancel={() => {
        setSettlementModal(false)
        setModalFormValue(undefined)
        formDescRef.current?.resetFields()
      }}
      modalRender={(modal) => {
        return <Draggable
          disabled={disabled}
          bounds={bounds}
          onStart={(event, uiData) => onDraggaleStart(event, uiData)}
        >
          <div ref={draggleRef}>{modal}</div>
        </Draggable>
      }}
    >
      <div>
        <ProForm
          layout={'horizontal'}
          formRef={editFormRef}
          submitter={false}
          initialValues={modalFormValue}
        >
          {/* <Row gutter={16} className={'formBox'}>
            <Col span={6}>
              <ProFormDigit
                name={'MobilePayCorrect'}
                label={'移动支付差额'}
                readonly
                fieldProps={{
                  precision: 2,
                }}
              />
            </Col>
            <Col span={6}>
              <ProFormDigit
                name={'CashPayCorrect'}
                label={'现金支付差额'}
                readonly
                fieldProps={{
                  precision: 2,
                }}
              />
            </Col>
          </Row> */}
        </ProForm>

        <ProTable
          columns={defaultColumns}
          bordered
          style={{ background: '#fff', paddingTop: '10px' }}
          search={false}
          options={false}
          pagination={false}
          loading={tableSecondLoading}
          dataSource={firstTableData}
        />

        <MonthSettlement detail={compareCurrent} />


        <ProForm
          formRef={formDescRef}
          submitter={{
            // 清空表单自带的按钮
            render: (props, doms) => {
              return []
            }
          }}
        >
          <Row>
            <Col span={6}>
              <ProFormSelect
                name="APPROVALSTAFF_ID"
                label="审批人"
                rules={[
                  {
                    required: true,
                    message: '请选择审批人'
                  }
                ]}
                disabled={currentREJECTTYPE}
                request={async () => {
                  const req = {
                    OperationType: 12,
                    CurState: 1000,
                    IsValid: 1,
                    ShowApprovalUser: true,
                    ServerpartIds: compareCurrent?.SERVERPART_ID || '',
                    ShopIds: compareCurrent?.Id || ''
                  }
                  const data = await handleGetAPPROVALROUTEDetail(req)

                  const detailReq: any = {
                    BUSINESSAPPROVALId: compareCurrent?.BUSINESSAPPROVAL_ID || compareCurrent?.BusinessApprovalId
                  }
                  console.log('req', req);
                  let detailData: any = []
                  if (compareCurrent?.BUSINESSAPPROVAL_ID || compareCurrent?.BusinessApprovalId) {
                    detailData = await handleGetBUSINESSAPPROVALDetail(detailReq)
                  }

                  const list: any = []

                  console.log('detailData', detailData);

                  if (detailData.REJECT_TYPE === 2) {
                    const nowPersonList: any = detailData.approveList[detailData.approveList.length - 1]
                    const list: any = [{ label: nowPersonList.REJECT_STAFF, value: `${nowPersonList.REJECT_STAFF}-${nowPersonList.REJECT_ID}` }]
                    formDescRef.current?.setFieldsValue({ APPROVALSTAFF_ID: `${nowPersonList.REJECT_STAFF}-${nowPersonList.REJECT_ID}` })
                    setNextState(nowPersonList?.REJECT_TYPE)
                    setCurrentREJECT_TYPE(true)
                    return list
                  }
                  setCurrentREJECT_TYPE(false)
                  setNextState(undefined)
                  if (data.UserList && data.UserList.length > 0) {
                    data.UserList.forEach((item: any) => {
                      if (item.USER_STATUS === 1) {
                        if (item.USER_STATUS === 1) {
                          list.push({ label: item.USER_NAME, value: `${item.USER_NAME}-${item.USER_ID}` })
                        }
                      }
                    })
                  }
                  if (list && list.length > 0 && list.length === 1) {
                    formDescRef.current?.setFieldsValue({ APPROVALSTAFF_ID: list[0].value })
                  }
                  if (currentUser?.ID === 2785) {
                    list.push({ label: '严琅杰', value: `严琅杰-2785` })
                  }
                  return list


                }}
              />
            </Col>
          </Row>


          <ProFormTextArea
            name="desc"
            label="审核意见"
            rules={[
              {
                required: true,
                message: '请输入备注说明'
              }
            ]}
            initialValue={'已核对，拟同意！'}
          />
          <ProFormUploadButton
            label={"上传月度结算单"}
            name="files"
            fileList={fileList}
            title={"上传月度结算单"}
            fieldProps={{
              onChange: async (info: any) => {
                console.log('info', info);
                // setFileList(info.fileList)
                const { fileList: newFileList } = info;

                // 过滤出有效的图片文件
                const validFileList = newFileList.filter(file => {
                  if (file.type.startsWith('image/')) {
                    return true;
                  }
                  message.error(`${file.name} 不是图片文件，已被移除.`);
                  return false;

                });

                // 更新文件列表
                setFileList(validFileList);
              }
            }}
            buttonProps={{
              children: '上传月度结算单'
            }}
          />



        </ProForm>

        <ReviewProcess compareCurrent={compareCurrent} type={'default'} showReviewProcess={settlementModal} />
      </div>
    </Modal>

    {/* 点击日期 显示的抽屉 */}
    <Drawer
      width="80%"
      className="project-drawer"
      visible={dailyRevenueDetail} // 抽屉弹框是否显示状态
      onClose={() => { // 关闭抽屉 则在清空选中行数据 并 设置抽屉状态为关闭
        setDailyRevenueDetail(false);
        setDailyCurrentRow(undefined);
      }}
      destroyOnClose
      bodyStyle={{ backgroundColor: "#f9f9f9", padding: 0 }}
      closable={false}
    >
      <DailyRevenue dailyCurrentRow={dailyCurrentRow} bottomTableSum={bottomTableSum} topProjectDetail={topProjectDetail} hiddenCorrectAmount={hiddenCorrectAmount} />
    </Drawer>

    <Drawer
      width="80%"
      className="project-drawer"
      visible={showReviewProcess} // 抽屉弹框是否显示状态
      onClose={() => { // 关闭抽屉 则在清空选中行数据 并 设置抽屉状态为关闭
        setShowReviewProcess(false);
      }}
      destroyOnClose
      bodyStyle={{ backgroundColor: "#f9f9f9", padding: 16 }}
      closable={false}
    >
      <ReviewProcess compareCurrent={{
        ...compareCurrent,
        BusinessApprovalId: compareCurrent?.BUSINESSAPPROVAL_ID
      }} showReviewProcess={showReviewProcess} />
    </Drawer>


    <Drawer
      width="80%"
      className="project-drawer"
      visible={showDailyDrawer} // 抽屉弹框是否显示状态
      onClose={() => { // 关闭抽屉 则在清空选中行数据 并 设置抽屉状态为关闭
        setShowDailyDrawer(false);
      }}
      destroyOnClose
      bodyStyle={{ backgroundColor: "#f9f9f9", padding: 16 }}
      closable={false}
    >
      {/* compareCurrent */}
      {showDailyDrawer && <RevenueList BusinessProjectId={compareCurrent.BUSINESSPROJECT_ID} propsBP={compareCurrent}
        propsRC={compareCurrent}
        ShopRoyaltyId={compareCurrent?.ShopRoyaltyId ? compareCurrent?.ShopRoyaltyId : 0}
        ShopIds={compareCurrent?.SERVERPARTSHOP_ID ? compareCurrent?.SERVERPARTSHOP_ID : ''}
        StartDate={moment(compareCurrent?.startTime).format('YYYY-MM-DD')}
        EndDate={moment(compareCurrent?.endTime).format('YYYY-MM-DD')} type={type === 'monthSettlement' ? 'monthSettlement' : 'compareList'}></RevenueList>}
    </Drawer>


    {/* 月度收入抽屉 */}
    <Drawer
      width="85%"
      className="project-drawer"
      visible={showMonthlyDarwer} // 抽屉弹框是否显示状态
      onClose={() => { // 关闭抽屉 则在清空选中行数据 并 设置抽屉状态为关闭
        setShowMonthlyDrawer(false);
        setCurrentMonthly(undefined)
      }}
      destroyOnClose
      bodyStyle={{ backgroundColor: "#f9f9f9" }}
      // , padding: 16
      closable={false}
    >
      {/* MonthDaily本身老的 后来换成RevenueSecondList显示在一起 */}
      {/* <MonthDaily compareCurrent={compareCurrent} showMonthlyDarwer={showMonthlyDarwer} monthTime={monthTime} topProjectDetail={topProjectDetail}/> */}
      <RevenueSecondList BusinessProjectId={compareCurrent?.BUSINESSPROJECT_ID} propsBP={{ ...compareCurrent, DecorateDesc: topProjectDetail?.DecorateDesc }} propsRC={{ ...compareCurrent, DecorateDesc: topProjectDetail?.DecorateDesc }}
        ShopRoyaltyId={compareCurrent?.ShopRoyaltyId ? compareCurrent?.ShopRoyaltyId : 0}
        ShopIds={compareCurrent?.SERVERPARTSHOP_ID ? compareCurrent?.SERVERPARTSHOP_ID : ''}
        StartDate={compareCurrent?.startTime ? moment(compareCurrent?.startTime).format('YYYY-MM-DD') : ''}
        EndDate={moment(compareCurrent?.endTime).format('YYYY-MM-DD')}
        monthTime={moment(monthTime).format('YYYYMM')}
        isHideDescriptions={true} type={'compareList'} topProjectDetail={topProjectDetail}></RevenueSecondList>
    </Drawer>

    {/* 查看附件 */}
    <Modal
      width={500}
      open={showSearchFile}
      title={'上传月度结算单'}
      onOk={() => {

      }}
      footer={false}
      destroyOnClose
      onCancel={() => {
        setShowSearchFile(false)
      }}
    >
      <ProForm
        formRef={uploadFormDescRef}
        submitter={false}
        request={async () => {
          console.log('compareCurrendshdlashdkasgdhaskjldgashdgkt', compareCurrent);

          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('.PNG') === -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')
                        const success = await deleteAHYDPicture(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', compareCurrent?.BUSINESSAPPROVAL_ID);

                      const success = await uploadAHYDPicture(formData)
                      console.log('success', success);
                      if (success) {
                        message.success("上传成功！")
                      }
                      await handleGetFile()
                    }
                  }
                }
              }}
              disabled={isChangeFile ? false : !((compareCurrent?.BUSINESSAPPROVAL_ID && compareCurrent?.Staff_ID === currentUser?.ID && compareCurrent?.Approvalstate !== 9))}
              buttonProps={{
                style: { display: compareCurrent?.BUSINESSAPPROVAL_ID && (compareCurrent?.Staff_ID === currentUser?.ID) && compareCurrent?.Approvalstate !== 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 }}>{compareCurrent?.Staff_Name}</span>上传附件！
            </div>
        }

      </ProForm>

    </Modal>


    {/* 上传附件的悬浮框 */}
    {
      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>
    }
  </div>
}

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