// 营收汇总报表

import moment from 'moment';
import numeral from 'numeral';
import { connect, history } from 'umi';
import React, { useEffect, useRef, useState } from 'react';
import ReactToPrint from 'react-to-print';
import ProTable from '@ant-design/pro-table';
import useRequest from '@ahooksjs/use-request';
import ProCard from '@ant-design/pro-card';
import { ControlTwoTone, InteractionTwoTone, MenuFoldOutlined } from '@ant-design/icons';
import { PageContainer } from '@ant-design/pro-layout';
import { Button, Drawer, message, Radio, Select, Space, Tooltip, Tree, Typography } from 'antd';
import ReactHTMLTableToExcel from "react-html-table-to-excel";
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 { RevenueStatisticsModel, RevenueStatisticsParams } from './data';
import type { CurrentUser } from '@/models/user';

import { getFieldEnum, getServerpartTree, handleCallLogs } from '@/services/options';
import { getRevenueReport } from './service';
import { exportExcel, printOutBody } from '@/utils/utils';
import '@/pages/style.less';
import { synchroBehaviorRecord } from "@/services/user";
import session from "@/utils/session";
import { handleGetServerpartShopTrade } from '../../productControl/commodityInfo/service';
import {
  handleGetShopShortNames,
  handleGetShopShortNamesGet
} from "@/pages/reports/BusinessAnalysis/transactionAnalysis/service";
import { handleGetRevenueReportByDate } from "@/pages/reports/Finance/revenueAnalysis/service";
import rectification from '@/assets/rectification.png'
import codeIcon from '@/assets/DataVerification/code.png'
import interfaceIcon from '@/assets/DataVerification/interface.png'
import PageTitleBox from '@/components/PageTitleBox';
import { formatTreeData, sortTreeData } from '@/utils/format';
import { exportXlsxFromProColumnsExcelJS } from '@/utils/exportExcelFun';

const { Text } = Typography;

/**
 * @description: 门店营收汇总页面
 * @param {currentUser} 当前登录用户信息
 * @return { React.FC } 页面主体
 */
