// 区域销售环比分析
import { connect } from "umi";
import type { CurrentUser } from "umi";
import type { ConnectState } from "@/models/connect";
import React, { useRef, useState } from "react";
import ProCard from "@ant-design/pro-card";
import { MenuFoldOutlined } from "@ant-design/icons";
import type { FormInstance } from "antd";
import { Button, Drawer } from "antd";
import { message, Space, Tree } from "antd";
import useRequest from "@ahooksjs/use-request";
import { getFieldEnum, getServerpartTree, handleCallLogs } from "@/services/options";
import type { ActionType } from "@ant-design/pro-table";
import ProTable from "@ant-design/pro-table";
import { handleGetExamineList } from "@/pages/examine/examineList/service";
import moment from "moment";
import ReactHTMLTableToExcel from "react-html-table-to-excel";
import search from "@/pages/BussinessProject/search";
import { handleGetGetRevenueQOQ, handleGetRevenueQOQByDate, handleGetRevenueYOYQOQByDate } from "./service";
import session from "@/utils/session";
import { handleGetShopShortNamesGet } from "../transactionAnalysis/service";
import { handleGetGetRevenueYOYQOQByDate } from "@/pages/reports/BusinessAnalysis/revenueYOYQOQReport/service";
import PageTitleBox from "@/components/PageTitleBox";
import { exportXlsxFromProColumnsExcelJS } from "@/utils/exportExcelFun";
import { formatTreeData } from "@/utils/format";


