// 项目拆分审批流程查询
import React, { useRef, useState } from "react";
import type { CurrentUser } from "@/models/user";
import { connect } from "umi";
import useRequest from "@ahooksjs/use-request";
import type { ConnectState } from "@/models/connect";
import type { ActionType } from "@ant-design/pro-table";
import ProTable from "@ant-design/pro-table";
import type { FormInstance } from "antd";
import { Button, Spin } from "antd";
import { Card, Steps } from "antd";
import { Col, Drawer, Row, Tooltip } from "antd";
import {
  handleGetExamineList,
  handleGetExamineListReturnList,
  handleGetMonthAccountProinst
} from "@/pages/examine/examineList/service";
import { getFieldEnumTree, getMoney } from "@/services/options";
import session from "@/utils/session";
import moment from "moment/moment";
import { message, Modal, Popconfirm, Space } from "antd";
import type { ProFormInstance } from "@ant-design/pro-form";
import ProForm, { ProFormDigit, ProFormSelect, ProFormTextArea } from "@ant-design/pro-form";
import {
  handleGetGetBUSINESSAPPROVALDetail,
  handleGetProjectAccountList,
  handleGetTableMonthlyReconciliation,
  handleGetTableRevenueRecognition
} from "@/pages/reports/ShopExpenseDetail/service";
import {
  handleApproveAccount,
  handleApproveMonthAccountProinst,
  handleRejectAccount, handleRejectMonthAccountProinst
} from "@/pages/examine/reconciliationApproval/base/service";
import { handleGetAPPROVALROUTEList } from "@/pages/Setting/serviceConfig/service";
import CompareList from "@/pages/reports/revenueConfirmation/components/compareList";
import { handleGetBIZPSPLITMONTHDetail } from "@/pages/examine/monthSettlement/service";
import Draggable from "react-draggable";
import { handleGetProjectPeriodIncome } from "@/pages/reports/revenueConfirmation/components/service";
import addIcon from "@/assets/ai/add.png";
import reduce from "@/assets/ai/reduce.png";
import numeral from "numeral";
import ReviewProcess from "@/pages/reports/revenueConfirmation/components/ReviewProcess";
import RevenueList from "@/pages/BussinessProject/components/RevenueList";
import LoadingBox from "@/pages/reports/Finance/businessAnalysis/components/loading";
import ProDescriptions from "@ant-design/pro-descriptions";
import MonthSettlement from "@/pages/reports/revenueConfirmation/components/monthSettlement";
import { PageContainer } from "@ant-design/pro-layout";
import ProjectDetailDrawer from "@/pages/reports/component/ProjectDetailDrawer";
import { wrapTreeNode } from "@/utils/format";
import YearContentTable from "@/pages/reports/settlementAccount/component/yearContentTable";
import YearExamineProcess from "@/pages/reports/settlementAccount/component/yearExamineProcess";
import MonthExamineProcess from "@/pages/reports/settlementAccount/component/monthExamineProcess";
import ReactHTMLTableToExcel from "react-html-table-to-excel";
import PageTitleBox from "@/components/PageTitleBox";