const RevenueSummaryTable: React.FC<{ currentUser?: CurrentUser }> = (props) => {
  const { currentUser } = props
  const actionRef = useRef<ActionType>();
  const formRef = useRef<ProFormInstance>();
  const { location } = history
  const [activeKey, setActiveKey] = useState<'1' | '2'>('1'); // 统计类型 1 日报表 2 月报表
  const [reqDetailList, setReqDetailList] = useState<RevenueStatisticsModel[]>(); // 导出excel表格
  const [printOut, setPrintOut] = useState<any>(); // 打印数据的内容
  const downloadBtnRef = useRef<any>()
  const [expandRow, setExpandRow] = useState<number[]>([]); // 选择打开的服务区
  const [collapsible, setCollapsible] = useState<boolean>(false)
  const [searchTime, setSearchTime] = useState<any>([moment().format('YYYY-MM-DD'), moment().format('YYYY-MM-DD')])
  // 搜索条件的时间
  const [searchParamsTime, setSearchParamsTime] = useState<any>()
  const [DataSourceType, setDataSourceType] = useState<'1' | '2'>('1'); // 统计类型 1 日结营收 2 自然日营收
  // const defaultShops = currentUser?.ServerpartShopIds ? currentUser?.ServerpartShopIds.split(',').map(Number) : []
  // const [shopId, setShopId] = useState<number[]>([]); // 选择的门店 根据选择的门店筛选数据结果
  const [selectedId, setSelectedId] = useState<string>()
  const [selectedArea, setSelectedArea] = useState<string>()
  const { loading: treeLoading, data: treeView } = useRequest(() => { return getServerpartTree() })
  const [showExportTable, setShowExportTable] = useState<boolean>(false)
  const [commoditySelectList, setCommoditySelectList] = useState<any>()
  const [commodityList, setCommodityList] = useState<any>()
  const [columnsStateMap, setColumnsStateMap] = useState<any>({
    // Business_Type:{show:false},
    ShopTrade: { show: false },
    "TotalRevenue.Mobile_Correct": { show: false },
    "TotalRevenue.Cash_Correct": { show: false },
    "RegionARevenue.Mobile_Correct": { show: false },
    "RegionARevenue.Cash_Correct": { show: false },
    "RegionBRevenue.Mobile_Correct": { show: false },
    "RegionBRevenue.Cash_Correct": { show: false },
  })
  const [columnsDailyStateMap, setColumnsDailyStateMap] = useState<any>({
    Shop_Count: { show: false },
    Business_Type: { show: false },
    MERCHANTS_NAME: { show: false },
    ShopTrade: { show: false },
  })
  const SHOPTRADEObj = session.get('SHOPTRADEObj')
  // 显示每日流水抽屉
  const [showDailyDrawer, setShowDailyDrawer] = useState<boolean>(false)
  const [currentRow, setCurrentRow] = useState<any>()
  // 展示自营业态
  const [showSelfBusiness, setShowSelfBusiness] = useState<boolean>(true)
  // 自营业态的选择列表
  const [shopNamesList, setShopNamesList] = useState<any>()
  // 导出的加载效果
  const [showLoading, setShowLoading] = useState<boolean>(false)
  // useEffect(() => {
  //     // 判断页面进入模式是否是带参数跳转进入，如果是则根据参数加载内容
  //     if (location.query?.StartDate) {
  //         setActiveKey('1')
  //         setShopId(currentUser?.ServerpartShopIds ? currentUser?.ServerpartShopIds.split(',').map(Number) : [])
  //         formRef.current?.setFieldsValue({ DataType: '1', search_date: [location.query?.StartDate, location.query?.EndDate] })
  //         formRef.current?.submit()
  //     }
  // }, [currentUser, location])
  const [printIndex, setPrintIndex] = useState<number>(new Date().getTime())
  // 判断是否是同一天
  const [isSameDay, setIsSameDay] = useState<boolean>(true)
  // 抽屉里面的数据
  const [dailyDrawerData, setDailyDrawerData] = useState<any>()

  const BUSINESSTYPEObj = session.get('BUSINESSTYPEObj')
  // 总服务区列表配置
  // @ts-ignore
  const columns: any = [
    {
      dataIndex: '',
      title: '',
      hideInTable: true,
      renderFormItem: () => {
        return <div style={{ whiteSpace: 'nowrap' }}>
          <Select
            style={{ width: '90px' }}
            value={activeKey}
            options={[{ label: '日报', value: '1' }, { label: '月报', value: '2' }]}
            onChange={(e: any) => {
              setActiveKey(e)
            }}
          >
          </Select>
          <Select
            style={{ width: '140px', marginLeft: '20px' }}
            value={DataSourceType}
            options={[{ label: '日结营收', value: '1' }, { label: '自然日营收', value: '2' }]}
            onChange={(e: any) => {
              setDataSourceType(e)
            }}
          >
          </Select>
        </div>
      }
    },
    {
      title: '统计时间',
      dataIndex: 'search_date',
      valueType: 'dateRange',
      hideInTable: true,
      hideInDescriptions: true,
      hideInSearch: activeKey === '2',
      initialValue: location.query?.StartDate ? [location.query?.StartDate, location.query?.EndDate] : [moment().add(-1, 'day'), moment().add(-1, 'day')],
      search: {
        transform: (value) => {
          return {
            StartDate: value[0],
            EndDate: value[1],
          };
        },
      },
    },
    {
      title: '统计类型',
      dataIndex: 'ShowShop',
      hideInTable: true,
      valueType: 'select',
      valueEnum: {
        1: '门店',
        0: '服务区',
        // 2: '日度'
      },
      initialValue: '1'
    },
    {
      title: '统计月份',
      dataIndex: 'search_months',
      valueType: "dateRange",
      hideInTable: true,
      hideInDescriptions: true,
      hideInSearch: activeKey === '1',
      initialValue: [moment().subtract(2, 'months').startOf("month"), moment().subtract(2, 'months').endOf("month")],
      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")
      }
    },
    {
      title: '经营模式',
      dataIndex: 'businessType',
      valueType: 'select',
      hideInTable: true,
      valueEnum: BUSINESSTYPEObj,
      fieldProps: {
        mode: "multiple",
        onChange: async (e) => {
          console.log('e', e)
          const flag = e.filter(item => item === '1000')?.toString() || ''
          console.log('flag', flag)
          if (flag) {
            setShowSelfBusiness(false)
            handleGetShopNamesList(selectedId)
          } else {
            setShowSelfBusiness(true)
            // setShopNamesList({})
          }
        }
      }
    },
    {
      title: '自营业态',
      dataIndex: 'shopNames',
      hideInTable: true,
      hideInSearch: showSelfBusiness,
      valueType: 'select',
      valueEnum: shopNamesList,
      // request: async () => {
      //   return await getFieldEnum({ FieldExplainField: 'BUSINESSTYPE' })
      // },
      fieldProps: {
        mode: 'multiple',
        showSearch: true,
        filterOption: (input, option) => (option?.label ?? '').toLowerCase().includes(input.toLowerCase()),
      }
    },
    {
      title: '外接系统',
      dataIndex: 'targetSystem',
      valueType: 'select',
      hideInTable: true,
      valueEnum: {
        "": '全部',
        1: "是",
        0: "否"
      },
      initialValue: ""
    },
    {
      title: '',
      dataIndex: 'SearchKeyValue',
      hideInTable: true,
      fieldProps: {
        placeholder: "请输入商户/品牌/门店/服务区"
      }
    },
    {
      // title: () => <Text strong>服务区信息</Text>,
      title: '服务区信息',
      hideInSearch: true,
      align: 'center',
      children: [
        {
          title: '序号',
          dataIndex: 'index',
          key: 'index',
          valueType: 'index',
          align: 'center',
          hideInTable: showDailyDrawer,
          width: 110,
          // render: (_, record) => {
          //     return (record?.ServerpartShop_Name || record?.Serverpart_ID === 0) ? '' : record?.index
          // }
        },
        {
          title: '服务区(门店)',
          dataIndex: 'Serverpart_Name',
          key: 'Serverpart_Name',
          ellipsis: true,
          width: 150,
          sorter: (a, b) => new Date(a.Serverpart_Name).getTime() - new Date(b.Serverpart_Name).getTime(),
          defaultSortOrder: 'descend',
          render: (_, record) => {
            return showDailyDrawer ?
              record?.SPRegionType_Name ? record?.SPRegionType_Name : record?.ServerpartShop_Name ? record?.ServerpartShop_Name : record?.Serverpart_Name :
              record?.SPRegionType_Name ? record?.SPRegionType_Name :
                <div>
                  <a style={{ color: isSameDay ? '#000' : '#1890ff' }} onClick={() => {
                    if (moment(searchParamsTime?.StartDate).format('YYYY-MM-DD') === moment(searchParamsTime?.EndDate).format('YYYY-MM-DD')) {
                    } else {
                      console.log('record', record)
                      if (record?.Serverpart_Name === '合计') {
                        let serverpartId: string = ''
                        if (record?.children && record?.children.length > 0) {
                          record?.children.forEach((item: any) => {
                            if (item.children && item.children.length > 0) {
                              item.children.forEach((subItem: any) => {
                                if (serverpartId) {
                                  serverpartId += `,${subItem.Serverpart_ID}`
                                } else {
                                  serverpartId = subItem.Serverpart_ID
                                }
                              })
                            }
                          })
                        }
                        setCurrentRow({
                          ...record,
                          Serverpart_ID: serverpartId
                        })
                        setShowDailyDrawer(true)
                      } else if (record?.SPRegionType_Name && record?.SPRegionType_Name.indexOf('管理中心') !== -1) {
                        let serverpartId: string = ''
                        if (record?.children && record?.children.length > 0) {
                          record?.children.forEach((item: any) => {
                            if (serverpartId) {
                              serverpartId += `,${item.Serverpart_ID}`
                            } else {
                              serverpartId = item.Serverpart_ID
                            }
                          })
                        }
                        setCurrentRow({
                          ...record,
                          Serverpart_ID: serverpartId
                        })
                        setShowDailyDrawer(true)
                      } else {
                        setCurrentRow(record)
                        setShowDailyDrawer(true)
                      }
                    }
                  }}>
                    {
                      record?.SPRegionType_Name ? record?.SPRegionType_Name : record?.ServerpartShop_Name ? record?.ServerpartShop_Name : record?.Serverpart_Name
                    }
                    {
                      record?.Transfer_Type > 0 ?
                        <img style={{ width: '16px', height: '16px', marginLeft: '4px' }} src={record?.Transfer_Type === 1 ? codeIcon : interfaceIcon} />
                        : ''
                    }
                  </a>
                  {
                    record?.TotalRevenue?.Supplement_Amount && record?.ServerpartShop_Name ?
                      <Tooltip title={record?.TotalRevenue?.Supplement_Amount}>
                        <img style={{ width: '20px', height: '20px', marginLeft: '4px' }} src={rectification} />
                      </Tooltip>
                      : ''
                  }
                </div>

          },
          // onCell: (record) => ({
          //   width: record?.ServerpartShop_Name ? 150 : 230,
          //   colSpan: record?.ServerpartShop_Name ? 2 : 1
          // }),
        },
        {
          title: '门店数',
          dataIndex: 'Shop_Count',
          key: 'Shop_Count',
          width: 68,
          align: 'center',
          render: (_, record) => {
            return record?.ServerpartShop_Name ?
              record?.ServerpartShop_Id && record?.ServerpartShop_Id.split(',') && record?.ServerpartShop_Id.split(',').length > 0 ? record?.ServerpartShop_Id.split(',').length
                : ''
              : record?.Shop_Count
          },
          // onCell: (record) => ({
          // width: record?.ServerpartShop_Name ? 0 : 80,
          // colSpan: record?.ServerpartShop_Name ? 0 : 1
          // }),
        },
        {
          title: '经营模式',
          width: 120,
          align: 'center',
          dataIndex: 'Business_Type',
          valueType: 'select',
          hideInSearch: true,
          valueEnum: BUSINESSTYPEObj
        },
        {
          title: '经营商户',
          width: 120,
          ellipsis: true,
          dataIndex: 'MERCHANTS_NAME',
          hideInSearch: true,
        },
        {
          dataIndex: 'ShopTrade',
          title: '商品业态',
          align: 'center',
          width: 120,
          valueType: 'select',
          hideInSearch: true,
          valueEnum: SHOPTRADEObj
          // request: async () => {
          //   // 这里要手动添加枚举字段（从下面这些字典中选择一个）：商品业态[BUSINESSTYPE]
          //   const options = await getFieldEnum({ FieldExplainField: 'BUSINESSTYPE' });
          //   return options;
          // },
        },
      ]
    },

    {
      // title: () => <Text strong>合计</Text>,
      title: '合计',
      hideInSearch: true,
      children: [
        {
          title: '实收金额',
          dataIndex: 'TotalRevenue.Revenue_Amount',
          align: 'right',
          width: 120,
          sorter: (a, b) => {
            return a.TotalRevenue?.Revenue_Amount - b.TotalRevenue?.Revenue_Amount
          },
          defaultSortOrder: 'descend',
          render: (_, record) => {
            const str: string = record?.RegionBRevenue?.Supplement_Amount || record?.RegionARevenue?.Supplement_Amount ? `${((record?.RegionARevenue?.Supplement_Amount || 0) + (record?.RegionBRevenue?.Supplement_Amount || 0)) > 0 ? '+' : ''}${(record?.RegionARevenue?.Supplement_Amount || 0) + (record?.RegionBRevenue?.Supplement_Amount || 0)}` : ''
            return <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'flex-end' }}>
              <span>{record?.TotalRevenue?.Revenue_Amount ? numeral(record?.TotalRevenue?.Revenue_Amount).format('0,0.00') : '-'}</span>
              {
                (record?.RegionARevenue?.Supplement_State === 1 || record?.RegionBRevenue?.Supplement_State === 1) && showDailyDrawer ?
                  <Tooltip title={str}>
                    <img style={{ width: '20px', height: '20px', marginLeft: '4px' }} src={rectification} />
                  </Tooltip>
                  : ''
              }
            </div>
          }
        },

        {
          title: '移动支付',
          dataIndex: 'TotalRevenue.MobilePay_Amount',
          width: 120,
          align: 'right',
          sorter: (a, b) => a.TotalRevenue?.MobilePay_Amount - b.TotalRevenue?.MobilePay_Amount,
          render: (_, record) => {
            return record?.TotalRevenue.MobilePay_Amount ? numeral(record?.TotalRevenue.MobilePay_Amount).format('0,0.00') : '-'
          }
        },
        {
          title: '现金支付',
          dataIndex: 'TotalRevenue.CashPay_Amount',
          width: 120,
          align: 'right',
          sorter: (a, b) => a.TotalRevenue?.CashPay_Amount - b.TotalRevenue?.CashPay_Amount,
          render: (_, record) => {
            return record?.TotalRevenue.CashPay_Amount ? numeral(record?.TotalRevenue.CashPay_Amount).format('0,0.00') : '-'
          }
        },
        {
          title: '移动支付冲正',
          dataIndex: 'TotalRevenue.Mobile_Correct',
          width: 120,
          align: 'right',
          render: (_, record) => {
            return record?.TotalRevenue?.Mobile_Correct ? numeral(record?.TotalRevenue?.Mobile_Correct).format('0,0.00') : '-'
          }
        },
        {
          title: '现金支付冲正',
          dataIndex: 'TotalRevenue.Cash_Correct',
          width: 120,
          align: 'right',
          render: (_, record) => {
            return record?.TotalRevenue?.Cash_Correct ? numeral(record?.TotalRevenue?.Cash_Correct).format('0,0.00') : '-'
          }
        },
        // {
        //     title: '长/短款',
        //     dataIndex: 'TotalRevenue.Different_Price_Less',
        //     width: 180,
        //     align: 'right',
        //     sorter: (a, b) => a.TotalRevenue?.Different_Price_Less - b.TotalRevenue?.Different_Price_Less,
        //     render: (_, record) => {
        //         const Different_Price_More = record?.TotalRevenue.Different_Price_More ? numeral(record?.TotalRevenue.Different_Price_More).format('0,0.00') : '-'
        //         const Different_Price_Less = record?.TotalRevenue.Different_Price_Less ? numeral(record?.TotalRevenue.Different_Price_Less).format('0,0.00') : '-'
        //         return Different_Price_More === '-' && Different_Price_Less === '-' ? '-' : `${Different_Price_More} / ${Different_Price_Less}`
        //     }
        // },

      ]
    },
    {

      // title: () => <Text strong>东(南)区</Text>,
      title: "东(南)区",
      hideInSearch: true,
      children: [
        {
          title: '实收金额',
          dataIndex: 'RegionARevenue.Revenue_Amount',
          width: 120,
          valueType: "money",
          align: 'right',
          // sorter: (a, b) => a.RegionARevenue.Revenue_Amount - b.RegionARevenue.Revenue_Amount,
          render: (_, record) => {
            const str: string = record?.RegionARevenue?.Supplement_Amount ? `${record?.RegionARevenue?.Supplement_Amount > 0 ? '+' : ''}${record?.RegionARevenue?.Supplement_Amount}` : ''
            return <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'flex-end' }}>
              <span>{record?.RegionARevenue && record?.RegionARevenue.Revenue_Amount ? numeral(record?.RegionARevenue.Revenue_Amount).format('0,0.00') : '-'}</span>
              {
                record?.RegionARevenue?.Supplement_State === 1 && showDailyDrawer ?
                  <Tooltip title={str}>
                    <img style={{ width: '20px', height: '20px', marginLeft: '4px' }} src={rectification} />
                  </Tooltip> : ''
              }
            </div>
          }
        },
        {
          title: '移动支付',
          dataIndex: 'RegionARevenue.MobilePay_Amount',
          width: 120,
          align: 'right',
          render: (_, record) => {
            return record?.RegionARevenue && record?.RegionARevenue.MobilePay_Amount ? numeral(record?.RegionARevenue.MobilePay_Amount).format('0,0.00') : '-'
          }
        },
        {
          title: '现金支付',
          dataIndex: 'RegionARevenue.CashPay_Amount',
          width: 120,
          align: 'right',
          render: (_, record) => {
            return record?.RegionARevenue && record?.RegionARevenue.CashPay_Amount ? numeral(record?.RegionARevenue.CashPay_Amount).format('0,0.00') : '-'
          }
        },
        {
          title: '移动支付冲正',
          dataIndex: 'RegionARevenue.Mobile_Correct',
          width: 120,
          align: 'right',
          render: (_, record) => {
            return record?.RegionARevenue?.Mobile_Correct ? numeral(record?.RegionARevenue?.Mobile_Correct).format('0,0.00') : '-'
          }
        },
        {
          title: '现金支付冲正',
          dataIndex: 'RegionARevenue.Cash_Correct',
          width: 120,
          align: 'right',
          render: (_, record) => {
            return record?.RegionARevenue?.Cash_Correct ? numeral(record?.RegionARevenue?.Cash_Correct).format('0,0.00') : '-'
          }
        },
        // {
        //     title: '长/短款',
        //     dataIndex: 'RegionARevenue.Different_Price_Less',
        //     width: 180,
        //     valueType: "money",
        //     align: 'right',
        //
        //     render: (_, record) => {
        //
        //         const Different_Price_More = record?.RegionARevenue && record?.RegionARevenue.Different_Price_More ? numeral(record?.RegionARevenue.Different_Price_More).format('0,0.00') : '-'
        //         const Different_Price_Less = record?.RegionARevenue && record?.RegionARevenue.Different_Price_Less ? numeral(record?.RegionARevenue.Different_Price_Less).format('0,0.00') : '-'
        //         return Different_Price_More === '-' && Different_Price_Less === '-' ? '-' : `${Different_Price_More} / ${Different_Price_Less}`
        //     }
        // },

      ]
    },
    {

      title: "西(北)区",
      // title: () => <Text strong>西(北)区</Text>,
      hideInSearch: true,
      children: [
        {
          title: '实收金额',
          dataIndex: 'RegionBRevenue.Revenue_Amount',
          align: 'right',
          width: 120,
          // sorter: (a, b) => a.RegionBRevenue.Revenue_Amount - b.RegionBRevenue.Revenue_Amount,
          render: (_, record) => {
            const str: string = record?.RegionBRevenue?.Supplement_Amount ? `${record?.RegionBRevenue?.Supplement_Amount > 0 ? '+' : ''}${record?.RegionBRevenue?.Supplement_Amount}` : ''
            return <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'flex-end' }}>
              <span>{record?.RegionBRevenue && record?.RegionBRevenue.Revenue_Amount ? numeral(record?.RegionBRevenue.Revenue_Amount).format('0,0.00') : '-'}</span>
              {
                record?.RegionBRevenue?.Supplement_State && showDailyDrawer ?
                  <Tooltip title={str}>
                    <img style={{ width: '20px', height: '20px', marginLeft: '4px' }} src={rectification} />
                  </Tooltip> : ''
              }
            </div>
          }
        },
        {
          title: '移动支付',
          dataIndex: 'RegionBRevenue.MobilePay_Amount',
          width: 120,
          align: 'right',
          render: (_, record) => {
            return record?.RegionBRevenue && record?.RegionBRevenue.MobilePay_Amount ? numeral(record?.RegionBRevenue.MobilePay_Amount).format('0,0.00') : '-'
          }
        },
        {
          title: '现金支付',
          dataIndex: 'RegionBRevenue.CashPay_Amount',
          width: 120,
          align: 'right',
          render: (_, record) => {
            return record?.RegionBRevenue && record?.RegionBRevenue.CashPay_Amount ? numeral(record?.RegionBRevenue.CashPay_Amount).format('0,0.00') : '-'
          }
        },
        {
          title: '移动支付冲正',
          dataIndex: 'RegionBRevenue.Mobile_Correct',
          width: 120,
          align: 'right',
          render: (_, record) => {
            return record?.RegionBRevenue?.Mobile_Correct ? numeral(record?.RegionBRevenue?.Mobile_Correct).format('0,0.00') : '-'
          }
        },
        {
          title: '现金支付冲正',
          dataIndex: 'RegionBRevenue.Cash_Correct',
          width: 120,
          align: 'right',
          render: (_, record) => {
            return record?.RegionBRevenue?.Cash_Correct ? numeral(record?.RegionBRevenue?.Cash_Correct).format('0,0.00') : '-'
          }
        },
        // {
        //     title: '长/短款',
        //     dataIndex: 'RegionBRevenue.Different_Price_Less',
        //     align: 'right',
        //     width: 180,
        //     render: (_, record) => {
        //         const Different_Price_More = record?.RegionBRevenue && record?.RegionBRevenue.Different_Price_More ? numeral(record?.RegionBRevenue.Different_Price_More).format('0,0.00') : '-'
        //         const Different_Price_Less = record?.RegionBRevenue && record?.RegionBRevenue.Different_Price_Less ? numeral(record?.RegionBRevenue.Different_Price_Less).format('0,0.00') : '-'
        //         return Different_Price_More === '-' && Different_Price_Less === '-' ? '-' : `${Different_Price_More} / ${Different_Price_Less}`
        //     }
        // },


      ]
    },
  ];

  // 导出的columns
  const exportColumns: any = [
    {
      title: "时间",
      width: 150,
      align: 'center',
      dataIndex: "Statistics_Date"
    },
    {
      // title: () => <Text strong>合计</Text>,
      title: '合计',
      hideInSearch: true,
      children: [
        {
          title: '实收金额',
          dataIndex: 'TotalRevenue.Revenue_Amount',
          align: 'right',
          valueType: 'digit',
          width: 120,
        },
        {
          title: '移动支付',
          dataIndex: 'TotalRevenue.MobilePay_Amount',
          width: 120,
          align: 'right',
          valueType: 'digit',
        },
        {
          title: '现金支付',
          dataIndex: 'TotalRevenue.CashPay_Amount',
          width: 120,
          align: 'right',
          valueType: 'digit',
        },
        {
          title: '移动支付冲正',
          dataIndex: 'TotalRevenue.Mobile_Correct',
          width: 120,
          align: 'right',
          valueType: 'digit',
        },
        {
          title: '现金支付冲正',
          dataIndex: 'TotalRevenue.Cash_Correct',
          width: 120,
          align: 'right',
          valueType: 'digit',
        },
      ]
    },
    {

      // title: () => <Text strong>东(南)区</Text>,
      title: "东(南)区",
      hideInSearch: true,
      children: [
        {
          title: '实收金额',
          dataIndex: 'RegionARevenue.Revenue_Amount',
          width: 120,
          align: 'right',
          valueType: 'digit',
        },
        {
          title: '移动支付',
          dataIndex: 'RegionARevenue.MobilePay_Amount',
          width: 120,
          align: 'right',
          valueType: 'digit',
        },
        {
          title: '现金支付',
          dataIndex: 'RegionARevenue.CashPay_Amount',
          width: 120,
          align: 'right',
          valueType: 'digit',
        },
        {
          title: '移动支付冲正',
          dataIndex: 'RegionARevenue.Mobile_Correct',
          width: 120,
          align: 'right',
          valueType: 'digit',
        },
        {
          title: '现金支付冲正',
          dataIndex: 'RegionARevenue.Cash_Correct',
          width: 120,
          align: 'right',
          valueType: 'digit',
        },
      ]
    },
    {

      title: "西(北)区",
      // title: () => <Text strong>西(北)区</Text>,
      hideInSearch: true,
      children: [
        {
          title: '实收金额',
          dataIndex: 'RegionBRevenue.Revenue_Amount',
          align: 'right',
          width: 120,
          valueType: 'digit',
        },
        {
          title: '移动支付',
          dataIndex: 'RegionBRevenue.MobilePay_Amount',
          width: 120,
          align: 'right',
          valueType: 'digit',
        },
        {
          title: '现金支付',
          dataIndex: 'RegionBRevenue.CashPay_Amount',
          width: 120,
          align: 'right',
          valueType: 'digit',
        },
        {
          title: '移动支付冲正',
          dataIndex: 'RegionBRevenue.Mobile_Correct',
          width: 120,
          align: 'right',
          valueType: 'digit',
        },
        {
          title: '现金支付冲正',
          dataIndex: 'RegionBRevenue.Cash_Correct',
          width: 120,
          align: 'right',
          valueType: 'digit',
        }
      ]
    }
  ]

  //   导出excel方法
  const exportTable = (e, haveType?: boolean) => {
    //   haveType判断要不要带上其他参数
    e.stopPropagation();                                            // 防止Collapse组件收起
    const main = document.getElementsByClassName(`RevenueReportHideBox${printIndex}`)[0]
    console.log('main', document.getElementsByClassName(`RevenueReportHideBox`))
    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');
    if (haveType) {
      const tableTop = document.createElement('div');
      tableTop.setAttribute('style', 'font-size:24px;font-weight:600')
      tableTop.innerText = `${DataSourceType === '1' ? '日结营收' : DataSourceType === '2' ? '自然日营收' : ''}`
      tempTable.appendChild(tableTop);
    }


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

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

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

    setShowLoading(false)

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

  // 自营业态的选择的列表方法
  const handleGetShopNamesList = async (id: any) => {
    const req: any = {
      ProvinceCode: currentUser?.ProvinceCode,
      BusinessType: 1000,
      ServerpartId: id || selectedId
    }
    const data = await handleGetShopShortNamesGet(req)
    console.log('data', data)
    if (data && data.length > 0) {
      const obj: any = {}
      if (data && data.length > 0) {
        data.forEach((item: any) => {
          obj[item] = item
        })
      }
      setShopNamesList(obj)
    }
  }

  return (
    <PageContainer header={{
      title: '',
      breadcrumb: {},
    }}>
      <div className={`RevenueReportHideBox${printIndex}`} style={{ position: 'fixed', zIndex: -1, top: 0, left: 0 }}>
        {
          showExportTable && reqDetailList && reqDetailList.length > 0 ?
            <ProTable
              columns={columns}
              dataSource={reqDetailList}
              pagination={false}
              expandable={{
                defaultExpandAllRows: true
              }}
            /> : ''
        }
      </div>
      <div id='hiddenBox' style={{ position: 'fixed', zIndex: -1, top: 0, left: 0 }} />
      <div style={{ backgroundColor: '#fff', display: 'flex' }}>
        <ProCard
          className="pageTable-leftnav"
          bodyStyle={{ padding: 0, paddingTop: 20, paddingLeft: 20, width: !collapsible ? "300px" : "60px" }}
          extra={<MenuFoldOutlined onClick={() => {
            setCollapsible(!collapsible);
          }} rev={undefined} />}
          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) => {
              console.log('info', info)
              const selectedArea = info.checkedNodes.filter(n => n?.type === 0)
              const selectedIds = info.checkedNodes.filter(n => n?.type === 1)
              setSelectedId(selectedIds.map(n => n?.value)?.toString() || '')
              setSelectedArea(selectedArea.map(n => n?.value)?.toString() || '')
              handleGetShopNamesList(selectedIds.map(n => n?.value)?.toString() || '')
              // actionRef?.current?.reload()
            }}
          // switcherIcon={<PlusOutlined />}
          /> : ''}
        </ProCard>
        <div style={{
          width: !collapsible ? 'calc(100% - 300px)' : 'calc(100% - 60px)',
          paddingTop: 0,
          paddingBottom: 0,
          paddingRight: 0
        }}>
          <div
            ref={(el) => {
              // 打印报表
              if (!reqDetailList || reqDetailList.length === 0) return;
              setPrintOut(el);
            }}
          >
            <ProTable
              rowKey={(record) => {
                return `${record?.index}-${record?.Serverpart_ID}-${record?.ServerpartShop_Id}-${record?.Serverpart_Name}-${record?.ServerpartShop_Name}`
              }}
              formRef={formRef}
              actionRef={actionRef}
              search={{
                span: 6,
                defaultCollapsed: false,
              }}
              request={async (params, sorter) => {

                const sortstr = Object.keys(sorter).map(n => {
                  const value = sorter[n]
                  return value ? `${n} ${value.replace('end', '')}` : ''
                })
                console.log('sortstrsortstrsortstr', sortstr);

                params.ServerpartIds = selectedId || '0'
                if (params?.StartDate === params?.EndDate) {
                  setIsSameDay(true)
                } else {
                  setIsSameDay(false)
                }
                const req: RevenueStatisticsParams = {
                  ...params,
                  DataType: activeKey || '1',
                  DataSourceType: DataSourceType || '1',
                  ShowShop: params.ShowShop === '1',
                  targetSystem: params.targetSystem || '',
                  businessType: params?.businessType ? params?.businessType.toString() : '',
                  shopNames: params.shopNames || '',
                  SearchKeyName: "MerchantName,Brand,Shop,Serverpart"
                }
                console.log('req', req)
                handleCallLogs()
                const data = await getRevenueReport(req);
                setSearchParamsTime(params)
                setSearchTime([params.StartDate, params.EndDate])

                let filterList: any = sortTreeData(data.data, sortstr.toString())
                console.log('filterList', filterList);


                setReqDetailList(data.data);
                setPrintOut(undefined);
                const list = data.data
                console.log('selectedId', selectedId)
                console.log('selectedArea', selectedArea)
                console.log('list', list)

                let isOneArea: boolean | null = null
                let isOneService: boolean = false
                if (selectedArea && selectedArea.indexOf(',') === -1) {
                  isOneArea = true
                }
                if (selectedId && selectedId.indexOf(',') === -1) {
                  isOneService = true
                }

                let result: any = []
                if (list && list.length > 0) {
                  list.forEach((item: any, index: number) => {
                    item.index = index + 1
                    if (item.children && item.children.length > 0) {
                      item.children.forEach((subItem: any, subIndex: number) => {
                        subItem.index = `${index + 1}-${subIndex + 1}`
                        if (subItem.children && subItem.children.length > 0) {
                          subItem.children.forEach((thirdItem: any, thirdIndex: number) => {
                            thirdItem.index = `${index + 1}-${subIndex + 1}-${thirdIndex + 1}`
                            if (thirdItem.children && thirdItem.children.length > 0) {
                              thirdItem.children.forEach((fourthItem: any, fourthIndex: number) => {
                                fourthItem.index = `${index + 1}-${subIndex + 1}-${thirdIndex + 1}-${fourthIndex + 1}`
                              })
                            }
                          })
                        }
                      })
                    }
                  })
                  console.log('list', list);

                  if (isOneService) {
                    const res: any = []
                    list.forEach((item: any, index: number) => {
                      item.index = index + 1
                      if (item.children && item.children.length > 0) {
                        item.children.forEach((subItem: any, subIndex: number) => {
                          subItem.index = `${index + 1}-${subIndex + 1}`
                          if (subItem.children && subItem.children.length > 0) {
                            subItem.children.forEach((thirdItem: any, thirdIndex: number) => {
                              thirdItem.index = `${index + 1}-${subIndex + 1}-${thirdIndex + 1}`
                              res.push(thirdItem)
                            })
                          }
                        })
                      }
                    })
                    result = res
                    console.log('result', result)
                  } else {
                    if (isOneArea || isOneArea === null) {
                      const res: any = []
                      list.forEach((item: any, index: number) => {
                        item.index = index + 1
                        if (item.children && item.children.length > 0) {
                          item.children.forEach((subItem: any, subIndex: number) => {
                            subItem.index = `${index + 1}-${subIndex + 1}`
                            subItem.SPRegionType_Name = subItem.Serverpart_Name
                            subItem.Serverpart_Name = ''
                            res.push(subItem)
                          })
                        }
                      })
                      result = res
                      console.log('result', result)
                    } else {
                      result = list
                      console.log('result', result)
                    }
                  }
                }

                let fieldData: any = [
                  'TotalRevenue.Revenue_Amount',
                  'TotalRevenue.MobilePay_Amount',
                  'TotalRevenue.CashPay_Amount',
                  'TotalRevenue.Mobile_Correct',
                  'TotalRevenue.Cash_Correct',
                  'RegionARevenue.Revenue_Amount',
                  'RegionARevenue.MobilePay_Amount',
                  'RegionARevenue.CashPay_Amount',
                  'RegionARevenue.Mobile_Correct',
                  'RegionARevenue.Cash_Correct',
                  'RegionBRevenue.Revenue_Amount',
                  'RegionBRevenue.MobilePay_Amount',
                  'RegionBRevenue.CashPay_Amount',
                  'RegionBRevenue.Mobile_Correct',
                  'RegionBRevenue.Cash_Correct',
                ]
                let enumList: any = ['ShopTrade']

                // 处理一下导出数据
                let newPrintData: any = formatTreeData(result, fieldData, enumList, SHOPTRADEObj, [])
                console.log('newPrintDatanewPrintDatanewPrintData', newPrintData);

                setReqDetailList(newPrintData);
                if (result) {
                  return { data: result, success: true };
                }
                return { data: [], success: true }

              }}

              // params={{ ServerpartShopIds: shopId && shopId.length > 0 ? shopId.toString() : '' }}
              rowClassName={(record) => expandRow?.includes(record?.Serverpart_ID) && !record?.ServerpartShop_Name ? 'expanded' : ''}
              expandable={
                {
                  rowExpandable: () => true,
                  defaultExpandedRowKeys: ['0-000'],
                  indentSize: 0,
                  expandRowByClick: true,
                  defaultExpandAllRows: true,
                  onExpand: (expanded, record) => {
                    if (expanded) {
                      setExpandRow([...expandRow, record.Serverpart_ID])
                    } else {
                      const nowData = expandRow?.reduce((p: number[], c) => {
                        if (c !== record?.Serverpart_ID) {
                          p.push(c)
                        }
                        return p
                      }, [])
                      setExpandRow(nowData || [])
                    }

                  }

                }
              }
              columnsState={{
                value: columnsStateMap,
                onChange: setColumnsStateMap,
              }}
              bordered
              columns={columns}
              headerTitle={<PageTitleBox props={props} />}
              toolbar={{
                actions: [
                  // <span style={{ visibility: 'hidden' }}>
                  //   <ReactHTMLTableToExcel
                  //     buttonText={'导出excel'}
                  //     ref={downloadBtnRef}
                  //     table="table-to-xls-RevenueReport"
                  //     filename={`门店经营报表（${moment(searchTime[0] || '').format('YYYY/MM/DD')}-${moment(searchTime[1] || '').format('YYYY/MM/DD')}）`}
                  //     sheet="sheet1"
                  //   />
                  // </span>,
                  <ReactToPrint
                    trigger={() => (
                      <Button key="printout" type="default" onClick={() => {
                      }}>
                        打印
                      </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 [start, end] = formRef.current?.getFieldValue('search_date');
                        const innerText = `统计时间：${moment(start).format('YYYY/MM/DD')}-${moment(end).format('YYYY/MM/DD')}`;

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

                        return ele
                      }
                      return ''
                    }}
                  />,
                  <Button
                    key="new"
                    type="primary"
                    onClick={async (e) => {
                      if (reqDetailList && reqDetailList.length > 0) {
                        // 尝试一下 导出新方法 
                        exportXlsxFromProColumnsExcelJS(columns,
                          reqDetailList,
                          `营收汇总报表${searchParamsTime?.StartDate}-${searchParamsTime?.EndDate}`,
                          {
                            // topTitle: `营收汇总报表`, // 顶部大标题
                            footerMaker: currentUser?.Name,
                            footerMakerTime: moment().format('YYYY-MM-DD HH:mm:ss'),
                            footerStatsTime: `${searchParamsTime?.StartDate}-${searchParamsTime?.EndDate}`
                          }
                        )
                      } else {
                        message.error('暂无数据可导出！')
                      }

                      // if (reqDetailList && reqDetailList.length > 0) {
                      //   setShowLoading(true)
                      //   setTimeout(() => {
                      //     setShowExportTable(true)
                      //     setTimeout(() => {
                      //       exportTable(e, true)
                      //     }, 100)
                      //   }, 100)
                      // } else {
                      //   message.error('暂无数据可导出！')
                      // }
                    }}
                  >
                    导出excel
                  </Button>,
                ],
              }}
              scroll={{ x: 1800, y: 'calc(100vh - 470px)' }}
              pagination={false}
            />
          </div>
        </div>
      </div>


      <Drawer
        width="90%"
        visible={showDailyDrawer}
        onClose={() => {
          setCurrentRow(undefined);
          setShowDailyDrawer(false);
        }}
        bodyStyle={{ backgroundColor: "#f9f9f9", padding: 16 }}
        destroyOnClose
        closable={false}
      >
        <ProTable
          rowKey={(record) => {
            return `${record?.Serverpart_ID}-${record?.Transfer_Type || 0}${record?.Serverpart_Name || 0}${record?.ServerpartShop_Name || 0}`
          }}
          formRef={formRef}
          actionRef={actionRef}
          search={false}
          options={false}
          columns={columns}
          bordered
          pagination={false}
          headerTitle={`${currentRow?.SPRegionType_Name || ''}` + `${currentRow?.Serverpart_Name || ''}` + ` ${currentRow?.ServerpartShop_Name || ''}`}
          request={async (params) => {
            console.log('currentRow', currentRow)
            // 判断点击的是否是门店
            let isShop: boolean = false
            let shopIds: string = ''
            // 是门店
            if (currentRow?.ServerpartShop_Id) {
              isShop = true
              shopIds = currentRow?.ServerpartShop_Id
            } else {
              if (currentRow?.children && currentRow?.children.length > 0) {
                currentRow?.children.forEach((item: any) => {
                  if (shopIds) {
                    shopIds += `,${item.ServerpartShop_Id}`
                  } else {
                    shopIds = item.ServerpartShop_Id
                  }
                })
              }
            }
            const req: any = {
              ServerpartIds: isShop ? '' : currentRow?.Serverpart_ID,
              ServerpartShopIds: isShop ? shopIds : '',
              StartDate: searchParamsTime?.StartDate ? moment(searchParamsTime?.StartDate).format('YYYY-MM-DD') : '',
              EndDate: searchParamsTime?.EndDate ? moment(searchParamsTime?.EndDate).format('YYYY-MM-DD') : '',
              DataType: 1,
              DataSourceType: DataSourceType || '1',
              ShowShop: searchParamsTime.ShowShop === '1',
              targetSystem: searchParamsTime.targetSystem || '',
              shopNames: searchParamsTime.shopNames || '',
              SearchKeyName: "MerchantName,Brand,Shop,Serverpart"
            }
            handleCallLogs()
            const data = await handleGetRevenueReportByDate(req);
            console.log('data2222', data)


            if (data && data.length > 0) {
              let fieldData: any = [
                "TotalRevenue.Revenue_Amount",
                "TotalRevenue.MobilePay_Amount",
                "TotalRevenue.CashPay_Amount",
                "TotalRevenue.Mobile_Correct",
                "TotalRevenue.Cash_Correct",
                "RegionARevenue.Revenue_Amount",
                "RegionARevenue.MobilePay_Amount",
                "RegionARevenue.CashPay_Amount",
                "RegionARevenue.Mobile_Correct",
                "RegionARevenue.Cash_Correct",
                "RegionBRevenue.Revenue_Amount",
                "RegionBRevenue.MobilePay_Amount",
                "RegionBRevenue.CashPay_Amount",
                "RegionBRevenue.Mobile_Correct",
                "RegionBRevenue.Cash_Correct"
              ]

              let newPrintData: any = formatTreeData(JSON.parse(JSON.stringify(data)), fieldData, [], [], [])
              console.log('newPrintDatanewPrintDatanewPrintData', newPrintData);
              setDailyDrawerData(newPrintData[0].children)
              return { data, success: true }
            }
            setDailyDrawerData([])
            return { data: [], success: true }

          }}
          columnsState={{
            value: columnsDailyStateMap,
            onChange: setColumnsDailyStateMap,
          }}
          scroll={{ x: 1000 }}
          expandable={{
            defaultExpandAllRows: true,
            defaultExpandedRowKeys: ['0-0合计0'],
          }}
          toolbar={{
            actions: [
              <Button
                key="new"
                type="primary"
                onClick={(e) => {
                  console.log('dailyDrawerDatadailyDrawerDatadailyDrawerDatadailyDrawerData', dailyDrawerData);

                  exportXlsxFromProColumnsExcelJS(exportColumns,
                    dailyDrawerData,
                    `${`${currentRow?.SPRegionType_Name || ''}` + `${currentRow?.Serverpart_Name || ''}` + ` ${currentRow?.ServerpartShop_Name || ''}`}每日营收汇总报表${moment(searchParamsTime?.StartDate).format('YYYY-MM-DD')}-${moment(searchParamsTime?.EndDate).format('YYYY-MM-DD')}`,
                    {

                      topTitle: `${`${currentRow?.SPRegionType_Name || ''}` + `${currentRow?.Serverpart_Name || ''}` + ` ${currentRow?.ServerpartShop_Name || ''}`}每日营收汇总报表`, // 顶部大标题
                    }
                  )
                }}
              >
                导出excel
              </Button>

            ]
          }}
        />
      </Drawer>
    </PageContainer>
  );
};

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