const revenueQOQReport: React.FC<{ currentUser: CurrentUser }> = (props) => {
  const { currentUser } = props
  const downloadBtnRef = useRef<any>()

  const actionRef = useRef<ActionType>();
  const actionByDateRef = useRef<ActionType>();
  const formRef = useRef<FormInstance>();
  const formByDateRef = useRef<FormInstance>();
  const [reqDetailList, setReqDetailList] = useState<any>(); // 合计项数据源
  const [printOut, setPrintOut] = useState<any>(); // 打印数据的内容
  const [collapsible, setCollapsible] = useState<boolean>(false)
  const [treeView, setTreeView] = useState<any>()
  const [printIndex, setPrintIndex] = useState<number>(new Date().getTime())

  // 加载服务区树
  const { loading: treeLoading, data: treeViews } = useRequest(async () => {
    const data = await getServerpartTree(currentUser?.ProvinceCode, currentUser?.CityAuthority, true, true, true)
    setTreeView(data)
    return data
  })
  // 导出的加载效果
  const [showLoading, setShowLoading] = useState<boolean>(false)
  // 是否显示打印的表格
  const [showExportTable, setShowExportTable] = useState<boolean>(false)
  // 树相关的属性和方法
  const [selectedId, setSelectedId] = useState<string>()
  // 第一次进来默认的表格方法不调用
  const [isFirst, setIsFirst] = useState<boolean>(true)
  // 搜索的条件
  const [searchParams, setSearchParams] = useState<any>()

  const businessTypeObj = session.get("BUSINESSTYPEObj")
  const [columnsStateMap, setColumnsStateMap] = useState<any>({
    // Business_Type:{show:false},
    ShopTrade: { show: false }
  })
  // 展示自营业态
  const [showSelfBusiness, setShowSelfBusiness] = useState<boolean>(true)
  // 自营业态的选择列表
  const [shopNamesList, setShopNamesList] = useState<any>()
  // 显示每日流水抽屉
  const [showDailyDrawer, setShowDailyDrawer] = useState<boolean>(false)
  const [currentRow, setCurrentRow] = useState<any>()
  const [columnsDailyStateMap, setColumnsDailyStateMap] = useState<any>({
    MERCHANTS_NAME: { show: false },
    ShopTrade: { show: false },
    BUSINESS_TYPE: { show: false }
  })
  const SHOPTRADEObj = session.get('SHOPTRADEObj')

  const columns: any = [
    // {
    //   title: '序号',
    //   dataIndex: 'index',
    //   hideInSearch: true,
    //   width: 140,
    // },
    {
      title: '服务区名称',
      width: 250,
      dataIndex: 'Name',
      align: 'center',
      ellipsis: true,
      hideInSearch: true,
      render: (_, record) => {
        return showDailyDrawer ? record?.Name : <a onClick={() => {
          console.log('record', record)
          if (moment(searchParams?.StartDate).format('YYYY-MM-DD') !== moment(searchParams?.EndDate).format('YYYY-MM-DD')) {
            if (record?.Name === '合计') {
              let id: 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 (id) {
                        id += `,${subItem.Id}`
                      } else {
                        id = subItem.Id
                      }
                    })
                  }
                })
              }
              console.log('id', id)
              setCurrentRow({
                ...record,
                Id: id,
                SERVERPART_ID: id,
              })

            } else if (record?.Name && record?.Name.indexOf('管理中心') !== -1) {
              let id: string = ''
              if (record?.children && record?.children.length > 0) {
                record?.children.forEach((item: any) => {
                  if (id) {
                    id += `,${item.Id}`
                  } else {
                    id = item.Id
                  }
                })
              }
              setCurrentRow({
                ...record,
                Id: id,
                SERVERPART_ID: id
              })
              console.log('id', id)
            }
            else {
              setCurrentRow(record)
            }
            setShowDailyDrawer(true)
          }
        }}>
          {record?.Name}
        </a>
      }
    },
    {
      title: '经营商户',
      width: 120,
      ellipsis: true,
      align: 'center',
      dataIndex: 'MERCHANTS_NAME',
      hideInSearch: true,
    },
    {
      title: '本期统计时间',
      dataIndex: 'search_date',
      valueType: 'dateRange',
      hideInTable: true,
      hideInDescriptions: true,
      initialValue: [moment().subtract(1, 'months'), moment().add(-1, 'day')],
      search: {
        transform: (value) => {
          return {
            StartDate: value[0],
            EndDate: value[1],
          };
        },
      },
      fieldProps: {
        disabledDate: (current: any) => current && current > moment().endOf('day')
      }
    },
    {
      title: '上期统计时间',
      dataIndex: 'search_periodDate',
      valueType: 'dateRange',
      hideInTable: true,
      hideInDescriptions: true,
      initialValue: [moment().subtract(2, 'months'), moment().subtract(1, 'months').add(-1, 'day')],
      search: {
        transform: (value) => {
          return {
            periodStartDate: value[0],
            periodEndDate: value[1],
          };
        },
      },
      fieldProps: {
        disabledDate: (current: any) => current && current > moment().endOf('day')
      }
    },
    {
      dataIndex: 'ShowShop',
      title: '统计类型',
      valueType: "radioButton",
      fixed: true,
      initialValue: '1',
      valueEnum: {
        1: '门店',
        0: '服务区'
      },
      hideInTable: true,
      fieldProps: {
        onChange: (event: any) => {
          formRef.current?.submit()
        },
        labelCol: { span: 0 },
        wrapperCol: { span: 24 }
      },
    },
    {
      title: '分析类型',
      valueType: 'select',
      hideInTable: true,
      align: 'center',
      dataIndex: 'SELECTTYPE',
      valueEnum: {
        1: "实收金额",
        2: "销售数量",
        3: "客单数量"
      },
      initialValue: '1',
      // request: async () => {
      //   return await getFieldEnum({ FieldExplainField: 'ANALYSISINS_TYPE', sessionName: 'ANALYSISINS_TYPE' });
      // },
      ellipsis: true
    },
    {
      title: '经营模式',
      width: 150,
      // hideInTable: true,
      dataIndex: 'BUSINESS_TYPE',
      valueType: 'select',
      align: 'center',
      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: {
        multiple: true,
        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: "请输入商户/品牌/门店/服务区"
      }
    },
    {
      dataIndex: 'ShopTrade',
      title: '商品业态',
      align: 'center',
      width: 120,
      valueType: 'select',
      valueEnum: SHOPTRADEObj,
      hideInSearch: true,
      // request: async () => {
      //   // 这里要手动添加枚举字段（从下面这些字典中选择一个）：商品业态[BUSINESSTYPE]
      //   const options = await getFieldEnum({ FieldExplainField: 'BUSINESSTYPE' });
      //   return options;
      // },
    },
    {
      title: '合计',
      dataIndex: 'CASHPAYSUM',
      hideInSearch: true,
      children: [
        {
          title: <div style={{ textAlign: 'center' }}>本期实收金额</div>,
          width: 120,
          dataIndex: 'CASHPAY_TotalA',
          hideInSearch: true,
          align: 'right',
          ellipsis: true,
          valueType: 'digit'
        },
        {
          title: <div style={{ textAlign: 'center' }}>上期实收金额</div>,
          width: 120,
          dataIndex: 'CASHPAY_TotalB',
          hideInSearch: true,
          align: 'right',
          ellipsis: true,
          valueType: 'digit'
        },
        {
          title: <div style={{ textAlign: 'center' }}>环比/同比</div>,
          width: 120,
          dataIndex: 'MOMTOTAL',
          align: 'right',
          ellipsis: true,
          hideInSearch: true,
          render: (_, record) => {
            return record?.MOMTOTAL ? `${record?.MOMTOTAL}%` : '-'
          }
        },
      ]
    },
    {
      title: '东(南)区',
      dataIndex: 'CASHPAYA',
      align: 'center',
      hideInSearch: true,
      children: [
        {
          title: <div style={{ textAlign: 'center' }}>本期实收金额</div>,
          width: 120,
          dataIndex: 'CASHPAY_A',
          align: 'right',
          valueType: 'digit',
          hideInSearch: true
        },
        {
          title: <div style={{ textAlign: 'center' }}>上期实收金额</div>,
          width: 120,
          dataIndex: 'CASHPAY_C',
          align: 'right',
          valueType: 'digit',
          hideInSearch: true
        },
        {
          title: <div style={{ textAlign: 'center' }}>环比/同比</div>,
          width: 120,
          dataIndex: 'MOM_A',
          align: 'right',
          hideInSearch: true,
          render: (_, record) => {
            return record?.MOM_A ? `${record?.MOM_A}%` : '-'
          }
        },
      ]
    },
    {
      title: '西(北)区',
      dataIndex: 'CASHPAYB',
      hideInSearch: true,
      children: [
        {
          title: <div style={{ textAlign: 'center' }}>本期总实收金额</div>,
          width: 120,
          dataIndex: 'CASHPAY_B',
          align: 'right',
          valueType: 'digit',
          hideInSearch: true
        },
        {
          title: <div style={{ textAlign: 'center' }}>上期总实收金额</div>,
          width: 120,
          dataIndex: 'CASHPAY_D',
          align: 'right',
          valueType: 'digit',
          hideInSearch: true
        },
        {
          title: <div style={{ textAlign: 'center' }}>环比/同比</div>,
          width: 120,
          dataIndex: 'MOM_B',
          hideInSearch: true,
          align: 'right',
          render: (_, record) => {
            return record?.MOM_B ? `${record?.MOM_B}%` : '-'
          }
        }
      ]
    },
  ]
  //   导出excel方法
  const exportTable = (e) => {
    e.stopPropagation();                                            // 防止Collapse组件收起
    const main = document.getElementsByClassName(`revenueQOQReportHideBox${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-revenueQOQReport');                    // 给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?.USER_PROVINCE,
      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 (
    <div ref={(el) => {
      // 打印报表
      if (!reqDetailList || reqDetailList.length === 0) return;
      setPrintOut(el);
    }}>

      <div className={`revenueQOQReportHideBox${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
          style={{ width: !collapsible ? "300px" : "60px" }}
          className="pageTable-leftnav"
          bodyStyle={{ padding: 0, paddingTop: 20, paddingLeft: 20, width: !collapsible ? "300px" : "60px" }}
          extra={<MenuFoldOutlined onClick={() => {
            setCollapsible(!collapsible)
          }} />}
          colSpan={!collapsible ? "300px" : "60px"}
          title={!collapsible ? "请选择服务区" : ""}
          headerBordered
          collapsed={collapsible}
        >
          {treeView && treeView.length > 0 ? <Tree
            checkable
            treeData={[{
              label: '全部',
              value: 0,
              key: '0-0',
              children: treeView
            }]}
            fieldNames={{
              title: "label",
              key: "key"
            }}
            blockNode
            defaultExpandedKeys={['0-0']}
            onCheck={(checkedKeys: React.Key[] | any, info) => {
              const selectedIds = info.checkedNodes.filter(n => n?.type === 1)
              setSelectedId(selectedIds.map(n => n?.value)?.toString() || '')
              handleGetShopNamesList(selectedIds.map(n => n?.value)?.toString() || '')
              // actionRef?.current?.reload()
              // getData(selectedIds.map(n => n?.value)?.toString() || '')
            }}
          // switcherIcon={<PlusOutlined />}
          /> : ''}
        </ProCard>
        <div style={{
          width: !collapsible ? 'calc(100% - 300px)' : 'calc(100% - 60px)',
          paddingTop: 0,
          paddingBottom: 0,
          paddingRight: 0
        }}>
          <ProTable
            actionRef={actionRef}
            formRef={formRef}
            rowKey={(record) => {
              return `${record?.index}-${record?.Id}-${record?.Name}-${record?.SERVERPART_ID}`
            }}
            columns={columns}
            bordered
            search={{ span: 6, labelWidth: 95, defaultCollapsed: false, }}
            scroll={{ x: '100%', y: 'calc(100vh - 470px)' }}
            pagination={false}
            headerTitle={<PageTitleBox props={props} />}
            request={async (params) => {
              if (isFirst) {
                setIsFirst(false)
                return
              }
              if (!selectedId) {
                message.error('请选择服务区')
                return
              }
              console.log('params', params)
              setSearchParams(params)
              const req = {
                ...params,
                ServerpartIds: selectedId || '',
                startDate: params?.StartDate, // 本期
                endDate: params?.EndDate,// 本期
                MOMstartDate: params?.periodStartDate,// 上期
                MOMendDate: params?.periodEndDate,// 上期
                ShowShop: params?.ShowShop === '1',
                targetSystem: params.targetSystem || '',
                shopNames: params.shopNames || '',
                SearchKeyName: "MerchantName,Brand,Shop,Serverpart"
              }
              handleCallLogs()
              console.log('req', req)
              const data = await handleGetGetRevenueQOQ(req)
              console.log('data', data)
              let list: any = []
              if (data && data.length > 0) {
                list = JSON.parse(JSON.stringify(data))
                // 处理index
                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 = subIndex + 1
                      if (subItem.children && subItem.children.length > 0) {
                        subItem.children.forEach((thirdItem: any, thirdIndex: number) => {
                          thirdItem.index = thirdIndex + 1
                        })
                      }
                    })
                  }
                })
              }
              console.log('list', list)

              let fieldData: any = [
                "CASHPAY_TotalA",
                "CASHPAY_TotalB",
                "CASHPAY_A",
                "CASHPAY_C",
                "CASHPAY_B",
                "CASHPAY_D",
              ]

              let enumList: any = ["BUSINESS_TYPE", "ShopTrade"]
              let newPrintData: any = formatTreeData(JSON.parse(JSON.stringify(list)), fieldData, enumList, [shopNamesList, SHOPTRADEObj], ["MOMTOTAL", "MOM_A", "MOM_B"])


              setReqDetailList(newPrintData)
              return { data: list, success: true }
            }}
            toolbar={{
              actions: [
                // <span style={{ visibility: 'hidden' }}>
                //   <ReactHTMLTableToExcel
                //     buttonText={'导出excel'}
                //     ref={downloadBtnRef}
                //     table="table-to-xls-revenueQOQReport"
                //     filename={`销售同/环比分析表_${searchParams?.StartDate}-${searchParams?.EndDate}`}
                //     sheet="sheet1"
                //   />
                // </span>,
                <Button
                  key="new"
                  type="primary"
                  onClick={(e) => {
                    if (reqDetailList && reqDetailList.length > 0) {
                      // 尝试一下 导出新方法 
                      exportXlsxFromProColumnsExcelJS(columns,
                        reqDetailList,
                        `销售同/环比分析表_${searchParams?.StartDate}-${searchParams?.EndDate}`,
                        {
                          footerMaker: currentUser?.Name,
                          footerMakerTime: moment().format('YYYY-MM-DD HH:mm:ss'),
                          footerStatsTime: `${searchParams?.StartDate}-${searchParams?.EndDate}`
                        }
                      )
                    } else {
                      message.error('暂无数据可导出！')
                    }


                    // if (reqDetailList && reqDetailList.length > 0) {
                    //   setShowLoading(true)
                    //   setTimeout(() => {
                    //     setShowExportTable(true)
                    //     setTimeout(() => {
                    //       exportTable(e)
                    //     }, 100)
                    //   }, 100)
                    // } else {
                    //   message.error('暂无数据可导出！')
                    // }
                  }}
                >
                  导出excel
                </Button>
              ]
            }}
            columnsState={{
              value: columnsStateMap,
              onChange: setColumnsStateMap,
            }}
          />
        </div>
      </div>

      <Drawer
        width="80%"
        visible={showDailyDrawer}
        onClose={() => {
          setCurrentRow(undefined);
          setShowDailyDrawer(false);
        }}
        bodyStyle={{ backgroundColor: "#f9f9f9", padding: 16 }}
        destroyOnClose
        closable={false}
      >
        <div style={{ width: '100%' }}>
          <ProTable
            actionRef={actionByDateRef}
            formRef={formByDateRef}
            rowKey={(record) => {
              return `${record?.index}-${record?.Id}-${record?.Name}-${record?.SERVERPART_ID}`
            }}
            columns={columns}
            bordered
            search={false}
            options={false}
            pagination={false}
            headerTitle={currentRow?.Name === '合计' ? '合计' : `${currentRow?.SPREGIONTYPE_NAME}${currentRow?.SERVERPART_NAME ? `-${currentRow?.SERVERPART_NAME}` : ''}${currentRow?.SHOPNAME ? `-${currentRow?.SHOPNAME}` : ''}`}
            scroll={{ x: '100%', y: 'calc(100vh - 230px)' }}
            columnsState={{
              value: columnsDailyStateMap,
              onChange: setColumnsDailyStateMap,
            }}
            request={async (params) => {
              console.log('currentRow', currentRow)
              const req = {
                ServerpartIds: currentRow?.SERVERPART_ID ? currentRow?.SERVERPART_ID : '',
                ServerpartShopId: currentRow?.SERVERPARTSHOP_ID ? currentRow?.SERVERPARTSHOP_ID : '',
                startDate: searchParams?.StartDate,
                endDate: searchParams?.EndDate,
                MOMstartDate: searchParams?.periodStartDate || '',
                MOMendDate: searchParams?.periodEndDate || '',
                SELECTTYPE: searchParams?.SELECTTYPE || '',
                shopTrade: searchParams?.ShopTrade || '',
                businessType: searchParams?.BUSINESS_TYPE || '',
                targetSystem: searchParams?.targetSystem || '',
              }
              const data = await handleGetRevenueQOQByDate(req)
              if (data && data.length > 0) {
                console.log('data', data)
                data.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 = subIndex + 1
                    })
                  }
                })
                return { data, success: true }
              }
              return { data: [], success: true }
            }}
          />
        </div>
      </Drawer>
    </div>
  )
}

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