import React, { useEffect } from 'react';
import moment from 'moment';
import numeral from 'numeral';
import ReactToPrint from 'react-to-print';
import ProTable from '@ant-design/pro-table';
import ProCard from '@ant-design/pro-card';
import useRequest from '@ahooksjs/use-request';
import { connect, history } from 'umi';
import { useRef, useState } from 'react';
import { MenuFoldOutlined, WarningTwoTone } from '@ant-design/icons';
import {
  Button, Col, DatePicker, Descriptions, Drawer, message, Modal, Popconfirm, Row, Space, Spin, Tooltip,
  Tree, Typography
} from 'antd';

import type { ConnectState } from '@/models/connect';
import type { ProFormInstance } from '@ant-design/pro-form';
import type { ActionType, ProColumns } from '@ant-design/pro-table';
import type { CurrentUser } from '@/models/user';
import type { MobilePayRoyaltyModel, BankRoyaltyParams, MobilePayRoyaltyRecordModel } from './data';

import { getServerpartTree, handleFormatNumber } from '@/services/options';
import { exportExcel, exportExcelReceivedSum, printOutBody } from '@/utils/utils';
import {
  GetBUSINESSPROJECTSPLITList,
  getList,
  getMobilePayRoyaltyReport,
  getNoShopList,
  getRebuildDailyAccount,
  GetSellMasterCompareList, handleSynchroBANKACCOUNTVERIFY, SynchroBUSINESSPROJECTSPLIT, SynchroREVENUEDAILYSPLIT
} from './service';
import '@/pages/merchantManagement/style.less';
import Merchant from "@/pages/reports/ShopExpenseDetail/detail";
import ProjectDetail from "@/pages/BussinessProject/detail";
import { getProjectDetail } from "@/pages/BussinessProject/service";
import ProjectEditor from "@/pages/BussinessProject/editor";
import noticeIcon from '@/assets/'
import { getYSSellMasterList } from '@/pages/merchantManagement/reports/SalesFlow/service';
import FlowDetail from '@/pages/merchantManagement/reports/SalesFlow/components/FlowDetail';
import type { YSSELLMASTERModel } from '@/pages/merchantManagement/reports/SalesFlow/data';

import './salesFlow.less'
import session from "@/utils/session";
import FlowDrawer from "@/pages/merchantManagement/mobilePayment/bankArrival/components/flowDrawer";
import ReactHTMLTableToExcel from "react-html-table-to-excel";
import ChangeRevenue from "@/pages/reports/shareRoyalty/component/changeRevenue";
import DifferenceAmount from './component/differenceAmount';
import PageTitleBox from '@/components/PageTitleBox';
import LeftSelectTree from '../settlementAccount/component/leftSelectTree';

const { Text } = Typography;

/**
 * @description: 移动支付分账页面
 * @param {currentUser} 当前登录用户信息
 * @return { React.FC } 页面主体
 */

type DetailProps = {
  currentUser?: any
  isComponents?: boolean // 判断是不是当组件
  compareCurrent?: any // 从合同执行情况表里面传入的行数据
}

// const ReportTable = ({ currentUser, isComponents, compareCurrent }: DetailProps) => {