const monthSearch: React.FC<{ currentUser?: CurrentUser }> = (props) => {
  const come: string = props?.location?.state
  const { currentUser } = props
  const downloadBtnRef = useRef<any>()
  const SETTLEMENT_MODESObj = session.get('SETTLEMENT_MODESObj')

  const actionRef = useRef<ActionType>();
  const formRef = useRef<FormInstance>();
  const actionDetailRef = useRef<ActionType>();
  const formDetailRef = useRef<FormInstance>();
  const editFormRef = useRef<ProFormInstance>();
  const YearContentTableRef = useRef<any>()
  // 是否显示打印的表格
  const [showExportTable, setShowExportTable] = useState<boolean>(false)
  const PROCESS_TYPEObj = session.get('PROCESS_TYPEObj')
  // 查询的条件
  const [searchParams, setSearchParams] = useState<any>()
  const [getType, setGetType] = useState<number>(0)
  const [proinstRow, setProinstRow] = useState<any>()
  const [showDescModal, setShowDescModal] = useState<boolean>(false)
  const formDescRef = useRef<any>();
  const [descText, setDescText] = useState<string>()
  const [showDetail, setShowDetail] = useState<boolean>(false)
  const [currentDefaultRow, setCurrentDefaultRow] = useState<any>()
  const [monthTime, setMonthTime] = useState<any>()
  const [allStateStr, setAllStateStr] = useState<string>()
  const [reqDetailList, setReqDetailList] = useState<any>(); // 合计项数据源
  // const [isFirst, setIsFirst] = useState<boolean>(true)
  // 结算悬浮框的值
  const [modalFormValue, setModalFormValue] = useState<any>()
  const [searchDetail, setSearchDetail] = useState<boolean>(false)
  // 悬浮框顶部的信息
  const [modalTopDetail, setModalTopDetail] = useState<any>()
  const [disabled, setDraggleDisabled] = useState<boolean>() // 是否拖动
  // 拖动开始
  const [bounds, setBounds] = useState<{ left: number, right: number, top: number, bottom: number }>() // 移动的位置
  const draggleRef = React.createRef<any>()
  // 年度还是月度
  const [busninessType, setBusinessType] = useState<number>(1)
  // 显示审核流程抽屉
  const [showReviewProcess, setShowReviewProcess] = useState<boolean>(false)
  // 月度状态的对象
  const [monthStateObj, setMonthStateObj] = useState<any>()
  // 年度状态的对象
  const [yearStateObj, setYearStateObj] = useState<any>()
  // 显示年度的详情抽屉
  const [showDeatilDrawer, setShowDetailDrawer] = useState<boolean>(false)
  // 显示年度表格上方内容
  const [otherData, setOtherData] = useState<any>();
  // 显示年度流程进度的当前状态
  const [progressState, setProgressState] = useState<number>(0)
  // 当前状态
  const [currentApprovalstate, setCurrentApprovalstate] = useState<any>()
  // 显示年度详情的加载效果
  const [detailLoading, setDetailLoading] = useState<boolean>(false)
  // 显示年度流程进度的数组
  const [progressList, setProgressList] = useState<any>()
  // 年度详情里面表格加载效果
  const [tableLoading, setTableLoading] = useState<boolean>(false)
  const [tableAllData, setTableAllData] = useState<any>()
  const [reqDetailListDetail, setReqDetailListDetail] = useState<any>(); // 合计项数据源
  const [printIndex, setPrintIndex] = useState<number>(new Date().getTime())
  // 当前点击的状态
  const [currentState, setCurrentState] = useState<any>()
  // 点击的是月度还是年度  1 年度  2 月度
  const [currentType, setCurrentType] = useState<string>('0')
  const [currentRow, setCurrentRow] = useState<any>()
  // 显示结算抽屉
  const [showExamineDetail, setShowExamineDetail] = useState<boolean>(false)
  // 是否显示批量月度审批的按钮
  const [isShowMonthBtn, setIsShowMonthBtn] = useState<boolean>(false)
  // 判断年度的是否可以结算
  const [isYearAllowSettlement, setIsYearAllowSettlement] = useState<boolean>(false)
  // 导出的加载效果
  const [showLoading, setShowLoading] = useState<boolean>(false)

  // compareList组件跳转月份的方法
  const handleGetNewMonth = async (obj: any, time: any) => {
    setShowExamineDetail(false)
    const req: any = {
      ServerpartId: obj?.SERVERPART_ID,
      ServerpartShopId: obj?.SERVERPARTSHOP_ID,
      StartDate: moment(time).format('YYYYMM'),
      EndDate: moment(time).format('YYYYMM'),
    }
    const data = await handleGetProjectAccountList(req)

    if (data && data.length > 0) {
      let bigObj: any = {}
      data.forEach((item: any) => {
        if (item.SETTLEMENT_TYPE === 2 && moment(item.ENDDATE).format('YYYYMM') === moment(time).format('YYYYMM')) {
          if (item.SHOPROYALTY_ID === obj?.SHOPROYALTY_ID) {
            bigObj = item
          }
        }
      })
      // const obj: any = data[0]
      setCurrentRow({
        ...bigObj,
        startTime: bigObj?.STARTDATE,
        endTime: bigObj?.ENDDATE,
        ShopRoyaltyId: bigObj?.SHOPROYALTY_ID,
        BUSINESSPROJECT_ID: bigObj?.BUSINESSPROJECT_ID,
        Id: bigObj?.SERVERPARTSHOP_ID,
        SERVERPART_ID: bigObj?.SERVERPART_ID,
        STATISTICS_MONTH: bigObj?.SETTLEMENT_DATE,
        Approvalstate: bigObj?.SETTLEMENT_STATE === 0 ? 0 : bigObj?.SETTLEMENT_STATE === 1 ? 9 : bigObj?.SETTLEMENT_STATE === 2 ? 1 : ''
      })
    }

    setShowExamineDetail(true)
  }


  // 合作商户合同期结算明细表表格的隐藏字段
  const [recordColumnsStateMap, setRecordColumnsStateMap] = useState<any>({
    BreachPenalty: { show: false },
    OtherFee: { show: false },
    SHOPEXPENSE_AMOUNT_1000: { show: false },
    SHOPEXPENSE_AMOUNT_2000: { show: false },
    SHOPEXPENSE_AMOUNT_3000: { show: false },
    SHOPEXPENSE_AMOUNT_5000: { show: false },
  })
  const onDraggaleStart = (event, uiData) => {

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

  // 点击期限 出现的每月或每日的数据
  const [showDailyDrawer, setShowDailyDrawer] = useState<boolean>(false)
  // 先把状态都请求出来
  const { loading: treeLoading, data: stateList } = useRequest(async () => {
    const req: any = {
      SearchParameter: {
        APPROVALROUTE_VALID: 1,
        OPERATION_TYPES: 12
      },
      SortStr: 'APPROVALROUTE_STATE asc',
      PageIndex: 1,
      PageSize: 999999
    }
    const secondReq: any = {
      SearchParameter: {
        APPROVALROUTE_VALID: 1,
        OPERATION_TYPES: 11
      },
      SortStr: 'APPROVALROUTE_STATE asc',
      PageIndex: 1,
      PageSize: 999999
    }
    const Yeardata = await handleGetAPPROVALROUTEList(secondReq)

    const data = await handleGetAPPROVALROUTEList(req)
    if (data && data.length > 0) {
      const list: any = []
      data.forEach((item: any) => {
        list.push({ label: item.APPROVALROUTE_NAME, value: item.APPROVALROUTE_STATE })
      })
      list.push({ label: '已审结', value: 9000 })
      list.push({ label: '已驳回', value: 3000 })
      let str: string = ''
      list.forEach((item: any) => {
        if (item.value === 3000) {

        } else {
          if (str) {
            str += `,${item.value}`
          } else {
            str = item.value
          }
        }
      })

      setAllStateStr(str)
      if (list && list.length > 0) {
        const obj: any = {}
        list.forEach((item: any) => {
          obj[item.value] = item.label
        })

        setMonthStateObj(obj)
      }
    }


    if (Yeardata && Yeardata.length > 0) {
      const list: any = []
      Yeardata.forEach((item: any) => {
        list.push({ label: item.APPROVALROUTE_NAME, value: item.APPROVALROUTE_STATE })
      })
      list.push({ label: '已审结', value: 9000 })
      list.push({ label: '已驳回', value: 3000 })
      let str: string = ''
      list.forEach((item: any) => {
        if (item.value === 3000) {

        } else {
          if (str) {
            str += `,${item.value}`
          } else {
            str = item.value
          }
        }
      })
      if (list && list.length > 0) {
        const obj: any = {}
        list.forEach((item: any) => {
          obj[item.value] = item.label
        })
        console.log('year', obj);

        setYearStateObj(obj)
      }
    }
  })



  const columns: any = [
    {
      title: '结算状态',
      width: 120,
      dataIndex: 'BusinessProcess_State',
      valueType: 'select',
      hideInSearch: true,
      align: 'center',
      fixed: 'left',
      // valueEnum: {
      //   "1000": "待提交",
      //   "2000": "审核中",
      //   "3000": "已驳回",
      //   "9000": "已审结",
      // },
      render: (_, record) => {
        return <a style={{
          color: (record?.BusinessProcess_State >= 2000 && record?.BusinessProcess_State < 9000 && record?.PendState === 0) ? '#faad14' :
            record?.BusinessProcess_State === 1000 && record?.PendState === 0 ? '#faad14' :
              ''
        }} onClick={() => {
          setCurrentState(record?.BusinessProcess_State)
          setCurrentType(record?.Operation_Type)
          console.log('record', record);
          const nowState: any = record?.BusinessProcess_State ? record?.BusinessProcess_State === 1000 ? record?.BusinessApproval_ID ? 1 : 0 : record?.BusinessProcess_State === 9000 ? 9 : 1 : ''
          setCurrentApprovalstate(nowState)
          if (record?.Operation_Type === '12') {
            const startTime: any = record?.STARTDATE
            const realTime: any = moment(record?.ENDDATE).startOf('M').format('YYYY-MM-DD')
            let resStartTime: any = ''
            if (new Date(startTime).getTime() > new Date(realTime).getTime()) {
              resStartTime = startTime
            } else {
              resStartTime = realTime
            }
            console.log('resStartTimeresStartTime', resStartTime);
            setCurrentRow({
              ...record,
              Approvalstate: nowState,
              startTime: resStartTime ? moment(resStartTime).format('YYYY-MM-DD') : '',
              endTime: record?.ENDDATE ? moment(record?.ENDDATE).format('YYYY-MM-DD') : '',
              ShopRoyaltyId: record?.SHOPROYALTY_ID,
              BUSINESSPROJECT_ID: record?.BUSINESSPROJECT_ID,
              Id: record?.ServerpartShop_ID,
              SERVERPART_ID: record?.Serverpart_ID,
              PEND_STATE: record?.PendState,
              SETTLEMENT_DATE: record?.ENDDATE ? moment(record?.ENDDATE).format('YYYY/MM') : '',
              STATISTICS_MONTH: record?.STATISTICS_MONTH ? moment(record?.STATISTICS_MONTH).format('YYYY-MM') : '',
              BUSINESSAPPROVAL_ID: record?.BusinessApproval_ID
            })
          } else {
            setCurrentRow({
              ...record,
              SETTLEMENT_STATE: record?.BusinessProcess_State === 9000 ? 1 : 2,
              PEND_STATE: record?.PendState,
              APPLY_PROCCESS: record?.BusinessProcess_State === 1000,
              BUSINESSAPPROVAL_ID: record?.BusinessApproval_ID,
              SERVERPARTSHOP_ID: record?.ServerpartShop_ID
            })

          }
          setShowExamineDetail(true)
        }}>
          {
            record?.BusinessProcess_State === 1000 ? '重新申请' :
              record?.BusinessProcess_State === 3000 ? '已驳回' :
                record?.BusinessProcess_State === 9000 ? '已审结' :
                  record?.BusinessProcess_State >= 2000 ? '审核中' : ''
          }
        </a>
      }
    },
    // {
    //   title: '服务区名称',
    //   width: 150,
    //   ellipsis: true,
    //   dataIndex: 'Serverpart_Name',
    //   hideInSearch: true
    // },
    {
      title: <div style={{ textAlign: 'center' }}>业务名称</div>,
      width: 400,
      ellipsis: true,
      dataIndex: 'BusinessProcess_Name',
      // render: (_, record) => {
      //   return <a onClick={async () => {
      //     if (busninessType === 1) {
      //       const res = await handleGetBIZPSPLITMONTHDetail({ BIZPSPLITMONTHId: record?.BusinessProcess_ID })
      //       setMonthTime(res.STATISTICS_MONTH)
      //       setModalFormValue({
      //         MobilePayCorrect: res.MOBILEPAY_CORRECT,
      //         CashPayCorrect: res.CASHPAY_CORRECT
      //       })
      //       setCurrentRow({
      //         ...record,
      //         ...res,
      //         RENTFEE: res.MINTURNOVER,
      //         TaxRate: '',
      //         MonthlyIncome: '',
      //         MonthlyCount: '',
      //         MonthlyTotalIncome: '',
      //         SERVERPART_ID: currentRow?.Serverpart_ID,
      //         Id: res.SERVERPARTSHOP_ID,
      //         STATISTICS_DATE_Start: moment(res.STARTDATE).format('YYYY-MM-DD'),
      //         startTime: moment(res.STARTDATE).format('YYYY-MM-DD'),
      //         STATISTICS_DATE_End: moment(res.ENDDATE).format('YYYY-MM-DD'),
      //         endTime: moment(res.ENDDATE).format('YYYY-MM-DD'),
      //         SHOPROYALTY_ID: res.SHOPROYALTY_ID,
      //         ShopRoyaltyId: res.SHOPROYALTY_ID,
      //         BUSINESSPROJECT_ID: res.BUSINESSPROJECT_ID,
      //         // SettlementModes: 3000,
      //         Approvalstate: res.Approvalstate,
      //         BusinessApprovalId: currentRow?.BusinessApproval_ID
      //       })
      //       setSearchDetail(true)
      //       setShowDetail(true)
      //     } else {
      //       console.log('record', record);

      //       const res = await handleGetBIZPSPLITMONTHDetail({ BIZPSPLITMONTHId: record?.BusinessProcess_ID })
      //       console.log('res', res);

      //       setCurrentRow({
      //         ...record,
      //         businessProjectId: res.BUSINESSPROJECT_ID,
      //         BusinessApprovalId: currentRow?.BusinessApproval_ID
      //       })
      //       // setCurrentRow(record)
      //       handleGetTableData(record?.BusinessProcess_ID, record?.Proinst_ID)
      //       setShowDetailDrawer(true)
      //     }

      //   }}>
      //     {record?.BusinessProcess_Name || ''}
      //   </a>
      // },
      render: (_, record) => {
        return record?.BusinessProcess_Name || ''
      }
    },
    {
      title: <div style={{ textAlign: 'center' }}>经办人</div>,
      width: 140,
      dataIndex: 'Staff_Name',
      ellipsis: true,
      hideInSearch: true,
      render: (_, record) => {
        return <Tooltip title={record?.Staff_Name}>
          <span style={{ whiteSpace: 'nowrap', textOverflow: 'ellipsis', overflow: 'hidden', width: '120px', display: 'inline-block' }}>{record?.Staff_Name}</span>
        </Tooltip>
      }
    },
    {
      title: '经营商户',
      width: 140,
      dataIndex: 'MERCHANTS_NAME',
      align: 'center',
      ellipsis: true,
      hideInSearch: true,
    },
    {
      title: '业务时间',
      width: 100,
      dataIndex: 'BusinessProcess_StartDate',
      align: 'center',
      hideInSearch: true,
      render: (_, record) => {
        return `${record?.BusinessProcess_StartDate ? moment(record?.BusinessProcess_StartDate).format('YYYY-MM-DD') : ''}`
      }
    },
    {
      title: <div style={{ textAlign: 'center' }}>业务状态</div>,
      width: 300,
      ellipsis: true,
      dataIndex: 'BusinessProcess_States',
      valueType: 'select',
      valueEnum: monthStateObj,
      hideInSearch: true,
      hideInTable: busninessType === 2,
      // hideInSearch: true,
      render: (_, record) => {
        return record?.BusinessProcess_State && monthStateObj ? `${monthStateObj[record?.BusinessProcess_State]}${record?.BusinessProcess_State === 9000 ? '' : `：${record?.ApproveStaff_Name}`}` : ''
      }
    },
    {
      title: '收款/退款',
      width: 120,
      align: 'center',
      dataIndex: 'PaymentTerms',
      hideInSearch: true,
      render: (_, record) => {
        return record?.PaymentTerms === 1 ? <span style={{ color: '#FF0000' }}>收款</span> : record?.PaymentTerms === 0 ? <span>退款</span> : '-'
      }
    },
    {
      title: <div style={{ textAlign: 'center' }}>金额</div>,
      width: 120,
      align: 'right',
      dataIndex: 'Liquidation_Amount',
      hideInSearch: true,
      valueType: 'digit'
    },
    {
      title: '业务状态',
      width: 350,
      ellipsis: true,
      hideInSearch: busninessType === 1,
      hideInTable: busninessType === 1,
      valueEnum: yearStateObj,
      dataIndex: 'BusinessProcess_States',
      valueType: 'select',
      render: (_, record) => {
        return record?.BusinessProcess_State ? `${yearStateObj[record?.BusinessProcess_State]}${record?.BusinessProcess_State === 9000 ? '' : `：${record?.ApproveStaff_Name}`}` : ''
      }
    },
    {
      title: <div style={{ textAlign: 'center' }}>经发部提单</div>,
      width: 120,
      dataIndex: 'BillState',
      ellipsis: true,
      align: 'center',
      hideInSearch: true,
      render: (_, record) => {
        return <span style={{ color: record?.BillState === 1 ? '' : '#FF0B0B' }}>{record?.BillState === 1 ? '已提单' : '未提单'}</span>
      }
    },
    {
      title: '结算类型',
      width: 100,
      dataIndex: 'Operation_Type',
      valueType: 'select',
      align: 'center',
      valueEnum: {
        "all": "全部",
        "11": "年度",
        "12": "月度"
      },
      initialValue: "all",
      fieldProps: {
        allowClear: false
      }
    },

    // {
    //   title: '待审核人名称',
    //   width: 150,
    //   ellipsis: true,
    //   dataIndex: 'ApproveStaff_Name',
    //   hideInSearch: true,
    //   render: (_, record) => {
    //     return record?.BusinessProcess_State === 9000 ? '' : record?.ApproveStaff_Name
    //   }
    // },

    {
      title: '本期累计时间',
      width: 180,
      ellipsis: true,
      align: 'center',
      hideInTable: busninessType === 2,
      dataIndex: 'STARTDATEENDDATE',
      hideInSearch: true,
      render: (_, record) => {
        return <a style={{ color: '#000' }} onClick={async () => {
          setCurrentRow(record)
          setShowDailyDrawer(true)
        }}>
          {`${record?.STARTDATE}-${record?.ENDDATE}`}
        </a>
      }
    },
    {
      title: '待办事项',
      width: 120,
      dataIndex: 'PendState',
      valueType: 'select',
      hideInTable: true,
      valueEnum: {
        "0": "全部",
        "1": "待审批",
        "2": "审批中",
        "3": "已审结",
        "4": "已驳回"
      },
      fieldProps: {
        allowClear: false
      },
      // 原本的
      // valueEnum: {
      //   "2": "全部",
      //   "0": "待审批",
      //   "1": "审批中",
      //   "9000": "已审结",
      //   "3000": "已驳回"
      // },
      initialValue: come === 'login' ? "1" : "0",
    },

    // {
    //   title: '备注说明',
    //   width: 200,
    //   ellipsis: true,
    //   dataIndex: 'BusinessProcess_Desc',
    //   hideInSearch: true
    // },
  ]
  const stateSelectList: any = ["2", "0", "1", "2", "3000"]
  const processState: any = ['', "1000", "2000", "9000", "3000"]


  const defaultColumns: any = [
    {
      title: '类型',
      dataIndex: 'type',
      width: 180,
      hideInSearch: true,
      render: (_, record) => {
        return <span>{record?.type}
          <span style={{ color: 'red', cursor: 'pointer' }} onClick={() => {
            setCurrentDefaultRow({
              ...currentRow,
              ...record,
              BusinessApprovalId: currentRow.BusinessApproval_ID
            })
            console.log('111', {
              ...currentRow,
              ...record,
            })
            setShowReviewProcess(true)
          }} >{`${currentRow?.Approvalstate === 9 && record?.type === '精算金额' ? '（已审结）' : currentRow?.Approvalstate > 0 && currentRow?.Approvalstate < 9 && record?.type === '精算金额' ? '（审核中）' : ''}`}</span>
        </span>
      }
    },
    {
      title: '统计时间',
      dataIndex: 'search_months',
      valueType: 'date',
      initialValue: moment().subtract(1, 'months').format('YYYY-MM'),
      search: {
        transform: (value) => {
          return {
            MonthDate: moment(value).startOf("month").format('YYYY-MM'),
          };
        },
      },
      hideInTable: true,
      fieldProps: {
        picker: "month",
        format: 'YYYY-MM',
      }
    },
    {
      title: <div style={{ textAlign: 'center' }}>{'本期累计时间'}</div>,
      dataIndex: 'IndexDesc',
      align: 'left',
      width: 180,
      hideInSearch: true,
      render: (_, record) => {
        return <a onClick={async () => {
          setShowDailyDrawer(true)
        }}>
          {`${record?.IndexDesc}`}
        </a>
      }
    },
    {
      title: '浮动提成应确认收入',
      dataIndex: '',
      hideInSearch: true,
      children: [
        {
          title: <div style={{ textAlign: 'center' }}>{'累计营业额'}</div>,
          dataIndex: 'REVENUEDAILY_AMOUNTTotal',
          width: 120,
          valueType: 'digit',
          align: 'right',
          hideInSearch: true,
          render: (_, record) => {
            return record?.REVENUEDAILY_AMOUNTTotal ?
              <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'flex-end' }}>
                {
                  record?.RevenueTrend === true || record?.RevenueTrend === false ?
                    <img style={{ width: '20px', height: '20px' }}
                      src={record?.RevenueTrend === true ? addIcon : record?.RevenueTrend === null ? '' : reduce} /> : ''
                }
                {
                  record?.BUSINESSPROJECT_ID ?
                    <span>{numeral(getMoney(record?.REVENUEDAILY_AMOUNTTotal)).format('0,0.00')}</span> :
                    <span>{numeral(getMoney(record?.REVENUEDAILY_AMOUNTTotal)).format('0,0.00')}</span>
                }
              </div>
              :
              '-'
          }
        },
        {
          title: <div style={{ textAlign: 'center' }}>{'移动支付'}</div>,
          dataIndex: 'MobilePay',
          width: 120,
          valueType: 'digit',
          align: 'right',
          hideInSearch: true,
        },
        {
          title: <div style={{ textAlign: 'center' }}>{'移动冲正'}</div>,
          dataIndex: 'MOBILEPAY_CORRECT',
          align: 'right',
          valueType: 'digit',
          width: 120,
          hideInSearch: true,
        },
        {
          title: <div style={{ textAlign: 'center' }}>{'现金交易'}</div>,
          dataIndex: 'CashPay',
          width: 120,
          valueType: 'digit',
          align: 'right',
          hideInSearch: true,
        },
        {
          title: <div style={{ textAlign: 'center' }}>{'现金冲正'}</div>,
          dataIndex: 'CASHPAY_CORRECT',
          align: 'right',
          valueType: 'digit',
          width: 120,
          hideInSearch: true,
        },
        {
          title: <div style={{ textAlign: 'center' }}>{'提成金额'}</div>,
          dataIndex: 'GUARANTEERATIOAMOUNT',
          width: 120,
          valueType: 'digit',
          align: 'right',
          hideInSearch: true,
          render: (_, record) => {
            const title: string = `分润营业额(${record.REVENUEDAILY_AMOUNTTotal}) * 提成比例(${record.GUARANTEERATIO ? `${record.GUARANTEERATIO}%` : ''})`
            return record.GUARANTEERATIO ? <Tooltip title={title}>
              <span>{numeral(record?.GUARANTEERATIOAMOUNT).format('0,0.00')}</span>
            </Tooltip> : <span>{numeral(record?.GUARANTEERATIOAMOUNT).format('0,0.00')}</span>
          }
        },
        {
          title: <div style={{ textAlign: 'center' }}>{'提成收入'}</div>,
          dataIndex: 'GUARANTEERATIOINCOME',
          width: 120,
          valueType: 'digit',
          align: 'right',
          hideInSearch: true,
          render: (_, record) => {
            const title: string = `提成金额(${record.GUARANTEERATIOAMOUNT}) / 税(1 + ${numeral(record.TaxRate / 100).format('0.00')})`
            return record.TaxRate ? <Tooltip title={title}>
              <span>{numeral(record?.GUARANTEERATIOINCOME).format('0,0.00')}</span>
            </Tooltip> : <span>{numeral(record?.GUARANTEERATIOINCOME).format('0,0.00')}</span>
          }
        },
      ]
    },
    {
      title: <div style={{ textAlign: 'center' }}>
        <div style={{ textAlign: 'center' }}>当月营业额</div>
        {
          showDetail ?
            <div style={{ textAlign: 'center' }}>{modalTopDetail?.IndexDesc || ''}</div> : ''
        }
      </div>,
      dataIndex: 'CurMonthRevenue',
      align: 'right',
      valueType: 'digit',
      hideInSearch: true,
    },
    {
      title: '本月确认收入',
      dataIndex: '',
      fixed: 'right',
      hideInSearch: true,
      hideInTable: true,
      children: [
        {
          title: <div style={{ textAlign: 'center' }}>{'累计应确认收入'}</div>,
          dataIndex: 'ROYALTYTHEORYMUST',
          width: 130,
          valueType: 'digit',
          align: 'right',
          fixed: 'right',
          hideInSearch: true,
          render: (_, record) => {
            const title: string = record?.GUARANTEERATIOINCOME > record?.MonthlyTotalIncome ?
              `${record?.GUARANTEERATIOINCOME}(提成收入)>${record?.MonthlyTotalIncome}(累计应确认收入)=${record?.GUARANTEERATIOINCOME}(提成收入)` :
              `${record?.MonthlyTotalIncome}(累计应确认收入)>${record?.GUARANTEERATIOINCOME}(提成收入)=${record?.MonthlyTotalIncome}(累计应确认收入)`
            return record?.ROYALTYTHEORYMUST && record?.BUSINESSPROJECT_ID ?
              <Tooltip title={title}>
                <span>{record?.ROYALTYTHEORYMUST ? numeral(record?.ROYALTYTHEORYMUST).format('0,0.00') : '-'}</span>
              </Tooltip>
              : record?.ROYALTYTHEORYMUST ? numeral(record?.ROYALTYTHEORYMUST).format('0,0.00') : '-'
          }
        },
        {
          title: <div style={{ textAlign: 'center' }}>{'累计已确认收入'}</div>,
          dataIndex: 'ROYALTYTHEORYOK',
          width: 130,
          valueType: 'digit',
          align: 'right',
          fixed: 'right',
          hideInSearch: true,
          render: (_, record) => {
            return <span>{record?.ROYALTYTHEORYOK ? numeral(record?.ROYALTYTHEORYOK).format('0,0.00') : '-'}</span>
          }
        },
        {
          title: <div style={{ textAlign: 'center' }}>{'本月应确认'}</div>,
          dataIndex: 'ROYALTYTHEORYMONTHLYMUST',
          width: 110,
          valueType: 'digit',
          align: 'right',
          fixed: 'right',
          hideInSearch: true,
          render: (_, record) => {
            const title: string = `累计应确认收入(${record.ROYALTYTHEORYMUST}) - 累计已确认收入(${numeral(record?.ROYALTYTHEORYOK).format('0.00')})`
            return <Tooltip title={title}>
              <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'flex-end' }}>
                {
                  record?.ROYALTYTrend === true || record?.ROYALTYTrend === false ?
                    <img style={{ width: '20px', height: '20px' }}
                      src={record?.ROYALTYTrend === true ? addIcon : record?.ROYALTYTrend === null ? '' : reduce} /> : ''
                }
                <span>{record?.ROYALTYTHEORYMONTHLYMUST ? numeral(record?.ROYALTYTHEORYMONTHLYMUST).format('0,0.00') : '-'}</span>
              </div>
            </Tooltip>
          }
        },
      ]
    },
  ]
  const detailColumns: any = [
    {
      title: <div style={{ textAlign: 'center' }}>期限</div>,
      dataIndex: 'PeriodDesc',
      align: 'left',
      width: 300,
      fixed: 'left',
      hideInSearch: true,
      render: (_, record) => {
        return <span>{`${record?.PeriodDesc}`}</span>
      }
    },
    {
      title: <div style={{ textAlign: 'center' }}>结算状态</div>,
      dataIndex: 'IsApplySuccess',
      align: 'right',
      width: 100,
      hideInSearch: true,
      render: (_, record) => {
        return record?.level === 1 ?
          currentRow?.Approvalstate === 0 ? <span style={{ color: '#1890ff' }}>{'待结算'}</span> :
            currentRow?.Approvalstate === 1 ? <span style={{ color: '#1890ff' }}>{'审批中'}</span> :
              currentRow?.Approvalstate === 9 ? <span style={{ color: '#faad14' }}>{'已结算'}</span> : ''
          : record?.IsApplySuccess ?
            // 子级跳进去
            <span>{'已结算'}</span>
            :
            <span>{'待结算'}</span>
      }
    },
    {
      title: '租金信息',
      dataIndex: '',
      hideInSearch: true,
      children: [
        {
          title: <div style={{ textAlign: 'center' }}>保底/固定租金</div>,
          dataIndex: 'MinturnOver',
          valueType: 'digit',
          align: 'right',
          width: 130,
          hideInSearch: true,
        },
        {
          title: <div style={{ textAlign: 'center' }}>提成比率</div>,
          dataIndex: 'GuaranteeRatio',
          hideInSearch: true,
          align: 'right',
          width: 100,
          render: (_, record) => {
            return record?.GuaranteeRatio ? `${record?.GuaranteeRatio}%` : ''
          }
        }
      ]
    },
    {
      title: '营业额',
      dataIndex: '',
      hideInSearch: true,
      children: [
        {
          title: <div style={{ textAlign: 'center' }}>现金</div>,
          dataIndex: 'CashAmount',
          valueType: 'digit',
          align: 'right',
          width: 80,
          hideInSearch: true,
        },
        {
          title: <div style={{ textAlign: 'center' }}>微支付</div>,
          dataIndex: 'MobilePayAmount',
          valueType: 'digit',
          align: 'right',
          width: 100,
          hideInSearch: true,
        },
        {
          title: <div style={{ textAlign: 'center' }}>小计</div>,
          dataIndex: 'RevenueAmount',
          valueType: 'digit',
          align: 'right',
          width: 150,
          hideInSearch: true,
          render: (_, record) => {
            return <span>{record?.RevenueAmount ? numeral(getMoney(record?.RevenueAmount)).format('0,0.00') : '0'}</span>
          }
        }
      ]
    },
    {
      title: <div style={{ textAlign: 'center' }}>业主收款</div>,
      dataIndex: 'RoyaltyAmount',
      valueType: 'digit',
      width: 100,
      align: 'right',
      hideInSearch: true,
    },
    {
      title: '应收费用',
      dataIndex: '',
      hideInSearch: true,
      children: [
        {
          title: <div style={{ textAlign: 'center' }}>合计</div>,
          dataIndex: 'ReceivableAmount',
          valueType: 'digit',
          align: 'right',
          width: 100,
          hideInSearch: true,
          render: (_, record) => {
            return record?.ReceivableAmount ? numeral(getMoney(record?.ReceivableAmount)).format('0,0.00') : ''
          }
        },
        {
          title: <div style={{ textAlign: 'center' }}>租金</div>,
          dataIndex: 'GuaranteeFee',
          valueType: 'digit',
          align: 'right',
          width: 120,
          hideInSearch: true,
          render: (_, record) => {
            return record?.GuaranteeFee ? numeral(getMoney(record?.GuaranteeFee)).format('0,0.00') : ''
          }
        },
        {
          title: <div style={{ textAlign: 'center' }}>物业费</div>,
          dataIndex: 'PropertyFee',
          valueType: 'digit',
          align: 'right',
          width: 100,
          hideInSearch: true,
          render: (_, record) => {
            return record?.PropertyFee ?
              numeral(getMoney(record?.PropertyFee)).format('0,0.00')
              : record?.PropertyFee === 0 ? <span style={{ color: 'red' }}>0</span> : ''
          }
        },
        {
          title: <div style={{ textAlign: 'center' }}>房租</div>,
          dataIndex: 'HouseRent',
          valueType: 'digit',
          align: 'right',
          width: 80,
          hideInSearch: true,
        },
        {
          title: <div style={{ textAlign: 'center' }}>罚款</div>,
          dataIndex: 'BreachPenalty',
          valueType: 'digit',
          align: 'right',
          width: 80,
          hideInSearch: true,
        },
        {
          title: <div style={{ textAlign: 'center' }}>电费</div>,
          dataIndex: 'ElectricityCharge',
          valueType: 'digit',
          align: 'right',
          width: 80,
          hideInSearch: true,
          render: (_, record) => {
            return record?.ElectricityCharge ?
              numeral(getMoney(record?.ElectricityCharge)).format('0,0.00')
              : record?.ElectricityCharge === 0 ? <span style={{ color: 'red' }}>0</span> : ''
          }
        },
        {
          title: <div style={{ textAlign: 'center' }}>水费</div>,
          dataIndex: 'WaterCharge',
          valueType: 'digit',
          align: 'right',
          width: 80,
          hideInSearch: true,
          render: (_, record) => {
            return record?.WaterCharge ?
              numeral(getMoney(record?.WaterCharge)).format('0,0.00')
              : record?.WaterCharge === 0 ? <span style={{ color: 'red' }}>0</span> : ''
          }
        },
        {
          title: <div style={{ textAlign: 'center' }}>其他</div>,
          dataIndex: 'OtherFee',
          valueType: 'digit',
          align: 'right',
          width: 80,
          hideInSearch: true,
        }
      ]
    },
    {
      title: '已缴费用',
      dataIndex: '',
      align: 'center',
      hideInSearch: true,
      children: [
        {
          title: <div style={{ textAlign: 'center' }}>合计</div>,
          dataIndex: 'SHOPEXPENSE_AMOUNT',
          valueType: 'digit',
          align: 'right',
          width: 100,
          hideInSearch: true,
          render: (_, record) => {
            return record?.SHOPEXPENSE_AMOUNT ? numeral(getMoney(record?.SHOPEXPENSE_AMOUNT)).format('0,0.00') : ''
          }
        },
        {
          title: <div style={{ textAlign: 'center' }}>水费</div>,
          dataIndex: 'SHOPEXPENSE_AMOUNT_1000',
          valueType: 'digit',
          align: 'right',
          width: 80,
          hideInSearch: true,
          render: (_, record) => {
            return record?.SHOPEXPENSE_AMOUNT_1000 ?
              numeral(getMoney(record?.SHOPEXPENSE_AMOUNT_1000)).format('0,0.00')
              : record?.SHOPEXPENSE_AMOUNT_1000 === 0 ? <span style={{ color: 'red' }}>0</span> : ''
          }
        },
        {
          title: <div style={{ textAlign: 'center' }}>电费</div>,
          dataIndex: 'SHOPEXPENSE_AMOUNT_2000',
          valueType: 'digit',
          align: 'right',
          width: 80,
          hideInSearch: true,
          render: (_, record) => {
            return record?.SHOPEXPENSE_AMOUNT_2000 ?
              numeral(getMoney(record?.SHOPEXPENSE_AMOUNT_2000)).format('0,0.00')
              : record?.SHOPEXPENSE_AMOUNT_2000 === 0 ? <span style={{ color: 'red' }}>0</span> : ''
          }
        },
        {
          title: <div style={{ textAlign: 'center' }}>房租</div>,
          dataIndex: 'SHOPEXPENSE_AMOUNT_3000',
          valueType: 'digit',
          align: 'right',
          width: 80,
          hideInSearch: true,
        },
        {
          title: <div style={{ textAlign: 'center' }}>物业费</div>,
          dataIndex: 'SHOPEXPENSE_AMOUNT_5000',
          valueType: 'digit',
          align: 'right',
          width: 100,
          hideInSearch: true,
          render: (_, record) => {
            return record?.SHOPEXPENSE_AMOUNT_5000 ?
              numeral(getMoney(record?.SHOPEXPENSE_AMOUNT_5000)).format('0,0.00')
              : record?.SHOPEXPENSE_AMOUNT_5000 === 0 ? <span style={{ color: 'red' }}>0</span> : ''
          }
        }
      ]
    },
    {
      title: <div style={{ textAlign: 'center' }}>退补款</div>,
      dataIndex: 'RefundSupplement',
      valueType: 'digit',
      align: 'right',
      fixed: 'right',
      width: 100,
      hideInSearch: true,
      render: (_, record) => {
        return record?.RefundSupplement ? numeral(getMoney(record?.RefundSupplement)).format('0,0.00') : ''
      }
    },

  ]
  // 外面表格的请求数据的方法
  const handleGetTableData = async (id?: any, SHOPROYALTY_ID?: any) => {
    if (!id) {
      return
    }
    setTableLoading(true)
    const req = {
      BUSINESSPROJECT_ID: id,
      SHOPROYALTY_ID
    }
    const data = await handleGetTableMonthlyReconciliation(req)
    let res: any = {}
    let list: any = []
    let otherMessage: any = {}
    if (data.List && data.List.length > 0) {
      res = data.List[0]
      setTableAllData(res)
      if (data.List[0].ProjectPeriodList) {
        otherMessage = data.List[0].ProjectPeriodList.node
        const resObj: any = data.List[0].ProjectPeriodList
        if (resObj.children && resObj.children.length > 0) {
          list = wrapTreeNode(resObj.children)
        }
      }
    }

    list.unshift({
      PeriodIndexStr: '',
      PeriodDesc: '合计',
      MinturnOver: otherMessage?.MinturnOver,
      GuaranteeRatio: otherMessage?.GuaranteeRatio,
      CashAmount: otherMessage?.CashAmount,
      MobilePayAmount: otherMessage?.MobilePayAmount,
      RevenueAmount: otherMessage?.RevenueAmount,
      RoyaltyAmount: otherMessage?.RoyaltyAmount,
      GuaranteeFee: otherMessage?.GuaranteeFee,
      PropertyFee: otherMessage?.PropertyFee,
      HouseRent: otherMessage?.HouseRent,
      BreachPenalty: otherMessage?.BreachPenalty,
      ElectricityCharge: otherMessage?.ElectricityCharge,
      WaterCharge: otherMessage?.WaterCharge,
      OtherFee: otherMessage?.OtherFee,
      ReceivableAmount: otherMessage?.ReceivableAmount,
      RefundSupplement: otherMessage?.RefundSupplement,
    })

    console.log('list', list)
    setReqDetailListDetail(list)
    setOtherData({
      ...data.OtherData,
      Dates: `${moment(data.OtherData.PROJECT_STARTDATE).format('YYYY/MM/DD')}-${moment(data.OtherData.PROJECT_ENDDATE).format('YYYY/MM/DD')}`
    })
    // setOtherData({
    //   SPREGIONTYPE_NAME: res?.SpregionType_Name,
    //   SERVERPART_NAME: res?.ServerPart_Name,
    //   SERVERPARTSHOP_NAME: res?.ServerPartShop_Name,
    //   MERCHANTS_NAME: res?.Merchants_Name,
    //   Dates: res?.Dates,
    // })
    setTableLoading(false)
  }
  const exportTable = (e) => {
    e.stopPropagation();                                            // 防止Collapse组件收起
    const main = document.getElementsByClassName(`monthSearch${printIndex}`)[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-saleRankReport');                    // 给table添加id，值与按钮上的table字段对应

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

    setShowLoading(false)

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



  return (
    <div>

      {
        showLoading ?
          <div
            style={{
              width: '100%',
              height: '100%',
              background: 'rgba(0,0,0,0.1)',
              position: 'fixed',
              zIndex: 5,
              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={`monthSearch${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 }} />


      <ProTable
        actionRef={actionRef}
        formRef={formRef}
        columns={columns}
        bordered
        expandable={{
          expandRowByClick: true
        }}
        scroll={{ x: 'max-content', y: 'calc(100vh - 400px)' }}
        pagination={{
          defaultPageSize: 20
        }}
        headerTitle={<PageTitleBox props={props} />}
        search={{ span: 6 }}
        request={async (params) => {
          // if (isFirst) {
          //   setIsFirst(false)
          //   return
          // }
          console.log('params', params);

          setSearchParams(params)
          const req: any = {
            SearchParameter: {
              // stateSelectList   ["2", "0", "1", "2", "3000"]

              PendState: stateSelectList[Number(params?.PendState)] === '3000' ? 1 : stateSelectList[Number(params?.PendState)],
              BusinessProcess_State: params?.PendState === '1' || params?.PendState === '2' ? '' : processState[Number(params?.PendState)],
              // BusinessProcess_State: stateSelectList[Number(params?.PendState)] === '3000' || stateSelectList[Number(params?.PendState)] === '9000' ? stateSelectList[Number(params?.PendState)] : '',
              Operation_Type: params?.Operation_Type === 'all' ? '11,12' : params?.Operation_Type
            },
            keyWord: params.BusinessProcess_Name ? {
              key: "BusinessProcess_Name",
              value: params.BusinessProcess_Name
            } : '',
            // SortStr: "BusinessProcess_StartDate desc",
            pageindex: 1,
            pagesize: 999999
          }
          const data = await handleGetMonthAccountProinst(req)
          console.log('data', data);

          if (data && data.length > 0) {
            data.forEach((item: any) => {
              item.BusinessProcess_States = item.BusinessProcess_State
            })
            setReqDetailList(data)
            return { data, success: true }
          }
          setReqDetailList([])
          return { data: [], success: true }
        }}
        toolbar={{
          actions: [
            <span style={{ visibility: 'hidden' }}>
              <ReactHTMLTableToExcel
                buttonText={'导出excel'}
                ref={downloadBtnRef}
                table="table-to-xls-saleRankReport"
                filename={`结算审批列表`}
                sheet="sheet1"
              />
            </span>,
            <Button
              key="new"
              type="primary"
              onClick={(e) => {
                if (reqDetailList && reqDetailList.length > 0) {
                  setShowLoading(true)
                  setTimeout(() => {
                    setShowExportTable(true)
                    setTimeout(() => {
                      exportTable(e)
                    }, 100)
                  }, 100)
                } else {
                  message.error('暂无数据可导出！')
                }
              }}
            >
              导出excel
            </Button>
          ]
        }}
      />


      <Modal
        title={
          <div
            style={{
              width: '100%',
              cursor: 'move',
            }}
            onMouseOver={() => {
              if (disabled) {
                setDraggleDisabled(false)
              }
            }}
            onMouseOut={() => {
              setDraggleDisabled(true)
            }}
            onFocus={() => { }}
            onBlur={() => { }}
          >
            {currentRow?.BusinessProcess_Name || ''}
          </div>
        }
        open={showDetail}
        width={1550}
        destroyOnClose
        onCancel={() => {
          setShowDetail(false)
          setSearchDetail(false)
          setCurrentRow(undefined)
          setModalTopDetail(undefined)
          editFormRef.current?.resetFields()
        }}
        footer={!searchDetail}
      // modalRender={(modal) => {
      //   return <Draggable
      //     disabled={disabled}
      //     bounds={bounds}
      //     onStart={(event, uiData) => onDraggaleStart(event, uiData)}
      //   >
      //     <div ref={draggleRef}>{modal}</div>
      //   </Draggable>
      // }}
      >
        <div>
          {/* <ProForm
            layout={'horizontal'}
            formRef={editFormRef}
            submitter={false}
            initialValues={modalFormValue}
          >
            <Row gutter={16} className={'formBox'}>
              <Col span={6}>
                <ProFormDigit
                  name={'MobilePayCorrect'}
                  label={'移动支付差额'}
                  readonly
                  fieldProps={{
                    precision: 2,
                  }}
                />
              </Col>
              <Col span={6}>
                <ProFormDigit
                  name={'CashPayCorrect'}
                  label={'现金支付差额'}
                  readonly
                  fieldProps={{
                    precision: 2,
                  }}
                />
              </Col>
            </Row>
          </ProForm> */}
          <ProDescriptions column={4}>
            {/* topDetail */}
            <ProDescriptions.Item label="结算日期">
              {modalTopDetail?.IndexDesc || ''}
              {/* {currentRow?.startTime ? moment(currentRow?.startTime).format('YYYY/MM/DD') : ''}
              {currentRow?.startTime && currentRow?.endTime ? '-' : ''}
              {currentRow?.endTime ? moment(currentRow?.endTime).format('YYYY/MM/DD') : ''} */}
            </ProDescriptions.Item>
            <ProDescriptions.Item label="结算模式">
              {modalTopDetail?.SETTLEMENT_MODES ? SETTLEMENT_MODESObj[modalTopDetail?.SETTLEMENT_MODES] : ''}
              {modalTopDetail?.SWITCH_MODES ? `--->${SETTLEMENT_MODESObj[modalTopDetail?.SWITCH_MODES]}` : ''}
              {
                modalTopDetail?.SWITCH_MODES ?
                  `（${modalTopDetail?.SWITCH_DATE}）` : ''
              }
            </ProDescriptions.Item>
            <ProDescriptions.Item label="项目期数">{modalTopDetail?.IndexStr}</ProDescriptions.Item>
            <ProDescriptions.Item label="装修期">{modalTopDetail?.DecorateStartDate || ''}</ProDescriptions.Item>
          </ProDescriptions>

          <ProDescriptions column={4}>
            <ProDescriptions.Item label="履约保证金"
            >{modalTopDetail?.SECURITYDEPOSIT ? `${getMoney(modalTopDetail?.SECURITYDEPOSIT)}万元` : ''}</ProDescriptions.Item>
            <ProDescriptions.Item label="提成比例">{modalTopDetail?.GUARANTEERATIO ? `${modalTopDetail?.GUARANTEERATIO}%` : '-'}</ProDescriptions.Item>
            <ProDescriptions.Item label="税率">{modalTopDetail?.TaxRate ? `${modalTopDetail?.TaxRate}%` : '-'}</ProDescriptions.Item>
            <ProDescriptions.Item label="期除税收入">{modalTopDetail?.MINTURNOVER ? `${getMoney(modalTopDetail?.MINTURNOVER / 10000)}万元` : ''}</ProDescriptions.Item>
          </ProDescriptions>

          <ProTable
            columns={currentUser?.UserPattern === 2000 ? defaultColumns.slice(0, 4) : defaultColumns}
            bordered
            style={{ background: '#fff', paddingTop: '10px' }}
            search={false}
            options={false}
            pagination={false}
            // loading={tableSecondLoading}
            request={async (params) => {
              // 只拿 结算模式的数据（老的结算模式 变更的结算模式 变更时间）
              const businessReq: any = {
                BUSINESSPROJECT_ID: currentRow?.BUSINESSPROJECT_ID,
                SHOPROYALTY_ID: currentRow?.ShopRoyaltyId
              }

              const businessData = await handleGetTableMonthlyReconciliation(businessReq)
              let businessObj: any = {}
              if (businessData.OtherData) {
                const businessRes: any = businessData.OtherData
                businessObj = {
                  SWITCH_DATE: businessRes.SWITCH_DATE,
                  SWITCH_MODES: businessRes.SWITCH_MODES,
                  SETTLEMENT_MODES: businessRes.SETTLEMENT_MODES
                }
              }

              // 说income是老的 detail是新的

              const incomeReq: any = {
                BusinessProjectId: currentRow?.BUSINESSPROJECT_ID,
                StatisticsMonth: currentRow?.STATISTICS_MONTH ? moment(currentRow?.STATISTICS_MONTH).format('YYYYMM') : '',
                ShopRoyaltyId: currentRow?.ShopRoyaltyId,
                // MobilePayCorrect: currentRow?.MOBILEPAY_CORRECT,
                // CashPayCorrect: currentRow?.CASHPAY_CORRECT
              }
              const recordData = await handleGetProjectPeriodIncome(incomeReq)
              console.log('recordData', recordData);

              let recordItem: any = {}
              if (recordData && recordData.length > 0) {
                recordItem = recordData[0]
                const obj: any = {}
                setModalTopDetail({ ...recordItem, ...businessObj })
                // inCome 是精算后的  bizDetail 是精算前的
                const list: any = [{
                  ...recordItem,
                  type: '结算金额',
                  MobilePay: recordItem?.MOBILEPAY_AMOUNT,
                  CashPay: recordItem?.CASHPAY_AMOUNT
                },
                {
                  ...currentRow,
                  type: '精算金额',
                  IndexDesc: recordItem?.IndexDesc,
                  GUARANTEERATIOAMOUNT: currentRow?.ROYALTY_PRICE,
                  GUARANTEERATIOINCOME: currentRow?.ROYALTY_THEORY,
                  ROYALTYTHEORYMUST: currentRow?.ACCROYALTY_PRICE,
                  ROYALTYTHEORYOK: currentRow?.ACCROYALTY_THEORY,
                  ROYALTYTHEORYMONTHLYMUST: currentRow?.ACCROYALTY_PRICE - currentRow?.ACCROYALTY_THEORY,
                  REVENUEDAILY_AMOUNTTotal: currentRow?.ACCREVENUE_AMOUNT,
                  MobilePay: currentRow?.MOBILEPAY_AMOUNT + currentRow.MOBILEPAY_CORRECT,
                  CashPay: currentRow?.CASHPAY_AMOUNT + currentRow.CASHPAY_CORRECT,
                  CurMonthRevenue: recordItem?.CurMonthRevenue,
                  RevenueTrend: currentRow?.ACCREVENUE_AMOUNT > recordItem.REVENUEDAILY_AMOUNTTotal ? true : currentRow?.ACCREVENUE_AMOUNT < recordItem.REVENUEDAILY_AMOUNTTotal ? false : null,
                  ROYALTYTrend: (getMoney(numeral(currentRow?.ACCROYALTY_PRICE - currentRow?.ACCROYALTY_THEORY).format('0.00'))) > recordItem.ROYALTYTHEORYMONTHLYMUST ? true : (getMoney(numeral(currentRow?.ACCROYALTY_PRICE - currentRow?.ACCROYALTY_THEORY).format('0.00'))) < recordItem.ROYALTYTHEORYMONTHLYMUST ? false : null
                }]
                // }]
                console.log('list', list)
                return { data: list, success: true }
              }

              return { data: [], success: true }
            }}
          // dataSource={firstTableData}
          />

          <MonthSettlement detail={{
            ...currentRow,
            selectMonthDate: currentRow?.STATISTICS_MONTH,
            SERVERPART_ID: currentRow?.Serverpart_ID,
            // SPREGIONTYPE_ID
          }} />

          {/* <ProForm
            formRef={formDescRef}
            submitter={{
              // 清空表单自带的按钮
              render: (props, doms) => {
                return []
              }
            }}
            initialValues={{ desc: currentRow?.BusinessProcess_Desc || '' }}
          >
            <ProFormTextArea
              name="desc"
              label="备注说明"
              readonly
              rules={[
                {
                  required: true,
                  message: '请输入备注说明'
                }
              ]}
            />
          </ProForm> */}

          <ReviewProcess compareCurrent={{ ...currentRow, BusinessApprovalId: currentRow?.BusinessApproval_ID }} showReviewProcess={showDetail} />
        </div>
      </Modal>


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

      <Drawer
        width="80%"
        className="project-drawer"
        visible={showDailyDrawer} // 抽屉弹框是否显示状态
        onClose={() => { // 关闭抽屉 则在清空选中行数据 并 设置抽屉状态为关闭
          setShowDailyDrawer(false);
        }}
        afterOpenChange={async (open: boolean) => {
          if (open) {
            const data = await handleGetBIZPSPLITMONTHDetail({ BIZPSPLITMONTHId: currentRow?.BusinessProcess_ID })
            setCurrentRow({
              ...currentRow,
              ...data,
              RENTFEE: data.MINTURNOVER,
              TaxRate: '',
              MonthlyIncome: '',
              MonthlyCount: '',
              MonthlyTotalIncome: '',
              Id: data.SERVERPARTSHOP_ID,
              STATISTICS_DATE_Start: moment(data.STARTDATE).format('YYYY-MM-DD'),
              startTime: moment(data.STARTDATE).format('YYYY-MM-DD'),
              STATISTICS_DATE_End: moment(data.ENDDATE).format('YYYY-MM-DD'),
              endTime: moment(data.ENDDATE).format('YYYY-MM-DD'),
              SHOPROYALTY_ID: data.SHOPROYALTY_ID,
              ShopRoyaltyId: data.SHOPROYALTY_ID,
              BUSINESSPROJECT_ID: data.BUSINESSPROJECT_ID,
              // SettlementModes: 3000,
              Approvalstate: data.Approvalstate,
              BusinessApprovalId: currentRow?.BusinessApproval_ID,
              SETTLEMENT_MODES: data.SettlementModes
            })
          }
        }}
        destroyOnClose
        bodyStyle={{ backgroundColor: "#f9f9f9", padding: 16 }}
        closable={false}
      >
        {/* compareCurrent */}
        {showDailyDrawer && currentRow?.BUSINESSPROJECT_ID ? <RevenueList BusinessProjectId={currentRow?.BUSINESSPROJECT_ID} propsBP={currentRow}
          propsRC={currentRow}
          isShowDetail={showDailyDrawer}
          ShopRoyaltyId={currentRow?.ShopRoyaltyId ? currentRow?.ShopRoyaltyId : 0}
          ShopIds={currentRow?.SERVERPARTSHOP_ID ? currentRow?.SERVERPARTSHOP_ID : ''}
          StartDate={moment(currentRow?.startTime).format('YYYY-MM-DD')}
          type={'monthSettlement'}
          EndDate={moment(currentRow?.endTime).format('YYYY-MM-DD')}></RevenueList> : <LoadingBox />}
      </Drawer>


      {/* 年度的业务名称点进来的 */}
      <Drawer
        width="80%"
        zIndex={20}
        visible={showDeatilDrawer} // 抽屉弹框是否显示状态
        onClose={() => { // 关闭抽屉 则在清空选中行数据 并 设置抽屉状态为关闭
          setCurrentRow(undefined);
          setShowDetailDrawer(false);
          setOtherData(undefined)
          setProgressState(0)
          setProgressList([])
        }}
        destroyOnClose
        bodyStyle={{ backgroundColor: "#fff", padding: 0 }}
        closable={false}
      >
        <PageContainer
          loading={detailLoading}
          header={{
            title: currentRow?.BusinessProcess_Name,
            breadcrumb: {},
          }}
          content={
            <>
              <ProjectDetailDrawer id={currentRow?.BusinessProcess_ID} shopName={currentRow?.SERVERPARTSHOP_NAME ? currentRow?.SERVERPARTSHOP_NAME.split(',')[0] : ''} />
            </>
          }
        >

          <ReviewProcess compareCurrent={{ ...currentRow, BusinessApprovalId: currentRow?.BusinessApproval_ID }} showReviewProcess={showDeatilDrawer} />


          {
            reqDetailListDetail && reqDetailListDetail.length > 0 ?
              <ProTable
                rowKey={(record) => {
                  return `${record?.ShopRoyalty_Id}-${record?.PeriodIndexStr}-${record?.StartDate}-${record?.EndDate}-${record?.level}`
                }}
                actionRef={actionDetailRef}
                formRef={formDetailRef}
                columns={detailColumns}
                bordered
                search={false}
                className={'detailTable'}
                loading={tableLoading}
                request={async (params: any) => {
                  if (currentRow?.SETTLEMENT_TYPE === 2) {
                    handleGetTableData()
                  }
                }}
                expandable={{
                  // expandedRowKeys: expandAllRow,
                  defaultExpandAllRows: true
                  // defaultExpandedRowKeys: expandAllRow
                }}
                scroll={{ x: 'max-content' }}
                headerTitle={`合作商户合同期结算明细表`} // 列表表头
                dataSource={reqDetailListDetail}
                pagination={false}
                columnsState={{
                  value: recordColumnsStateMap,
                  onChange: setRecordColumnsStateMap,
                }}

              >
              </ProTable> : <LoadingBox />
          }
        </PageContainer>
      </Drawer>


      {/* 跳转到审批的内容 */}
      {
        currentType === '11' ?
          <YearExamineProcess onShow={showExamineDetail} setOnShow={setShowExamineDetail} parentRow={currentRow} setParentRow={setCurrentRow}
            setCurrentApprovalstate={setCurrentApprovalstate} currentApprovalstate={currentApprovalstate} actionRef={actionRef} isYear={true} /> :
          currentType === '12' ?
            <MonthExamineProcess onShow={showExamineDetail} setOnShow={setShowExamineDetail} parentRow={currentRow} setParentRow={setCurrentRow}
              setCurrentApprovalstate={setCurrentApprovalstate} actionRef={actionRef} currentApprovalstate={currentApprovalstate} monthTime={monthTime}
              setMonthTime={setMonthTime} />
            // <Drawer
            //   width="80%"
            //   visible={showExamineDetail} // 抽屉弹框是否显示状态
            //   onClose={() => { // 关闭抽屉 则在清空选中行数据 并 设置抽屉状态为关闭
            //     setShowExamineDetail(false)
            //     setCurrentState(undefined)
            //     setCurrentType('0')
            //     setCurrentRow(undefined)
            //   }}
            //   destroyOnClose
            //   bodyStyle={{ backgroundColor: "#fff", padding: 0 }}
            //   closable={false}
            // >
            //   <CompareList compareCurrent={currentRow} setShowCompareDrawer={setShowExamineDetail} handleGetNewMonth={handleGetNewMonth}
            //     fatherActionRef={actionRef} monthTime={monthTime} showTopTable={true} />
            // </Drawer>
            : ''
      }
    </div>
  )
}

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