const ReportTable: React.FC<{ currentUser?: CurrentUser, isComponents?: boolean, compareCurrent?: any }> = (props) => {
  const { currentUser, isComponents, compareCurrent } = props

  const { location } = history
  const actionRef = useRef<ActionType>();
  const differenceRef = useRef<ActionType>();
  const formRef = useRef<ProFormInstance>();
  const formRef2 = useRef<ProFormInstance>();
  const formRefAdd = useRef<ProFormInstance>();
  const downloadBtnRef = useRef<any>()
  const ChangeRevenueRef = useRef()

  const [activeKey, setActiveKey] = useState<'1' | '2'>('1'); // 统计类型 1 日报表 2 月报表
  const [currentRow, setCurrentRow] = useState<any>(); // 当前选中行
  const [startTime, setStartTime] = useState<any>()// 开始时间
  const [endTime, setEndTime] = useState<any>()// 结束时间
  const [showDetail, setShowDetail] = useState<boolean>(false) // 是否显示详情
  const [reqDetailList, setReqDetailList] = useState<MobilePayRoyaltyModel[]>(); // 导出excel表格
  const [printOut, setPrintOut] = useState<any>(); // 打印数据的内容
  const [showWarningDrawer, setShowWarningDrawer] = useState<boolean>(false)// 显示异常的抽屉
  const [noShopList, setNoShopList] = useState<any>()
  const [expandRow, setExpandRow] = useState<string[]>([]); // 选择打开的服务区
  const [showNewDetail, setShowNewDetail] = useState<boolean>(false)
  const [showNewAdd, setShowNewAdd] = useState<boolean>(false)
  const [collapsible, setCollapsible] = useState<boolean>(false)
  const [selectedId, setSelectedId] = useState<string>()
  // 显示单位:元旁边符号出现的悬浮框
  const [showNotice, setShowNotice] = useState<boolean>(false)
  // ProTable上方计算的汇总信息数据
  const [reduceTableData, setReduceTableData] = useState<any>()
  const [tableStart, setTableStart] = useState<any>()
  const [tableEnd, setTableEnd] = useState<any>()
  // 显示业主分润的顶层悬浮框
  const [showFirstNotice, setShowFirstNotice] = useState<boolean>(false)
  // 悬浮框的X轴坐标
  const [noticeX, setNoticeX] = useState<number>(0)
  // 悬浮框的Y轴坐标
  const [noticeY, setNoticeY] = useState<number>(0)
  // 拿到当前服务区id
  const [currentServerpartId, setCurrentServerpartId] = useState<any>()
  // 拿到当前的片区id
  const [currentSPRegionTypeID, setCurrentSPRegionTypeID] = useState<string>()
  const [tableDiffDays, setTableDiffDays] = useState<any>()
  // 所有管理中心的项目合计
  const [allProjectSum, setAllProjectSum] = useState<number>()
  // 流水抽屉
  const [flowDrawer, setFlowDrawer] = useState<boolean>(false)
  // 流水抽屉详情
  const [flowDetailList, setFlowDetailList] = useState<any>()
  // 流水悬浮框
  const [visible, setVisible] = useState<boolean>(false)
  // 移动支付分账报表的搜索时间
  const [bigSearchTime, setBigSearchTime] = useState<any>()
  const { loading: treeLoading, data: treeView } = useRequest(async () => {
    return getServerpartTree(currentUser?.ProvinceCode, currentUser?.CityAuthority, true, false, true)
  }) // 获取用户服务区权限树
  // 统计时间
  const [statisticsTime, setStatisticsTime] = useState<any>()
  // 判断统计时间是否是同一天
  const [statisticsSame, setStatisticsSame] = useState<boolean>(true)
  // 差额的抽屉
  const [differenceDrawer, setDifferenceDrawer] = useState<boolean>(false)
  // 点开悬浮的选择时间 拿到老的一份统计时间
  const { RangePicker } = DatePicker;
  // 移动支付分账报表的真实搜索时间
  const [realSearchTime, setRealSearchTime] = useState<any>()
  // 项目详情
  const [projectDetail, setProjectDetail] = useState<any>()
  // 有计算公式的流水抽屉
  const [haveFlowDrawer, setHaveFlowDrawer] = useState<boolean>()
  // 抽屉的加载框
  const [drawerLoading, setDrawerLoading] = useState<boolean>(false)
  // 表格第一层的商家到账是否可以点击展开
  const [isFirstFloorClick, setIsFirstFloorClick] = useState<boolean>(false)
  // 表格加载效果
  const [tableLoading, setTableLoading] = useState<boolean>(false)
  // 页面主要表格的加载效果
  const [mainTableLoading, setMainTableLoading] = useState<boolean>(false)
  const SETTLEMENTMODESOBJ = session.get('SETTLEMENT_MODESObj')
  // 是否显示打印的表格
  const [showExportTable, setShowExportTable] = useState<boolean>(false)
  // 重新生成的加载效果
  const [showLoading, setShowLoading] = useState<boolean>(false)
  // 调整业主到账的差异的抽屉
  const [changeRevenueDrawer, setChangeRevenueDrawer] = useState<boolean>(false)
  // 拿到调成差异的新备注
  const [allNewDesc, setAllNewDesc] = useState<string>()
  // 修改的门店数据列表
  const [drawerShopDataList, setDrawerShopDataList] = useState<any>()
  // 导出excel表格的数据
  const [exportTableData, setExportTableData] = useState<any>()
  // 表格搜索条件
  const [searchParams, setSearchParams] = useState<any>()
  // 移动支付分账统计列表
  const columns: ProColumns<MobilePayRoyaltyModel>[] = [
    {
      dataIndex: 'DataType',
      // title: '统计方式',
      valueType: "radioButton",
      initialValue: '1',
      // colSize: 1,
      colSpan: 2,
      valueEnum: {
        2: { text: '月报' },
        1: { text: '日报' },
      },
      hideInTable: true,
      fieldProps: {
        onChange: (event: any) => {
          setActiveKey(event.target.value)
          formRef.current?.submit()
        },
        labelCol: { span: 0 },
        wrapperCol: { span: 24 }
      },
    },
    {
      title: '统计时间',
      dataIndex: 'search_date',
      valueType: 'dateRange',
      hideInTable: true,
      hideInDescriptions: true,
      hideInSearch: activeKey === '2',
      initialValue: location.query?.StartDate ? [location.query?.StartDate, location.query?.EndDate] :
        // [moment().subtract(1, 'months').startOf('day').format('YYYY-MM-DD'), moment().subtract(1, 'day').startOf('day').format('YYYY-MM-DD')],
        [moment().subtract(1, 'day').format('YYYY-MM-DD'), moment().subtract(1, 'day').format('YYYY-MM-DD')],
      search: {
        transform: (value) => {
          return {
            StartDate: value[0],
            EndDate: value[1],
          };
        },
      },
      fieldProps: {
        disabledDate: (current: any) => current && current > moment().endOf('day')
      }
    },
    {
      title: '统计月份',
      dataIndex: 'search_months',
      valueType: "dateRange",
      hideInTable: true,
      hideInDescriptions: true,
      hideInSearch: activeKey === '1',
      initialValue: [moment().startOf("month").format('YYYY-MM-DD'), moment().subtract(1, "days").format('YYYY-MM-DD')],
      search: {
        transform: (value) => {
          return {
            StartDate: moment(value[0]).startOf("month").format('YYYY-MM-DD'),
            EndDate: moment(value[1]).endOf("month").format('YYYY-MM-DD'),
          };
        },
      },
      fieldProps: {
        picker: "month",
        format: 'YYYY-MM',
        // disabledDate: (current: any) => current && current > moment().subtract(2, 'months').startOf("month")
      }
    },
    {
      dataIndex: 'index',
      // title: () => <Text strong>服务区信息</Text>,
      title: '服务区信息',
      hideInSearch: true,
      valueType: 'index',
      align: 'center',
      children: [
        {
          title: '序号',
          dataIndex: 'index',
          key: 'index',
          valueType: 'index',
          align: 'center',
          width: 70,
          render: (_, record) => {
            // return (!record?.Serverpart_ID || record?.Serverpart_ID === null) ? '' : _?.props.text + 1
            return record.index
          },
        },
        {
          title: '服务区/门店',
          dataIndex: 'shopName',
          key: 'shopName',
          width: 250,
          ellipsis: true,
          hideInSearch: true,
          render: (_, record) => {
            if (record?.Statistics_Date) {
              return <a onClick={() => {
                setCurrentRow(record);
                setShowDetail(true);
              }}>{record?.Statistics_Date}</a>
            }
            // if (record?.ServerpartShop_Name && record?.Business_Unit){
            //   return <p><span>{record.ServerpartShop_Name}</span><span style={{marginLeft:'10px'}}>{record.Business_Unit}</span></p>
            // }
            return <span style={{
              color:
                record?.ServerpartShop_Name && !record?.ServerpartShop_ID ? '#1890ff' : record?.Show_Warning ? 'red' : '', cursor: 'pointer'
            }} onClick={async () => {
              if (record?.ServerpartShop_Name && !record?.ServerpartShop_ID) {
                if (record?.BusinessProject_ID) {
                  const data = await getProjectDetail(record?.BusinessProject_ID)
                  setCurrentRow(data);
                  setShowNewDetail(true)
                } else {
                  setCurrentServerpartId(record.Serverpart_ID)
                  setCurrentSPRegionTypeID(record.SPRegionType_ID)
                  const current = {
                    PROJECT_VALID: 1,
                    MULTIPROJECT_STATE: 0,
                    SEGMENTED_MODE: 1
                  }
                  formRefAdd.current?.setFieldsValue(current)
                  setCurrentRow(current)
                  setShowNewAdd(true)
                }
              }

            }}>
              {record?.ServerpartShop_Name ? record?.ServerpartShop_Name : record?.Serverpart_Name ? record?.Serverpart_Name : record?.SPRegionType_Name ? record?.SPRegionType_Name : ''}
              {/* {record?.SPRegionType_Name ? record?.SPRegionType_Name : record?.Serverpart_Name ? record?.Serverpart_Name : record?.ServerpartShop_Name} */}
              {/* {record?.SPRegionType_Name?`${record?.SPRegionType_Name}[${record?.Project_Count}]`:record?.Serverpart_Name ? record?.Serverpart_Name : record?.ServerpartShop_Name} */}
            </span>
          }
        },
        {
          title: '项目数量',
          dataIndex: 'Project_Count',
          align: 'right',
          width: 80,
          render: (_, record) => {
            return !record?.SPRegionType_Name && !record?.Serverpart_Name ? '' : record?.Project_Count
          }
        },
        {
          title: '经营商家',
          dataIndex: 'Business_Unit',
          ellipsis: true,
          width: 150,
          key: 'Business_Unit',
          hideInSearch: true,
          render: (_, record) => {
            // 说是修改掉 这里只显示经营商家 红色字的情况 移到项目到账
            return <span style={{
              // color:
              //   record?.Show_Warning ? 'red' : ''
            }}>
              {record?.Business_Unit || ''}
              {/* { */}
              {/*   record?.Show_Warning ? record?.BusinessProject_ID ? '结算模式错误,请修改' : '未建经营项目,请添加' : record?.Business_Unit */}
              {/* } */}
              {/* { */}
              {/*   !record?.Royalty_Price && !record?.RoyaltyProject_Price && !record?.Royalty_DiffPrice?record?.Business_Unit: */}
              {/*   !record?.RoyaltyProject_Price && record?.ServerpartShop_Name && !record?.ServerpartShop_ID? */}
              {/*   record?.BusinessProject_ID?'结算模式错误,请修改':'未建经营项目,请添加' */}
              {/*   :record?.Business_Unit */}
              {/* } */}
            </span>
          }
        }
      ]
    },
    {
      // title: () => <Text strong>合计',
      title: '业主分润',
      hideInSearch: true,
      align: 'center',
      children: [
        {
          title: <Tooltip title={`取客无忧接口返回本地的业主到账数据\n(如真实打款存在差异需要联系客无忧处理)`}>
            <span>{'银行到账'}</span>
          </Tooltip>,
          dataIndex: 'Royalty_Price',
          width: 105,
          align: 'right',
          sorter: (a, b) => a.Royalty_Price - b.Royalty_Price,
          render: (_, record) => {
            return record?.Royalty_Price ? numeral(record.Royalty_Price).format('0,0.00') : '-'
          },
        },
        {
          title: <Tooltip title={`根据自然日流水拆分的数据(如自然日流水缺失将无法拆分)`}>
            <span>{'项目到账'}</span>
          </Tooltip>,
          width: 105,
          dataIndex: 'RoyaltyProject_Price',
          align: 'right',
          sorter: (a, b) => a.RoyaltyProject_Price - b.RoyaltyProject_Price,
          render: (_, record) => {
            const isRed: boolean = (record?.MobilePay_Price > record?.Ticket_Price) && statisticsSame
            // return isRed?<a style={{color:'red',cursor:'pointer'}} onClick={()=>{
            //   if (record?.ServerpartShop_Name && !record?.ServerpartShop_Code){
            //     console.log('record',record)
            //     setCurrentRow(record)
            //     setChangeRevenueDrawer(true)
            //   }
            // }}>
            //   {record?.ServerpartShop_Name && !record?.ServerpartShop_Code?'调整差异':record?.RoyaltyProject_Price ? numeral(record.RoyaltyProject_Price).format('0,0.00') : '-'}
            //
            //   {/* {record?.RoyaltyProject_Price ? numeral(record.RoyaltyProject_Price).format('0,0.00') : '-'} */}
            // </a>:<span onClick={()=>{
            //
            //   console.log('statisticsSame',statisticsSame)
            // }}>
            //   {record?.RoyaltyProject_Price ? numeral(record.RoyaltyProject_Price).format('0,0.00') : '-'}
            // </span>
            return <span onClick={() => {
              console.log('statisticsSame', statisticsSame)
            }}>
              {record?.RoyaltyProject_Price ? numeral(record.RoyaltyProject_Price).format('0,0.00') : '-'}
            </span>
          },
        },
        {
          title: '差额',
          width: 105,
          dataIndex: 'Royalty_DiffPrice',
          align: 'right',
          sorter: (a, b) => a.Royalty_DiffPrice - b.Royalty_DiffPrice,
          render: (_, record) => {
            const isRed: boolean = (record?.MobilePay_Price > record?.Ticket_Price) && statisticsSame
            return isRed ? <Tooltip title={`本地流水(${record?.MobilePay_Price || 0}) > 上游流水(${record?.Ticket_Price || 0})`}>
              <a style={{ color: 'red', cursor: 'pointer' }} onClick={async () => {
                console.log('record', record);
                if (record?.ServerpartShop_Name && !record?.ServerpartShop_Code) {
                  console.log('record', record)
                  setCurrentRow(record)
                  setChangeRevenueDrawer(true)
                } else if (record?.ServerpartShop_Name && record?.ServerpartShop_Code) {
                  if (record?.ServerpartShop_Code && record?.Ticket_Price - record?.MobilePay_Price !== 0) {
                    if (bigSearchTime && bigSearchTime.length > 0) {
                      if (moment(statisticsTime[0]).format('YYYYMMDD') === moment(statisticsTime[1]).format('YYYYMMDD')) {
                        setShowLoading(true)
                        const req = {
                          StatisticsDate: moment(statisticsTime[0]).format('YYYY-MM-DD'),
                          ServerpartShopId: record?.ServerpartShop_ID,
                        }
                        const data = await getRebuildDailyAccount(req)
                        if (data.Result_Code === 100) {
                          message.success(data.Result_Desc)
                        } else {
                          message.error(data.Result_Desc)
                        }
                        actionRef.current?.reload()
                        setShowLoading(false)
                      } else {
                        message.error('统计时间为同一天才能重新生成！')
                      }
                    }
                  }
                }
              }}>
                {/* {record?.ServerpartShop_Name && !record?.ServerpartShop_Code ? '调整差异' : record?.RoyaltyProject_Price ? numeral(record.RoyaltyProject_Price).format('0,0.00') : '-'} */}
                {'调整差异'}
                {/* {record?.RoyaltyProject_Price ? numeral(record.RoyaltyProject_Price).format('0,0.00') : '-'} */}
              </a>
            </Tooltip>
              : <span style={{ color: record?.Royalty_DiffPrice ? 'red' : '' }}>
                {record?.Royalty_DiffPrice ? numeral(record.Royalty_DiffPrice).format('0,0.00') : '-'}
              </span>
          },
        },
      ]
    },
    {
      // title: () => <Text strong>合计',
      title: '交易到账',
      hideInSearch: true,
      children: [
        // {
        //     title: '交易金额',
        //     dataIndex: 'Ticket_Price',
        //     align: 'right',
        //     width: 100,
        //     sorter: (a, b) => {
        //         return a.Ticket_Price - b.Ticket_Price
        //     },
        //     render: (_, record) => {
        //         return record?.Ticket_Price ? numeral(record.Ticket_Price).format('0,0.00') : '-'
        //     },
        // },
        {
          title: <Tooltip title={`收银系统上传的自然日报表数据`}>
            <span>{'本地流水'}</span>
          </Tooltip>,
          dataIndex: 'MobilePay_Price',
          width: 120,
          align: 'right',
          hideInSearch: true,
          sorter: (a, b) => {
            return a.MobilePay_Price - b.MobilePay_Price
          },
          render: (_, record) => {
            return <>
              {
                (record?.ServerpartShop_Name && !record?.ServerpartShop_ID) ?
                  <span style={{ color: '#1890ff', cursor: 'pointer' }}
                    onClick={() => {
                      // setCurrentRow(record)
                      // setFlowDrawer(true)
                      console.log('record', record)
                      const res = JSON.parse(JSON.stringify(record))
                      console.log('statisticsTime', statisticsTime);
                      console.log('searchParams', searchParams);
                      const time = searchParams?.EndDate
                      res.Statistics_Date = moment(time).format('YYYY-MM-DD')
                      res.BusinessProject_Id = record.BusinessProject_ID
                      res.ServerpartShop_ID = record.newServerpartShop_ID
                      res.Serverpart_Name = record.newServerpart_Name
                      console.log('res', res)
                      setCurrentRow(res);
                      setHaveFlowDrawer(true);
                    }}>
                    {record?.MobilePay_Price ? numeral(record.MobilePay_Price).format('0,0.00') : '-'}
                  </span> :
                  <span>{record?.MobilePay_Price ? numeral(record.MobilePay_Price).format('0,0.00') : '-'}</span>

                //   : record.type === 'shop' ?<span style={{color:'#faad14', cursor: 'pointer'}} onClick={()=>{
                //   const res = JSON.parse(JSON.stringify(record))
                //   res.Statistics_Date = moment(statisticsTime[1]).format('YYYY-MM-DD')
                //   res.BusinessProject_Id = record.BusinessProject_ID
                //   setCurrentRow(res);
                //   setHaveFlowDrawer(true);
                // }}>{record?.MobilePay_Price ? numeral(record.MobilePay_Price).format('0,0.00') : '-'}</span> :
              }
            </>
          },
        },
        {
          title: <Tooltip title={`取客无忧接口返回的分账流水交易总金额`}>
            <span>{'上游流水'}</span>
          </Tooltip>,
          dataIndex: 'Ticket_Price',
          align: 'right',
          width: 110,
          hideInSearch: true,
          sorter: (a, b) => {
            return a.Ticket_Price - b.Ticket_Price
          },
          render: (_, record) => {
            return record?.Ticket_Price ? numeral(record.Ticket_Price).format('0,0.00') : '-'
          },
        },
        {
          title: '差额',
          dataIndex: '',
          width: 110,
          hideInSearch: true,
          sorter: (a, b) => {
            return (a.Ticket_Price - a.MobilePay_Price) - (b.Ticket_Price - b.MobilePay_Price)
          },
          render: (_, record) => {
            const num = record?.Ticket_Price - record?.MobilePay_Price
            return <span style={{ color: num > 0 ? '#60cf60' : num < 0 ? 'red' : '', cursor: (record?.ServerpartShop_Code && record?.Ticket_Price - record?.MobilePay_Price !== 0) || (record?.index && record?.index.indexOf('.') !== -1 && record?.Ticket_Price - record?.MobilePay_Price !== 0) ? 'pointer' : '' }} onClick={async () => {
              if (record?.index && record?.index.indexOf('.') !== -1 && record?.Ticket_Price - record?.MobilePay_Price !== 0) {
                const res: any = formRef.current?.getFieldsValue()
                console.log('res', res);
                const [start, end] = res.search_date
                if (moment(start._d).format('YYYY-MM-DD') === moment(end._d).format('YYYY-MM-DD')) {
                  console.log('1', moment(start._d).format('YYYY-MM-DD'));
                  console.log('2', moment(end._d).format('YYYY-MM-DD'));
                  setCurrentRow(record)
                  setDifferenceDrawer(true)
                }

                // const data = await getProjectDetail(record?.BusinessProject_ID)
                // setProjectDetail(data)
              }
            }}>
              {numeral(record?.Ticket_Price - record?.MobilePay_Price).format('0,0.00')}
            </span>
          },
        },
        // {
        //   title: '到账金额',
        //   dataIndex: 'Account_Price',
        //   align: 'right',
        //   width: 110,
        //   sorter: (a, b) => {
        //     return a.Account_Price - b.Account_Price
        //   },
        //   render: (_, record) => {
        //     return record?.Account_Price ? numeral(record.Account_Price).format('0,0.00') : '-'
        //   },
        // },
      ]
    },
    {
      // title: () => <Text strong>合计',
      title: '商家分润',
      hideInSearch: true,
      children: [
        {
          title: <Tooltip title={`=上游流水-银行到账-手续费`}>
            <span>{'到账金额'}</span>
          </Tooltip>,
          dataIndex: 'SubRoyalty_Price',
          width: 105,
          align: 'right',
          sorter: (a, b) => a.SubRoyalty_Price - b.SubRoyalty_Price,
          render: (_, record) => {
            return record?.SubRoyalty_Price ? numeral(record.SubRoyalty_Price).format('0,0.00') : '-'
          },
        },
        {
          title: '手续费',
          dataIndex: 'Ticket_Fee',
          width: 105,
          align: 'right',
          sorter: (a, b) => a.Ticket_Fee - b.Ticket_Fee,
          render: (_, record) => {
            return record?.Ticket_Fee ? numeral(record.Ticket_Fee).format('0,0.00') : '-'
          },
        },
      ]
    },

  ];
  // 表格的导出columns
  const exportColumns: any = [
    {
      dataIndex: 'index',
      title: '服务区信息',
      hideInSearch: true,
      valueType: 'index',
      align: 'center',
      children: [
        {
          title: '管理中心',
          dataIndex: 'SPRegionType_Name',
          hideInSearch: true,
        },
        {
          title: '服务区',
          dataIndex: 'Serverpart_Name',
          hideInSearch: true,
        },
        {
          title: '门店',
          dataIndex: 'ServerpartShop_Name',
          hideInSearch: true,
        },
        {
          title: '经营商家',
          dataIndex: 'Business_Unit',
          hideInSearch: true,
          // render: (_, record) => {
          //   return <span style={{
          //     color:
          //       record?.Show_Warning ? 'red' : ''
          //   }}>
          //     {
          //       record?.Show_Warning ? record?.BusinessProject_ID ? '' : '' : record?.Business_Unit
          //     }
          //   </span>
          // }
        },
      ]
    },
    {
      // title: () => <Text strong>合计',
      title: '业主分润',
      hideInSearch: true,
      align: 'center',
      children: [
        {
          title: <Tooltip title={`取客无忧接口返回本地的业主到账数据\n(如真实打款存在差异需要联系客无忧处理)`}>
            <span>{'银行到账'}</span>
          </Tooltip>,
          dataIndex: 'Royalty_Price',
          width: 105,
          align: 'right',
          sorter: (a, b) => a.Royalty_Price - b.Royalty_Price,
          render: (_, record) => {
            return <span>{record?.Royalty_Price ? handleFormatNumber(record?.Royalty_Price) : '0.00'}</span>
          },
        },
        {
          title: <Tooltip title={`根据自然日流水拆分的数据(如自然日流水缺失将无法拆分)`}>
            <span>{'项目到账'}</span>
          </Tooltip>,
          width: 105,
          dataIndex: 'RoyaltyProject_Price',
          align: 'right',
          sorter: (a, b) => a.RoyaltyProject_Price - b.RoyaltyProject_Price,
          render: (_, record) => {
            const isRed: boolean = (record?.MobilePay_Price > record?.Ticket_Price)
            return isRed ? <a style={{ color: 'red', cursor: 'pointer' }} onClick={() => {
              if (record?.ServerpartShop_Name && !record?.ServerpartShop_Code) {
                console.log('record', record)
                setCurrentRow(record)
                setChangeRevenueDrawer(true)
              }
            }}>
              {record?.ServerpartShop_Name && !record?.ServerpartShop_Code ? '调整差异' : record?.RoyaltyProject_Price ? numeral(record.RoyaltyProject_Price).format('0,0.00') : '-'}

              {/* {record?.RoyaltyProject_Price ? numeral(record.RoyaltyProject_Price).format('0,0.00') : '-'} */}
            </a> : <span>
              {/* {record?.RoyaltyProject_Price ? numeral(record.RoyaltyProject_Price).format('0,0.00') : '-'} */}

              {record?.RoyaltyProject_Price ? handleFormatNumber(record?.RoyaltyProject_Price) : '0.00'}
            </span>
          },
        },
        {
          title: '差额',
          width: 105,
          dataIndex: 'Royalty_DiffPrice',
          align: 'right',
          sorter: (a, b) => a.Royalty_DiffPrice - b.Royalty_DiffPrice,
          render: (_, record) => {
            return <span style={{ color: record?.Royalty_DiffPrice ? 'red' : '' }}>
              {/* {record?.Royalty_DiffPrice ? numeral(record.Royalty_DiffPrice).format('0,0.00') : '-'} */}
              {record?.Royalty_DiffPrice ? handleFormatNumber(record?.Royalty_DiffPrice) : '0.00'}
            </span>
          },
        },
      ]
    },
    {
      // title: () => <Text strong>合计',
      title: '交易到账',
      hideInSearch: true,
      children: [
        // {
        //     title: '交易金额',
        //     dataIndex: 'Ticket_Price',
        //     align: 'right',
        //     width: 100,
        //     sorter: (a, b) => {
        //         return a.Ticket_Price - b.Ticket_Price
        //     },
        //     render: (_, record) => {
        //         return record?.Ticket_Price ? numeral(record.Ticket_Price).format('0,0.00') : '-'
        //     },
        // },
        {
          title: <Tooltip title={`收银系统上传的自然日报表数据`}>
            <span>{'本地流水'}</span>
          </Tooltip>,
          dataIndex: 'MobilePay_Price',
          width: 120,
          align: 'right',
          hideInSearch: true,
          sorter: (a, b) => {
            return a.MobilePay_Price - b.MobilePay_Price
          },
          render: (_, record) => {
            return <>
              {
                (record?.ServerpartShop_Name && !record?.ServerpartShop_ID) ?
                  <span style={{ color: '#1890ff', cursor: 'pointer' }}
                    onClick={() => {
                      // setCurrentRow(record)
                      // setFlowDrawer(true)
                      const res = JSON.parse(JSON.stringify(record))
                      res.Statistics_Date = moment(statisticsTime[1]).format('YYYY-MM-DD')
                      res.BusinessProject_Id = record.BusinessProject_ID
                      res.ServerpartShop_ID = record.newServerpartShop_ID
                      res.Serverpart_Name = record.newServerpart_Name
                      setCurrentRow(res);
                      setHaveFlowDrawer(true);
                    }}>
                    {/* {record?.MobilePay_Price ? numeral(record.MobilePay_Price).format('0,0.00') : '-'} */}
                    {record?.MobilePay_Price ? handleFormatNumber(record?.MobilePay_Price) : '0.00'}
                  </span> :
                  <span>
                    {/* {record?.MobilePay_Price ? numeral(record.MobilePay_Price).format('0,0.00') : '-'} */}
                    {record?.MobilePay_Price ? handleFormatNumber(record?.MobilePay_Price) : '0.00'}
                  </span>

                //   : record.type === 'shop' ?<span style={{color:'#faad14', cursor: 'pointer'}} onClick={()=>{
                //   const res = JSON.parse(JSON.stringify(record))
                //   res.Statistics_Date = moment(statisticsTime[1]).format('YYYY-MM-DD')
                //   res.BusinessProject_Id = record.BusinessProject_ID
                //   setCurrentRow(res);
                //   setHaveFlowDrawer(true);
                // }}>{record?.MobilePay_Price ? numeral(record.MobilePay_Price).format('0,0.00') : '-'}</span> :
              }
            </>
          },
        },
        {
          title: <Tooltip title={`取客无忧接口返回的分账流水交易总金额`}>
            <span>{'上游流水'}</span>
          </Tooltip>,
          dataIndex: 'Ticket_Price',
          align: 'right',
          width: 110,
          hideInSearch: true,
          sorter: (a, b) => {
            return a.Ticket_Price - b.Ticket_Price
          },
          render: (_, record) => {
            // return record?.Ticket_Price ? numeral(record.Ticket_Price).format('0,0.00') : '-'
            return record?.Ticket_Price ? handleFormatNumber(record?.Ticket_Price) : '0.00'
          },
        },
        {
          title: '差额',
          dataIndex: '',
          width: 110,
          hideInSearch: true,
          sorter: (a, b) => {
            return (a.Ticket_Price - a.MobilePay_Price) - (b.Ticket_Price - b.MobilePay_Price)
          },
          render: (_, record) => {
            const num = record?.Ticket_Price - record?.MobilePay_Price
            return <span style={{ color: num > 0 ? '#60cf60' : num < 0 ? 'red' : '', cursor: (record?.ServerpartShop_Code && record?.Ticket_Price - record?.MobilePay_Price !== 0) || (record?.index && record?.index.indexOf('.') !== -1 && record?.Ticket_Price - record?.MobilePay_Price !== 0) ? 'pointer' : '' }} onClick={async () => {
              if (record?.ServerpartShop_Code && record?.Ticket_Price - record?.MobilePay_Price !== 0) {
                if (bigSearchTime && bigSearchTime.length > 0) {
                  if (moment(statisticsTime[0]).format('YYYYMMDD') === moment(statisticsTime[1]).format('YYYYMMDD')) {
                    setShowLoading(true)
                    const req = {
                      StatisticsDate: moment(statisticsTime[0]).format('YYYY-MM-DD'),
                      ServerpartShopId: record?.ServerpartShop_ID,
                    }
                    const data = await getRebuildDailyAccount(req)
                    if (data.Result_Code === 100) {
                      message.success(data.Result_Desc)
                    } else {
                      message.error(data.Result_Desc)
                    }
                    actionRef.current?.reload()
                    setShowLoading(false)
                  } else {
                    message.error('统计时间为同一天才能重新生成！')
                  }
                }
              } else if (record?.index && record?.index.indexOf('.') !== -1 && record?.Ticket_Price - record?.MobilePay_Price !== 0) {
                setCurrentRow(record)
                setDifferenceDrawer(true)
                const data = await getProjectDetail(record?.BusinessProject_ID)
                setProjectDetail(data)
              }
            }}>

              {record?.Ticket_Price ? handleFormatNumber(record?.Ticket_Price - record?.MobilePay_Price) : '0.00'}
              {/* {numeral(record?.Ticket_Price - record?.MobilePay_Price).format('0,0.00')} */}
            </span>
          },
        },
        // {
        //   title: '到账金额',
        //   dataIndex: 'Account_Price',
        //   align: 'right',
        //   width: 110,
        //   sorter: (a, b) => {
        //     return a.Account_Price - b.Account_Price
        //   },
        //   render: (_, record) => {
        //     return record?.Account_Price ? numeral(record.Account_Price).format('0,0.00') : '-'
        //   },
        // },
      ]
    },
    {
      // title: () => <Text strong>合计',
      title: '商家分润',
      hideInSearch: true,
      children: [
        {
          title: <Tooltip title={`=上游流水-银行到账-手续费`}>
            <span>{'到账金额'}</span>
          </Tooltip>,
          dataIndex: 'SubRoyalty_Price',
          width: 105,
          align: 'right',
          sorter: (a, b) => a.SubRoyalty_Price - b.SubRoyalty_Price,
          render: (_, record) => {
            // return record?.SubRoyalty_Price ? numeral(record.SubRoyalty_Price).format('0,0.00') : '-'
            return record?.SubRoyalty_Price ? handleFormatNumber(record?.SubRoyalty_Price) : '0.00'
          },
        },
        {
          title: '手续费',
          dataIndex: 'Ticket_Fee',
          width: 105,
          align: 'right',
          sorter: (a, b) => a.Ticket_Fee - b.Ticket_Fee,
          render: (_, record) => {
            // return record?.Ticket_Fee ? numeral(record.Ticket_Fee).format('0,0.00') : '-'
            return record?.Ticket_Fee ? handleFormatNumber(record?.Ticket_Fee) : '0.00'
          },
        },
      ]
    },
  ]
  // 移动支付流水清单
  const columnsRecord: ProColumns<MobilePayRoyaltyRecordModel>[] = [
    {
      dataIndex: 'Ticket_Code',
      title: '订单编号',
      align: 'center',
      hideInTable: true,
      hideInDescriptions: true,
      colSize: 2
    },
    {
      // title: () => <Text strong>合计',
      title: '订单信息',
      hideInSearch: true,
      children: [
        {
          dataIndex: 'Pay_Date',
          title: '交易时间',
          align: 'center',
          hideInSearch: true,
          hideInDescriptions: true,
          sorter: true,
          defaultSortOrder: 'descend',
        },
        {
          dataIndex: 'Ticket_Code',
          title: '订单编号',
          align: 'center',
          hideInDescriptions: 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,
        },
      ]
    },
    {
      // title: () => <Text strong>合计',
      title: '商家分润',
      hideInSearch: true,
      children: [
        {
          dataIndex: 'SubRoyalty_Price',
          title: '到账金额',
          align: 'right',
          hideInSearch: true,
          hideInDescriptions: true,
        },
        {
          dataIndex: 'Ticket_Fee',
          title: '手续费',
          align: 'right',
          hideInSearch: true,
          hideInDescriptions: true,
        },
      ]
    },
    {
      // title: () => <Text strong>合计',
      title: '业主分润',
      hideInSearch: true,
      children: [
        {
          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 flowColumns: ProColumns<YSSELLMASTERModel>[] = [

    {
      dataIndex: 'index',
      title: '序号',
      hideInSearch: true,
      valueType: 'index',
      fixed: true,
      align: 'center',
      width: 48,
    },
    {
      dataIndex: 'SELLMASTER_DATE',
      valueType: "dateRange",
      title: '销售时间',
      align: 'center',
      initialValue: bigSearchTime || [moment().subtract(1, 'day').startOf('day').format('YYYY-MM-DD'), moment().subtract(1, 'day').startOf('day').format('YYYY-MM-DD')],
      render: (_, record) => {
        return record?.SELLMASTER_DATE
      },
      fieldProps: {
        disabledDate: (current: any) => current && current > moment()
      },
      search: {
        transform: (value) => {
          return {
            SELLMASTER_DATE_Start: moment(value[0]).format('YYYY-MM-DD'),
            SELLMASTER_DATE_End: moment(value[1]).format('YYYY-MM-DD'),
          };
        },
      },
    },
    {
      dataIndex: 'TICKET_CODE',
      title: '小票编号',
      hideInSearch: true,
      align: 'center',
    },
    {
      dataIndex: 'SELLMASTER_COUNT',
      title: '销售数量',
      hideInSearch: true,
      align: 'right',
      sorter: (a, b) => a.SELLMASTER_COUNT - b.SELLMASTER_COUNT
    },


    {
      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',
    },

    {
      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 differenceColums: any = [
    {
      title: '收银系统',
      dataIndex: '',
      children: [
        {
          title: '服务区名称',
          dataIndex: 'ServerpartName',
          align: 'center',
        },
        {
          title: '门店名称',
          dataIndex: 'ServerpartShopName',
          align: 'center',
        },
        {
          title: '收银机号',
          dataIndex: 'MachineCode',
          align: 'center',
        },
        {
          title: '交易时间',
          dataIndex: 'PayDateStr',
          align: 'center',
        },
        {
          title: '订单金额',
          dataIndex: 'MobilePayAmount',
          align: 'right',
        },
        {
          title: '交易结果',
          dataIndex: 'MobileRecordState',
        },
      ]
    },
    {
      title: '渠道返回',
      dataIndex: '',
      children: [
        {
          title: '渠道返回',
          dataIndex: 'KwyRecordState',
        },
        {
          title: '交易金额',
          dataIndex: 'KwyAmount',
          align: 'right',
        },
      ]
    },
    {
      title: '订单信息',
      dataIndex: '',
      children: [
        {
          title: '订单编号',
          dataIndex: 'TradeNo',
          align: 'center',
        },
        {
          title: '支付方式',
          dataIndex: 'PaymentType',
          align: 'center',
        },
      ]
    }
  ]
  const getRightTime = (time: any) => {
    // const [start,end] = [moment(time[0]).format('YYYY/MM/DD'),moment(time[1]).format('YYYY/MM/DD')]
    if (moment().format('YYYY/MM') === moment(time[0]).format('YYYY/MM') || moment().format('YYYY/MM') === moment(time[1]).format('YYYY/MM')) {
      setStartTime(moment(time[0]).startOf("month").format('YYYY/MM/DD'))
      setEndTime(moment().subtract(1, "days").format('YYYY/MM/DD'))
      return [moment(time[0]).startOf("month").format('YYYY-MM-DD'), moment().subtract(1, "days").format('YYYY-MM-DD')]
    }
    setStartTime(moment(time[0]).startOf("month").format('YYYY/MM/DD'))
    setEndTime(moment(time[1]).endOf("month").format('YYYY/MM/DD'))
    return [moment(time[0]).startOf("month").format('YYYY-MM-DD'), moment(time[1]).endOf("month").format('YYYY-MM-DD')]
  }
  const [changeRevenueTopData, setChangeRevenueTopData] = useState<any>()

  //   导出excel方法
  const exportTable = (e) => {
    e.stopPropagation();                                            // 防止Collapse组件收起
    const main = document.getElementsByClassName('shareRoyaltyHideBox')[0]
    const thead = main.querySelector('thead').cloneNode(true);  // 深克隆DOM节点
    const tbody = main.querySelector('tbody').cloneNode(true);  // 深克隆DOM节点
    const container = document.querySelector('#hiddenBox');

    const tempTable = document.createElement('table');
    tempTable.appendChild(thead);
    tempTable.appendChild(tbody);

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

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

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

  // 修改差异的抽屉的点击确认修改的方法
  const handleGetChangeRevenue = async () => {
    let desc: string = ''
    if (allNewDesc && allNewDesc?.indexOf('】:') !== -1) {
      const desText: string = allNewDesc ? allNewDesc?.split('】:')[1] : ""
      desc = `${currentUser?.Name}【${moment().format('YYYY-MM-DD')}】:\n${desText}`
    } else {
      desc = `${currentUser?.Name}【${moment().format('YYYY-MM-DD')}】:\n${allNewDesc}`
    }
    console.log('desc', desc)
    const req = {
      ...changeRevenueTopData,
      BUSINESSPROJECTSPLIT_DESC: desc || '',
      SETTLEMENT_STATE: 1
    }
    console.log('req', req)
    const data = await SynchroBUSINESSPROJECTSPLIT(req)

    const list: any = []
    if (drawerShopDataList && drawerShopDataList.length > 0) {
      drawerShopDataList.forEach((item: any) => {
        item.RECORD_DATE = moment(item.RECORD_DATE).format('YYYY-MM-DD')
        list.push(item)
      })
    }
    console.log('list', list)
    const revenueReq = list
    const revenueData = await SynchroREVENUEDAILYSPLIT(revenueReq)

    console.log('revenueData', revenueData)
    if (data.Result_Code === 100) {
      message.success(data.Result_Desc)
    } else {
      message.error(data.Result_Desc)
    }

    if (revenueData.Result_Code === 100) {
      message.success(revenueData.Result_Desc)
      setCurrentRow(undefined);
      setChangeRevenueDrawer(false);
    } else {
      message.error(revenueData.Result_Desc)
    }
  }

  return (
    <div
      className={'bigBox'}
      style={{ height: 'calc(100vh - 132px)', overflowY: 'auto' }}
      ref={(el) => {
        // 打印报表
        if (!reqDetailList || reqDetailList.length === 0) return;
        setPrintOut(el);
      }}
      onScroll={(e) => {
        if (e.target.scrollTop > 100) {
          setShowFirstNotice(true)
        } else {
          setShowFirstNotice(false)
        }
      }}
    >
      {
        showLoading ?
          <div
            style={{
              width: '100%',
              height: '100%',
              background: 'rgba(0,0,0,0.1)',
              position: 'fixed',
              zIndex: 99,
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'center'
            }}
          >
            <div style={{
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'center',
              padding: '15px 20px 10px',
              background: '#fff',
              borderRadius: '8px',
              width: '200px'
            }}>
              <Spin />
              <span style={{ marginLeft: '5px' }}>重新生成中...</span>
            </div>
          </div> : ''
      }

      {/* 用来打印的 */}
      <div className={'shareRoyaltyHideBox'} style={{ position: 'fixed', zIndex: -1, top: 0, left: 0 }}>
        {
          showExportTable && exportTableData && exportTableData.length > 0 ?
            <ProTable
              columns={exportColumns}
              dataSource={exportTableData}
              pagination={false}
              expandable={{
                defaultExpandAllRows: true
              }}
            /> : ''
        }
      </div>
      <div id='hiddenBox' style={{ position: 'fixed', zIndex: -1, top: 0, left: 0 }} />
      {/* height: 'calc(100vh - 66px)', */}
      <div style={{ backgroundColor: '#fff', width: '100%', display: 'flex' }}>
        {
          isComponents ? '' :
            <LeftSelectTree setSelectedId={setSelectedId} setCollapsible={setCollapsible} collapsible={collapsible} />

          // <ProCard
          //   className="pageTable-leftnav"
          //   style={{ width: !collapsible ? "240px" : "60px" }}
          //   headStyle={{ width: !collapsible ? "240px" : "60px" }}
          //   bodyStyle={{ padding: 0, paddingTop: 20, paddingLeft: 20, width: !collapsible ? "240px" : "60px" }}
          //   extra={<MenuFoldOutlined onClick={() => {
          //     setCollapsible(!collapsible)
          //   }} />}
          //   colSpan={!collapsible ? "240px" : "60px"}
          //   title={!collapsible ? "可筛选门店" : ""}
          //   headerBordered
          //   collapsed={collapsible}
          // >
          //   {treeView && treeView.length > 0 ? <Tree
          //     checkable
          //     treeData={!treeLoading ? [{
          //       label: '全部',
          //       value: 0,
          //       key: '0-0',
          //       children: treeView
          //     }] : []}
          //     fieldNames={{
          //       title: "label",
          //       key: "key"
          //     }}
          //     blockNode
          //     defaultExpandedKeys={['0-0']}
          //     onCheck={(checkedKeys: React.Key[] | any, info) => {
          //       const selectedIds = info.checkedNodes.filter(n => n?.type === 1)
          //       setSelectedId(selectedIds.map(n => n?.value)?.toString() || '')
          //       // actionRef?.current?.reload()
          //     }}
          //   /> : ''}
          // </ProCard>
        }
        <div style={{
          paddingTop: isComponents ? '16px' : 0,
          paddingBottom: 0,
          paddingRight: 0,
          width: isComponents ? '100%' : `calc(100% - ${!collapsible ? 240 : 60}px)`,
          overflowX: 'auto'
        }}>
          {
            showNotice ?
              <div onClick={() => {
                setShowNotice(!showNotice)
              }} style={{
                position: 'fixed', background: '#fff', padding: '15px',
                borderRadius: '8px',
                width: '70vw',
                left: '440px',
                top: `${noticeY}px`,
                zIndex: 97,
                boxShadow: '0px 9px 28px 8px rgba(0,0,0,0.05), 0px 6px 16px 0px rgba(0,0,0,0.08), 0px 3px 6px -4px rgba(0,0,0,0.12)'
              }}>
                <Row>
                  <Col span={12}>
                    <Descriptions
                      title={<Text type="success" style={{ color: "#1890ff", fontSize: 14 }}>商家分润</Text>}
                      size="small" className="commity-sale-description" column={2}
                      contentStyle={{ fontWeight: "bolder" }} labelStyle={{ color: "#00000073" }}
                    >
                      <Descriptions.Item
                        label="到账金额">¥{numeral(reduceTableData?.SubRoyalty_Price).format('0,0.00')}</Descriptions.Item>
                      <Descriptions.Item
                        label="手续费">¥{numeral(reduceTableData?.Ticket_Fee).format('0,0.00')}</Descriptions.Item>
                    </Descriptions>
                  </Col>
                </Row>
                <Row>
                  <Col span={24}>
                    <Descriptions
                      title={<Text type="success" style={{ color: "#1890ff", fontSize: 14 }}>交易到账汇总</Text>}
                      size="small" column={4}
                      className="commity-sale-description"
                      contentStyle={{ fontWeight: "bolder" }} labelStyle={{ color: "#00000073" }}
                    >
                      <Descriptions.Item
                        label="交易金额">¥{numeral(reduceTableData?.Ticket_Price).format('0,0.00')}</Descriptions.Item>
                      <Descriptions.Item
                        label="到账金额">¥{numeral(reduceTableData?.Account_Price).format('0,0.00')}</Descriptions.Item>
                      {
                        activeKey === '1' ?
                          <Descriptions.Item
                            label="统计时间">{`${moment(tableStart).format('YYYY/MM/DD')}-${moment(tableEnd).format('YYYY/MM/DD')} `}
                            <Text type="secondary">( 共{numeral(tableDiffDays).format('0')}日 )</Text>
                          </Descriptions.Item> :
                          <Descriptions.Item label="统计时间">{`${startTime}-${endTime} `}</Descriptions.Item>
                      }
                    </Descriptions>
                  </Col>
                </Row>
              </div> : ''
          }
          {
            showNotice ?
              <div style={{
                width: '100vw',
                height: '100vh',
                position: 'fixed',
                top: '0px',
                left: '0px',
                zIndex: 100
              }} onClick={() => {
                setShowNotice(false)
              }}></div> : ''
          }
          {
            showFirstNotice ?
              <div style={{
                // width: `calc(100% - ${!collapsible ? 520 : 340}px)`,
                width: `calc(100% - ${collapsible ? 50 : 360}px)`,
                position: 'fixed',
                top: '100px',
                right: '24px',
                background: '#fff',
                zIndex: 98,
                padding: '8px 0'
              }}>
                <Row>
                  <Col span={24}>
                    <div style={{ paddingBottom: '12px' }}>
                      <span style={{ color: 'rgb(24, 144, 255)', fontSize: '14px', fontWeight: 600 }}>业主分润</span>
                      <div style={{
                        display: 'flex',
                        alignItems: 'center',
                        justifyContent: 'space-between',
                        boxSizing: 'border-box',
                        padding: '0 16px 0 0',
                        marginTop: '12px'
                      }}>
                        <div style={{ width: '240px', display: 'flex', alignItems: 'center' }}>
                          <span style={{
                            color: 'rgba(0, 0, 0, 0.45)',
                            fontSize: '14px',
                            fontWeight: 'normal',
                            whiteSpace: 'nowrap'
                          }}>到账金额：</span>
                          <div style={{ display: 'flex', alignItems: 'flex-end', height: '22px' }}>
                            <span style={{ fontWeight: 'normal', marginRight: '2px' }}>¥</span>
                            <span style={{
                              fontSize: '26px',
                              color: '#faad14',
                              fontWeight: 500,
                              lineHeight: '34px',
                              whiteSpace: 'nowrap'
                            }}>{numeral(reduceTableData.Royalty_Price).format('0,0.00')}</span>
                          </div>
                        </div>
                        <div style={{ width: '150px', display: 'flex', alignItems: 'center' }}>
                          <span style={{
                            color: 'rgba(0, 0, 0, 0.45)',
                            fontSize: '14px',
                            fontWeight: 'normal',
                            whiteSpace: 'nowrap'
                          }}>分润项目：</span>
                          <div style={{ display: 'flex', alignItems: 'flex-end', height: '22px' }}>
                            <span style={{ fontWeight: 'normal', marginRight: '2px' }}></span>
                            <span style={{
                              fontSize: '26px',
                              color: '#faad14',
                              fontWeight: 500,
                              lineHeight: '34px',
                              whiteSpace: 'nowrap'
                            }}>{numeral(allProjectSum).format('0,0')}</span>
                          </div>
                        </div>
                        <div style={{ width: '170px' }}>
                          <div style={{ display: 'flex', alignItems: 'center' }}>
                            <span style={{
                              color: 'rgba(0, 0, 0, 0.45)',
                              fontSize: '14px',
                              fontWeight: 'normal',
                              whiteSpace: 'nowrap'
                            }}>项目到账：</span>
                            <span style={{
                              color: 'rgba(0, 0, 0, 0.85',
                              fontWeight: 'bold',
                              whiteSpace: 'nowrap'
                            }}>{numeral(reduceTableData.RoyaltyProject_Price).format('0,0.00')}</span>
                          </div>
                        </div>
                        <div style={{ width: '150px' }}>
                          <div style={{ display: 'flex', alignItems: 'center' }}>
                            <span style={{
                              color: 'rgba(0, 0, 0, 0.45)',
                              fontSize: '14px',
                              fontWeight: 'normal',
                              whiteSpace: 'nowrap'
                            }}>差额：</span>
                            <span style={{
                              color: 'rgba(0, 0, 0, 0.85',
                              fontWeight: 'bold',
                              whiteSpace: 'nowrap'
                            }}>{numeral(reduceTableData.Royalty_DiffPrice).format('0,0.00')}</span>
                          </div>
                        </div>
                        <div style={{ width: '440px', display: 'flex', alignItems: 'center' }}>
                          <span style={{
                            color: 'rgba(0, 0, 0, 0.45)',
                            fontSize: '14px',
                            fontWeight: 'normal',
                            whiteSpace: 'nowrap'
                          }}>统计时间：</span>
                          {
                            isComponents ? '' :
                              <RangePicker
                                value={statisticsTime}
                                onChange={(e: any) => {
                                  console.log('e', e);

                                  if (e) {
                                    setStatisticsTime([moment(e[0]._d), moment(e[1]._d)])
                                    formRef.current?.setFieldsValue({ search_date: [moment(e[0]._d), moment(e[1]._d)] })
                                  } else {
                                    setStatisticsTime(undefined)
                                  }
                                }}
                                disabledDate={(current: any) => current && current > moment()}
                              />
                          }
                          <Button type={'primary'} style={{ marginLeft: '8px' }} onClick={() => {
                            actionRef.current?.reload()
                          }}>查询</Button>
                        </div>
                      </div>
                    </div>
                  </Col>
                </Row>
              </div> : ''
          }
          <ProTable<MobilePayRoyaltyModel>
            rowKey={(record) => {
              return `${record?.SPRegionType_ID}-${record?.Serverpart_ID}-${record?.ServerpartShop_Name}-${record?.ServerpartShop_ID}-${record?.Statistics_Date}`
            }}
            formRef={formRef}
            actionRef={actionRef}
            search={isComponents ? false : { span: 6 }}
            loading={mainTableLoading}
            request={async (params) => {
              setMainTableLoading(true)
              // 统计时间
              setExportTableData([])
              const formRes: any = formRef.current?.getFieldsValue()
              console.log('formRes', formRes);

              let [searchStartTime, searchEndTime]: any = activeKey === '1' ? formRes?.search_date : formRes?.search_months
              console.log('searchStartTime', searchStartTime);
              console.log('searchEndTime', searchEndTime);



              if (searchStartTime === searchEndTime) {
                setStatisticsSame(true)
              } else {
                setStatisticsSame(false)
              }
              console.log('activeKey', activeKey);
              console.log('params', params);

              if (params && searchStartTime && searchEndTime) {
                setBigSearchTime([searchStartTime, searchEndTime])
                // setStatisticsTime([moment(params.StartDate),moment(params.EndDate)])
                setRealSearchTime([moment(searchStartTime).format('YYYY-MM-DD'), moment(searchEndTime).format('YYYY-MM-DD')])
              } else {
                setBigSearchTime(undefined)
                // setStatisticsTime(undefined)
              }
              const time: any = [searchStartTime, searchEndTime]
              if (time && time.length > 0) {
                setStatisticsTime([moment(time[0]), moment(time[1])])
                if (activeKey === '1') {
                  searchStartTime = moment(time[0]).format('YYYY-MM-DD')
                  searchEndTime = moment(time[1]).format('YYYY-MM-DD')
                } else {
                  // searchStartTime = moment(time[0]).format('YYYY-MM')
                  // searchEndTime = moment(time[1]).format('YYYY-MM')
                  searchStartTime = moment(time[0]).startOf('M').format('YYYY-MM-DD')
                  searchEndTime = moment(time[1]).endOf('M').format('YYYY-MM-DD')
                }
              }
              console.log('compareCurrent', compareCurrent);
              console.log('isComponents', isComponents);
              console.log('searchEndTime', searchEndTime);
              console.log('searchStartTime', searchStartTime);
              const req: any = {
                DataType: 1,
                StartDate: isComponents ? compareCurrent?.searchStart : searchStartTime,
                EndDate: isComponents ? compareCurrent?.searchEnd : searchEndTime,
                ServerpartIds: isComponents ? compareCurrent?.SERVERPART_ID : (selectedId || '0'),
                ServerpartShopIds: isComponents ? compareCurrent?.SERVERPARTSHOP_ID : '',
                GroupByDaily: !!isComponents
              }
              setSearchParams(req)
              const data = await getMobilePayRoyaltyReport(req);
              console.log('data', data);

              // 给最里层的门店加一个标识
              data.data.forEach((item: any) => {
                if (item.children && item.children.length > 0) {
                  item.children.forEach((subItem: any) => {
                    if (subItem.children && item.children.length > 0) {
                      subItem.children.forEach((thirdItem: any) => {
                        thirdItem.newServerpart_Name = subItem.Serverpart_Name
                        thirdItem.type = 'shop'
                        let shopId: string = ''
                        if (thirdItem.children && thirdItem.children.length > 0) {
                          thirdItem.children.forEach((fourthItem: any) => {
                            if (shopId) {
                              shopId += `,${fourthItem.ServerpartShop_ID}`
                            } else {
                              shopId = fourthItem.ServerpartShop_ID
                            }
                          })
                        }
                        thirdItem.newServerpartShop_ID = shopId
                      })
                    }
                  })
                }
              })

              let projectSum: number = 0
              if (data && data.data && data.data.length > 0) {
                data.data.forEach((item: any) => {
                  projectSum += item.Project_Count
                })
              }

              setAllProjectSum(projectSum)
              setReqDetailList(data.data);
              setPrintOut(undefined);


              getRightTime(isComponents ? [compareCurrent?.searchStart, compareCurrent?.searchEnd] : [params.StartDate, params.EndDate])
              if (selectedId || isComponents) {
                const req = {
                  ProvinceCode: currentUser?.ProvinceCode,
                  ServerpartIds: isComponents ? compareCurrent?.SERVERPART_ID : selectedId
                }
                const result = await getNoShopList(req)
                if (result && result.List.length > 0) {
                  setNoShopList(result.List)
                }
              } else {
                setNoShopList([])
              }
              const res = JSON.parse(JSON.stringify(data.data))
              console.log('1', res);
              if (res && res.length > 0) {
                const reduceData = res.reduce((p: {
                  Ticket_Price: number, Account_Price: number, SubRoyalty_Price: number, Ticket_Fee: number,
                  Royalty_Price: number, RoyaltyProject_Price: number, Royalty_DiffPrice: number
                }, currentValue: MobilePayRoyaltyModel) => {
                  const previousValue = { ...p }
                  previousValue.Ticket_Price = numeral(numeral(previousValue.Ticket_Price + currentValue.Ticket_Price).format('0.00')).value() || 0;
                  previousValue.Account_Price = numeral(numeral(previousValue.Account_Price +
                    currentValue.Account_Price).format('0.00')).value() || 0;
                  previousValue.SubRoyalty_Price = numeral(numeral(previousValue.SubRoyalty_Price +
                    currentValue.SubRoyalty_Price).format('0.00')).value() || 0;
                  previousValue.Ticket_Fee = numeral(numeral(previousValue.Ticket_Fee +
                    currentValue.Ticket_Fee).format('0.00')).value() || 0;
                  previousValue.Royalty_Price = numeral(numeral(previousValue.Royalty_Price +
                    currentValue.Royalty_Price).format('0.00')).value() || 0;
                  previousValue.RoyaltyProject_Price = numeral(numeral(previousValue.RoyaltyProject_Price +
                    currentValue.RoyaltyProject_Price).format('0.00')).value() || 0;
                  previousValue.Royalty_DiffPrice = numeral(numeral(previousValue.Royalty_DiffPrice +
                    currentValue.Royalty_DiffPrice).format('0.00')).value() || 0;
                  return previousValue
                }, {
                  Ticket_Price: 0, Account_Price: 0, SubRoyalty_Price: 0,
                  Ticket_Fee: 0, Royalty_Price: 0, RoyaltyProject_Price: 0, Royalty_DiffPrice: 0
                });
                setReduceTableData(reduceData)
                if (formRef?.current?.getFieldValue('search_date') && activeKey !== "2") {
                  const [start, end] = formRef.current?.getFieldValue('search_date')
                  setTableStart(start)
                  setTableEnd(end)
                  const diffDays = moment.duration(moment(end).diff(moment(start))).asDays() + 1
                  setTableDiffDays(diffDays)
                } else {
                  setTableStart(undefined)
                  setTableEnd(undefined)
                  setTableDiffDays(undefined)
                }
              }
              console.log('232131321', data)
              if (data.data && data.data.length > 0) {
                const exportList: any = []
                const exportData: any = JSON.parse(JSON.stringify(data.data))
                exportData.forEach((item: any) => {
                  if (item.children && item.children.length > 0) {
                    item.children.forEach((subItem: any) => {
                      if (subItem.children && subItem.children.length > 0) {
                        subItem.children.forEach((thirdItem: any) => {
                          thirdItem.children = []
                          thirdItem.SPRegionType_Name = item.SPRegionType_Name ? item.SPRegionType_Name.split('管理中心')[0] : ""
                          thirdItem.Serverpart_Name = subItem.Serverpart_Name ? subItem.Serverpart_Name.split('服务区')[0] : ""
                          exportList.push(thirdItem)
                        })
                      }
                    })
                  }
                })
                console.log('exportList', exportList);

                setExportTableData(exportList)
              }
              setMainTableLoading(false)
              return data;
            }}
            rowClassName={(record) => expandRow?.includes(record?.ServerpartShop_Code) && !record?.Serverpart_ID ? 'expanded' : ''}
            expandable={
              {
                rowExpandable: () => true,
                defaultExpandedRowKeys: ['0-000'],
                indentSize: 0,
                // expandRowByClick: true,
                defaultExpandAllRows: true,
                onExpand: (expanded, record) => {
                  if (expanded) {
                    setExpandRow([...expandRow, record.ServerpartShop_Code])
                  } else {
                    const nowData = expandRow?.reduce((p: string[], c) => {
                      if (c !== record?.ServerpartShop_Code) {
                        p.push(c)
                      }
                      return p
                    }, [])
                    setExpandRow(nowData || [])
                  }
                }
              }
            }
            style={{ backgroundColor: "#ffffff", width: '100%' }}
            tableExtraRender={
              (_, data) => {
                if (data) {
                  const reduceData = data.reduce((p: {
                    Ticket_Price: number, Account_Price: number, SubRoyalty_Price: number, Ticket_Fee: number,
                    Royalty_Price: number, RoyaltyProject_Price: number, Royalty_DiffPrice: number
                  }, currentValue: MobilePayRoyaltyModel) => {
                    const previousValue = { ...p }
                    previousValue.Ticket_Price = numeral(numeral(previousValue.Ticket_Price + currentValue.Ticket_Price).format('0.00')).value() || 0;
                    previousValue.Account_Price = numeral(numeral(previousValue.Account_Price +
                      currentValue.Account_Price).format('0.00')).value() || 0;
                    previousValue.SubRoyalty_Price = numeral(numeral(previousValue.SubRoyalty_Price +
                      currentValue.SubRoyalty_Price).format('0.00')).value() || 0;
                    previousValue.Ticket_Fee = numeral(numeral(previousValue.Ticket_Fee +
                      currentValue.Ticket_Fee).format('0.00')).value() || 0;
                    previousValue.Royalty_Price = numeral(numeral(previousValue.Royalty_Price +
                      currentValue.Royalty_Price).format('0.00')).value() || 0;
                    previousValue.RoyaltyProject_Price = numeral(numeral(previousValue.RoyaltyProject_Price +
                      currentValue.RoyaltyProject_Price).format('0.00')).value() || 0;
                    previousValue.Royalty_DiffPrice = numeral(numeral(previousValue.Royalty_DiffPrice +
                      currentValue.Royalty_DiffPrice).format('0.00')).value() || 0;
                    return previousValue
                  }, {
                    Ticket_Price: 0, Account_Price: 0, SubRoyalty_Price: 0,
                    Ticket_Fee: 0, Royalty_Price: 0, RoyaltyProject_Price: 0, Royalty_DiffPrice: 0
                  });
                  // setReduceTableData(reduceData)

                  // const [start, end] =
                  //   activeKey === "2" ?
                  //     ''
                  //     : formRef.current?.getFieldValue('search_date')

                  // setTableStart(start)
                  // setTableEnd(end)

                  //   const diffDays = moment.duration(moment(end).diff(moment(start))).asDays() + 1
                  // setTableDiffDays(diffDays)
                  return <div style={{ paddingLeft: 24 }} className={'YDRevenue'}>
                    <Row>
                      <Col span={24}>
                        <Descriptions
                          title={<Text type="success" style={{ color: "#1890ff", fontSize: 14 }}>业主分润</Text>}
                          size="small" className="commity-sale-description" column={4}
                          contentStyle={{ fontWeight: "bolder" }} labelStyle={{ color: "#00000073" }}
                          style={{ marginBottom: 16 }}
                        >
                          <Descriptions.Item label="">
                            <div style={{ display: 'flex', alignItems: 'center' }}>
                              <span style={{
                                color: 'rgba(0, 0, 0, 0.45)',
                                fontSize: '14px',
                                fontWeight: 'normal'
                              }}>到账金额：</span>
                              <div style={{ display: 'flex', alignItems: 'flex-end', height: '30px' }}>
                                <span style={{ fontWeight: 'normal', marginRight: '2px' }}>¥</span>
                                <span style={{
                                  fontSize: '28px',
                                  color: '#faad14',
                                  fontWeight: 500,
                                  lineHeight: '34px'
                                }}>{numeral(reduceData.Royalty_Price).format('0,0.00')}</span>
                              </div>
                            </div>
                          </Descriptions.Item>
                          <Descriptions.Item label="">
                            <div style={{ display: 'flex', alignItems: 'center' }}>
                              <span style={{
                                color: 'rgba(0, 0, 0, 0.45)',
                                fontSize: '14px',
                                fontWeight: 'normal'
                              }}>分润项目：</span>
                              <div style={{ display: 'flex', alignItems: 'flex-end', height: '30px' }}>
                                <span style={{ fontWeight: 'normal', marginRight: '2px' }}></span>
                                <span style={{
                                  fontSize: '28px',
                                  color: '#faad14',
                                  fontWeight: 500,
                                  lineHeight: '34px'
                                }}>{numeral(allProjectSum).format('0,0')}</span>
                              </div>
                            </div>
                          </Descriptions.Item>
                          <Descriptions.Item
                            label="项目到账">{numeral(reduceData.RoyaltyProject_Price).format('0,0.00')}</Descriptions.Item>
                          <Descriptions.Item
                            label="差额">{numeral(reduceData.Royalty_DiffPrice).format('0,0.00')}</Descriptions.Item>
                        </Descriptions>
                      </Col>
                    </Row>
                    {/* <Descriptions */}
                    {/*   title={<Text type="success" style={{ color: "#1890ff", fontSize: 14 }}>分润项目合计</Text>} */}
                    {/*   size="small" column={4} */}
                    {/*   className="commity-sale-description" */}
                    {/*   contentStyle={{ fontWeight: "bolder" }} labelStyle={{ color: "#00000073" }} */}
                    {/* > */}
                    {/*    */}
                    {/*   /!* <Descriptions.Item label="银行到账">¥{numeral(reduceData.Royalty_Price).format('0,0.00')}</Descriptions.Item> *!/ */}
                    {/*   /!* <Descriptions.Item label="项目到账">¥{numeral(reduceData.RoyaltyProject_Price).format('0,0.00')}</Descriptions.Item> *!/ */}
                    {/*   /!* <Descriptions.Item label="分润差额">¥{numeral(reduceData.Royalty_DiffPrice).format('0,0.00')}</Descriptions.Item> *!/ */}
                    {/* </Descriptions> */}
                    {/* <Descriptions */}
                    {/*     size="small" className="commity-sale-description" column={5} */}
                    {/*     contentStyle={{ fontWeight: "bolder" }} labelStyle={{ color: "#00000073" }}> */}
                    {/*   { */}
                    {/*     activeKey==='1'? */}
                    {/*     <Descriptions.Item label="统计时间">{`${moment(start).format('YYYY/MM/DD')}-${moment(end).format('YYYY/MM/DD')} `} */}
                    {/*       <Text type="secondary">( 共{numeral(diffDays).format('0')}日 )</Text> */}
                    {/*     </Descriptions.Item>: */}
                    {/*     <Descriptions.Item label="统计时间">{`${startTime}-${endTime} `}</Descriptions.Item> */}
                    {/*   } */}
                    {/* </Descriptions> */}

                    {/* { */}
                    {/*   noShopList && noShopList.length>0? */}
                    {/*     <WarningTwoTone style={{cursor:'pointer'}} onClick={async ()=>{ */}
                    {/*       setShowWarningDrawer(true) */}
                    {/*     }}/>:'' */}
                    {/* } */}
                  </div>
                }
                return <></>
              }
            }
            bordered
            columns={columns}
            headerTitle={<PageTitleBox props={props} />}
            toolbar={{
              actions: isComponents ? [] : [
                <div>
                  <span style={{ visibility: 'hidden' }}>
                    <ReactHTMLTableToExcel
                      buttonText={'导出excel'}
                      ref={downloadBtnRef}
                      table="table-to-xls-shareRoyalty"
                      filename={`移动支付分账报表_${moment().format('YYYY_MM_DD')}`}
                      sheet="sheet1"
                    />
                  </span>
                  <img style={{ cursor: 'pointer', width: '20px', height: '20px' }} onClick={(e) => {
                    setShowNotice(!showNotice)
                    setNoticeY(e.clientY)
                    setNoticeX(e.clientX)
                  }} src={'https://eshangtech.com/ShopICO/ahyd-BID/newIndex3/noticeIcon.svg'} />
                  <Typography.Text type="secondary">单位：元</Typography.Text>
                  <ReactToPrint
                    trigger={() => (
                      <Button style={{ margin: '0 8px' }} key="printout" type="default">
                        打印
                      </Button>
                    )}
                    content={() => {
                      if (printOut) {
                        const content: HTMLElement | Node | undefined = printOut?.getElementsByClassName('ant-card-body')[0]
                        const extra: HTMLElement | Node | undefined = printOut?.getElementsByClassName('ant-pro-table-extra')[0]
                        const innerText = `统计时间：${moment().format('YYYY/MM/DD')}`;

                        const ele = printOutBody([extra ? extra.cloneNode(true) : '', content ? content.cloneNode(true) : ''], innerText);

                        return ele
                      }
                      return ''
                    }}
                  />
                  <Button
                    key="new"
                    type="primary"
                    onClick={async (e) => {
                      if (exportTableData && exportTableData.length > 0) {
                        setShowExportTable(true)
                        setTimeout(() => {
                          exportTable(e)
                        }, 100)
                      } else {
                        message.error('暂无数据可导出！')
                      }
                    }}
                  //   const nowColumns = columns.filter(n => !n.hideInTable)
                  //   const fat = nowColumns.map((n: any, index: number) => {
                  //     if (n?.children) {
                  //       return n?.children.map((m: { title: any; }) => {
                  //         const title = index === 0 ? m.title : n.title + m.title
                  //         return {...m, title}
                  //       })
                  //     }
                  //     return n
                  //   })
                  //   const list: any = JSON.parse(JSON.stringify(reqDetailList))
                  //   const printList: any = []
                  //   list.forEach((item: any) => {
                  //     item.shopName = item.SPRegionType_Name
                  //     if (item.children && item.children.length > 0) {
                  //       item.children.forEach((subItem: any) => {
                  //         subItem.shopName = subItem.Serverpart_Name
                  //         if (subItem.children && subItem.children.length > 0) {
                  //           subItem.children.forEach((thirdItem: any) => {
                  //             thirdItem.shopName = thirdItem.ServerpartShop_Name
                  //             thirdItem.children = []
                  //           })
                  //         }
                  //       })
                  //     }
                  //   })
                  //   const success = await exportExcelReceivedSum(
                  //     fat.flat(),
                  //     list || [],
                  //     `移动支付分账报表_${moment().format('YYYY/MM/DD')}`,
                  //   );
                  //   if (success.message !== 'ok') {
                  //     message.info({content: success.message});
                  //   }
                  // }}
                  >
                    导出excel
                  </Button>
                  <Popconfirm
                    title="确认固化数据？"
                    onConfirm={async () => {
                      setMainTableLoading(true)
                      const req: any = {
                        StartDATE: searchParams?.StartDate,
                        EndDATE: searchParams?.EndDate,
                        SERVERPART_IDS: searchParams?.ServerpartIds,
                        STAFF_NAME: currentUser?.Name,
                        STAFF_ID: currentUser?.ID,
                        OPRATE_DATE: moment().format('YYYY-MM-DD HH:mm:ss')
                      }
                      const data = await handleSynchroBANKACCOUNTVERIFY(req)
                      setMainTableLoading(false)
                      if (data.Result_Code === 100) {
                        message.success(data.Result_Desc)
                        actionRef.current?.reload()
                      } else {
                        message.error(data.Result_Desc)
                      }
                    }}
                  >
                    <Button style={{ marginLeft: '8px' }} type="primary">固化数据</Button>
                  </Popconfirm>

                </div>,

              ],
            }}
            scroll={isComponents ? { y: 'calc(100vh - 300px)' } : { x: "100%" }}
            pagination={false}
          />
        </div>
      </div>

      {/* 项目数据编辑弹出框 */}
      <ProjectEditor parentTableRef={actionRef} currentRecord={currentRow} modalVisible={showNewAdd}
        handleModalVisible={setShowNewAdd} currentServerpartId={currentServerpartId}
        currentSPRegionTypeID={currentSPRegionTypeID} />

      <Drawer
        width="80%"
        className="project-drawer"
        visible={showNewDetail} // 抽屉弹框是否显示状态
        onClose={() => { // 关闭抽屉 则在清空选中行数据 并 设置抽屉状态为关闭
          setCurrentRow(undefined);
          setShowNewDetail(false);
        }}
        bodyStyle={{ backgroundColor: "#f9f9f9", padding: 0 }}
        closable={false}
      >
        {/* 抽屉打开时 加载项目详情组件 */}
        {showNewDetail &&
          <ProjectDetail tabActive={'5'} id={currentRow?.BUSINESSPROJECT_ID} businessType={currentRow?.BUSINESS_TYPE}
            showType={'edit'}></ProjectDetail>}
      </Drawer>


      <Drawer
        width="80%"
        className="project-drawer"
        visible={showDetail} // 抽屉弹框是否显示状态
        onClose={() => { // 关闭抽屉 则在清空选中行数据 并 设置抽屉状态为关闭
          setShowDetail(false);
        }}
        bodyStyle={{ backgroundColor: "#f9f9f9", padding: 0 }}
        closable={false}
      >
        {showDetail && <ProTable<MobilePayRoyaltyRecordModel>
          rowKey="Pay_Date"
          headerTitle=""
          actionRef={actionRef}
          search={{ span: 6 }}
          bordered={true}
          request={async (params, sorter) => {
            // 排序字段
            const sortstr = Object.keys(sorter).map(n => {
              const value = sorter[n]
              return value ? `${n} ${value.replace('end', '')}` : ''
            })
            const data = await getList({
              ...params, ServerpartShop_ID: currentRow?.ServerpartShop_ID,
              Serverpart_IDS: currentRow?.Serverpart_ID, ServerpartShop_IDS: currentRow?.ServerpartShop_ID,
              Pay_Date: currentRow?.Statistics_Date, Record_State: '1,2',
              SortStr: sortstr.length ? sortstr.toString() : '',
            });
            return data;
          }}
          columns={columnsRecord}
          pagination={{ defaultPageSize: 10 }}
          options={false}
        />}
      </Drawer>
      {/*   显示异常的抽屉 */}
      <Drawer
        width={'25%'}
        visible={showWarningDrawer}
        onClose={() => {
          setShowWarningDrawer(false);
        }}
      >
        {
          noShopList && noShopList.length > 0 ?
            <>
              {
                noShopList.map((item: any) => {
                  return <div>
                    <span style={{ minWidth: '80px', marginRight: '10px' }}>{item.ico}</span>
                    <span style={{ minWidth: '80px', marginRight: '10px' }}>{item.key}</span>
                    <span style={{ minWidth: '80px' }}>{item.label}</span>
                  </div>
                })
              }
            </> : ''
        }
      </Drawer>
      {/* 显示流水 */}
      <Drawer
        width={'80%'}
        visible={flowDrawer}
        onClose={() => {
          setFlowDrawer(false);
          setCurrentRow(undefined)
        }}
        destroyOnClose
      >
        <ProTable
          rowKey="SELLMASTER_CODE"
          headerTitle={<Text type="success" style={{ color: "#1890ff", fontSize: 14 }} strong>销售流水明细</Text>}
          formRef={formRef2}
          actionRef={actionRef}
          search={{ span: 6 }}
          request={async (params) => {
            let shopId: string = ''
            if (currentRow?.type === 'shop') {
              shopId = currentRow?.ServerpartShop_ID
            } else if (currentRow?.children && currentRow?.children.length > 0) {
              currentRow?.children.forEach((item: any) => {
                if (shopId) {
                  shopId += `,${item.ServerpartShop_ID}`
                } else {
                  shopId = item.ServerpartShop_ID
                }
              })
            }
            const data = await getYSSellMasterList({
              ...params,
              SERVERPARTSHOP_ID: shopId || null,
              // SELLMASTER_DATE :params.StartDate,
              // SELLMASTER_DATE_Start:params.StartDate,
              // SELLMASTER_DATE_End:params.EndDate
            });
            setFlowDetailList(data.data);
            return data;
          }}
          bordered
          columns={flowColumns}
          tableExtraRender={
            (_, data) => {

              if (data) {
                const reduceData = data.reduce((
                  p: {
                    SELLMASTER_OFFPRICE: number,
                    SELLMASTER_COUNT: number,
                    SELLMASTER_AMOUNT: number,
                    MACHINECODE: string[],
                    payway: {},
                    mobilePay: {}
                  },
                  currentValue: any) => {
                  const previousValue = { ...p }
                  previousValue.SELLMASTER_COUNT += currentValue.SELLMASTER_COUNT || 0; // 销售数量
                  previousValue.SELLMASTER_OFFPRICE += currentValue.SELLMASTER_OFFPRICE || 0; // 优惠金额
                  previousValue.SELLMASTER_AMOUNT += currentValue.SELLMASTER_AMOUNT || 0; // 实收金额

                  if (currentValue.PAYMENT_TYPE === 1010 || currentValue.PAYMENT_TYPE === 1020) {
                    previousValue.payway['移动'] += currentValue.SELLMASTER_AMOUNT
                    if (!previousValue.mobilePay[currentValue.PAYMENT_TYPE_TEXT]) { // 移动支付方式
                      previousValue.mobilePay[currentValue.PAYMENT_TYPE_TEXT] = 0
                    }
                    previousValue.mobilePay[currentValue.PAYMENT_TYPE_TEXT] += currentValue.SELLMASTER_AMOUNT
                  } else {
                    if (!previousValue.payway[currentValue.PAYMENT_TYPE_TEXT]) { // 支付方式
                      previousValue.payway[currentValue.PAYMENT_TYPE_TEXT] = 0
                    }
                    previousValue.payway[currentValue.PAYMENT_TYPE_TEXT] += currentValue.SELLMASTER_AMOUNT
                  }
                  if (!previousValue.MACHINECODE.includes(currentValue.MACHINECODE)) {

                    previousValue.MACHINECODE.push(currentValue.MACHINECODE); // 收银机号
                  }
                  return previousValue
                }, {
                  SELLMASTER_OFFPRICE: 0,
                  SELLMASTER_COUNT: 0,
                  SELLMASTER_AMOUNT: 0,
                  MACHINECODE: [],
                  payway: { '移动': 0, '现金': 0, },
                  mobilePay: {}
                });

                return <div style={{ paddingLeft: 24 }}>
                  <Descriptions
                    title={<Text type="success" style={{ color: "#1890ff", fontSize: 14 }}>销售流水汇总</Text>}
                    size="small" column={5}
                    className="commity-sale-description"
                    contentStyle={{ fontWeight: "bolder" }} labelStyle={{ color: "#00000073" }}
                  >
                    <Descriptions.Item className='mobileMoney' label="移动支付">
                      ¥<span className='mobileMoneyText'>{numeral(reduceData.payway['移动']).format('0,0.00')}</span>
                    </Descriptions.Item>
                    <Descriptions.Item
                      label="现金支付">¥{numeral(reduceData.payway['现金']).format('0,0.00')}</Descriptions.Item>
                    <Descriptions.Item
                      label="实收金额">¥{numeral(reduceData.SELLMASTER_AMOUNT).format('0,0.00')}</Descriptions.Item>
                  </Descriptions>
                  <Descriptions size="small" className="commity-sale-description" column={5}
                    contentStyle={{ fontWeight: "bolder" }} labelStyle={{ color: "#00000073" }}>
                    <Descriptions.Item label="客单数量">{numeral(data.length).format('0,0')}<Text
                      type="secondary"> 笔</Text></Descriptions.Item>
                    <Descriptions.Item
                      label="优惠金额">¥{numeral(reduceData.SELLMASTER_OFFPRICE).format('0,0.00')}</Descriptions.Item>
                    <Descriptions.Item label="收银机">{numeral(reduceData.MACHINECODE.length).format('0,0')}<Text
                      type="secondary"> 台</Text></Descriptions.Item>
                  </Descriptions>
                  <Descriptions size="small" className="commity-sale-description" column={5}
                    contentStyle={{ fontWeight: "bolder" }} labelStyle={{ color: "#00000073" }}>
                    <Descriptions.Item label="销售数量">{numeral(reduceData.SELLMASTER_COUNT).format('0,0')}<Text
                      type="secondary"> 件</Text></Descriptions.Item>
                    <Descriptions.Item
                      label="客单均价">¥{numeral(reduceData.SELLMASTER_AMOUNT / data.length).format('0,0.00')}</Descriptions.Item>
                    <Descriptions.Item
                      label="商品均价">¥{numeral(reduceData.SELLMASTER_AMOUNT / reduceData.SELLMASTER_COUNT).format('0,0.00')}</Descriptions.Item>
                  </Descriptions>
                </div>

              }
              return <></>
            }
          }
          onRow={(record) => {
            return {

              onClick: () => {
                setCurrentRow(record)
                setVisible(true)
              }
            }
          }}
          pagination={{ defaultPageSize: 10 }}
        />
      </Drawer>

      {/* 流水悬浮框 */}
      <Modal
        title={currentRow ? `${currentRow?.SERVERPART_NAME + currentRow?.SHOPNAME}销售流水明细` : '销售流水明细'}
        centered
        visible={visible}
        onOk={() => setVisible(false)}
        onCancel={() => setVisible(false)}
        width={1024}
        bodyStyle={{ padding: 0 }}

      >
        {currentRow && <FlowDetail id={currentRow?.SELLMASTER_CODE} />}
      </Modal>

      {/* 差额的抽屉 */}
      <Drawer
        width={'80%'}
        visible={differenceDrawer}
        onClose={() => {
          setDifferenceDrawer(false);
          setCurrentRow(undefined)
        }}
        destroyOnClose
      >
        <DifferenceAmount onShow={differenceDrawer} parentRow={currentRow} searchParams={searchParams} />
      </Drawer>
      {/* 有计算公式的流水 */}
      <Drawer
        width={1000}
        visible={haveFlowDrawer}
        className={'drawerBox'}
        onClose={() => {
          setCurrentRow(undefined);
          setHaveFlowDrawer(false);
        }}
        destroyOnClose
        closable={false}
      >
        <FlowDrawer drawerLoading={drawerLoading} currentRow={currentRow} setDrawerLoading={setDrawerLoading}
          isFirstFloorClick={isFirstFloorClick}
        />
      </Drawer>
      <Drawer
        width={1000}
        visible={changeRevenueDrawer}
        onClose={() => {
          setCurrentRow(undefined);
          setChangeRevenueDrawer(false);
        }}
        destroyOnClose
        closable={false}
        bodyStyle={{ backgroundColor: "#fff", padding: 16 }}
        footer={<div style={{ width: '100%', display: 'flex', justifyContent: 'flex-end' }}>
          <Button type={'primary'} onClick={() => {
            console.log('drawerShopDataList', drawerShopDataList)
            handleGetChangeRevenue()
          }}>确认修改</Button>
        </div>}
      >
        <ChangeRevenue ref={ChangeRevenueRef} currentRow={currentRow} time={statisticsTime} show={changeRevenueDrawer}
          setDrawerShopDataList={setDrawerShopDataList} setChangeRevenueTopData={setChangeRevenueTopData} setAllNewDesc={setAllNewDesc} />
      </Drawer>
    </div>
  );
};

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