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 { Avatar, Button, Menu, message, Space, Spin, Tree } from "antd";
import useRequest from "@ahooksjs/use-request";
import { getServerpartTree, handleCallLogs, handleGetCashierStatus } from "@/services/options";
import type { ActionType } from "@ant-design/pro-table";
import ProTable from "@ant-design/pro-table";
import ReactHTMLTableToExcel from "react-html-table-to-excel";
import SubMenu from "antd/lib/menu/SubMenu";
import { handleGetStateFeedBackList } from "@/pages/reports/audit/curVerify/service";
import moment from "moment";
import * as numeral from "numeral";
import ProDescriptions from "@ant-design/pro-descriptions";
import PageTitleBox from "@/components/PageTitleBox";
import { exportXlsxFromProColumnsExcelJS } from "@/utils/exportExcelFun";


const curVerify: React.FC<{ currentUser: CurrentUser }> = (props) => {
  const { currentUser } = props
  const downloadBtnRef = useRef<any>()
  const actionRef = useRef<ActionType>();
  const formRef = useRef<FormInstance>();
  const [reqDetailList, setReqDetailList] = useState<any>(); // 合计项数据源
  const [printOut, setPrintOut] = useState<any>(); // 打印数据的内容
  const [collapsible, setCollapsible] = useState<boolean>(false)
  const [treeView, setTreeView] = useState<any>()
  // 加载服务区树
  const { loading: treeLoading, data: treeViews } = useRequest(async () => {
    const data = await getServerpartTree(currentUser?.ProvinceCode, currentUser?.CityAuthority, true, true, true)
    setTreeView(data)
    return data
  })
  // 树相关的属性和方法
  const [selectedId, setSelectedId] = useState<string>()
  // 导出的加载效果
  const [showLoading, setShowLoading] = useState<boolean>(false)
  // 是否显示打印的表格
  const [showExportTable, setShowExportTable] = useState<boolean>(false)
  const [currenMenu, setCurrenMenu] = useState<any>(); // 当前选中左侧菜单的服务区节点
  const columns: any = [
    {
      title: '统计时间',
      dataIndex: 'search_date',
      valueType: 'dateRange',
      hideInTable: true,
      hideInDescriptions: true,
      colSize: 1,
      initialValue: [moment().format('YYYY-MM-DD'), moment().format('YYYY-MM-DD')],
      search: {
        transform: (value) => {
          return {
            StartDate: value[0],
            EndDate: value[1],
          };
        },
      },
      fieldProps: {
        disabledDate: (current: any) => current && current > moment()
      }
    },
    {
      title: '序号',
      width: 80,
      dataIndex: 'index',
      hideInSearch: true,
      valueType: 'index',
      align: 'center'
    },
    {
      title: '门店',
      width: 150,
      hideInSearch: true,
      dataIndex: 'ServerpartShop_Name',
      align: 'center'
    },
    {
      title: '收银状态',
      width: 120,
      align: 'center',
      dataIndex: 'status',
      hideInSearch: true,
      render: (_, record) => {
        return record?.Connect_Date ? handleGetCashierStatus(record?.Connect_Date, 10) ? <span style={{ color: '#00bfff' }}>{'收银状态正常'}</span> :
          <span style={{ color: '#c71585' }}>{'网络未连接'}</span> : '-'
      }
      // render:(_,record)=>{
      //    return new Date(moment(record?.Connect_Date).format('YYYY-MM-DD HH:mm:ss')).getTime()>new Date().getTime() || new Date(moment(record?.Connect_Date).format('YYYY-MM-DD HH:mm:ss')).getTime() + 5*60*1000 > new Date().getTime()?
      //      <span style={{color:'#00bfff'}}>{'收银状态正常'}</span>:<span style={{color:'#c71585'}}>{'网络未连接'}</span>
      // }
    },
    {
      title: '心跳时间',
      width: 200,
      dataIndex: 'Connect_Date',
      align: 'center',
      hideInSearch: true,
      sorter: (a, b) => new Date(a.Connect_Date).getTime() - new Date(b.Connect_Date).getTime(),
      defaultSortOrder: 'descend',
      render: (_, record) => {
        return record?.Connect_Date ? moment(record?.Connect_Date).format('YYYY-MM-DD HH:mm:ss') : '-'
      }
    },
    {
      title: '系统/在售商品',
      width: 150,
      align: 'center',
      dataIndex: 'PassCommCount/Current_GoodsCount',
      hideInSearch: true,
      render: (_, record) => {
        return `${record?.PassCommCount || '0'}/${record?.Current_GoodsCount || '0'}`
      }
    },
    {
      title: <div style={{ textAlign: 'center' }}>对客营收</div>,
      width: 120,
      valueType: 'digit',
      align: 'right',
      dataIndex: 'Current_SellAmount',
      hideInSearch: true,
    },
    {
      title: <div style={{ textAlign: 'center' }}>客单数量</div>,
      width: 120,
      dataIndex: 'Current_TicketCount',
      valueType: 'digit',
      align: 'right',
      hideInSearch: true,
    },
    {
      title: <div style={{ textAlign: 'center' }}>客单均价</div>,
      width: 120,
      hideInSearch: true,
      valueType: 'digit',
      align: 'right',
      dataIndex: 'averagePrice',
      render: (_, record) => {
        return record?.Current_TicketCount && record?.Current_SellAmount ? `${numeral(record?.Current_SellAmount / record?.Current_TicketCount).format('0,0.00')}` : '0'
      }
    },
    {
      title: <div style={{ textAlign: 'center' }}>今日营收</div>,
      width: 120,
      hideInSearch: true,
      valueType: 'digit',
      align: 'right',
      dataIndex: 'Current_SellAmount',
    },
    {
      title: '在售人员',
      width: 180,
      dataIndex: 'Current_Person',
      hideInSearch: true,
      align: 'center',
      ellipsis: true,
    },
    {
      title: '收银机名称',
      width: 150,
      hideInSearch: true,
      align: 'center',
      dataIndex: 'MachineCode',
      render: (_, record) => {
        return record?.MachineCode ? `POS${record?.MachineCode}` : '-'
      }
    },
    {
      title: '机器号',
      width: 120,
      align: 'center',
      hideInSearch: true,
      dataIndex: 'MachineCode',
    },
    {
      title: 'IP地址',
      width: 120,
      align: 'center',
      hideInSearch: true,
      dataIndex: 'Connect_IP',
    },
    {
      title: '最近销售信息',
      width: 160,
      align: 'center',
      hideInSearch: true,
      dataIndex: 'Sell_Content',
    },
    {
      title: '收银机版本号',
      width: 160,
      align: 'center',
      hideInSearch: true,
      dataIndex: 'Version_Num',
    },
    {
      title: '销售商品版本号',
      width: 180,
      align: 'center',
      hideInSearch: true,
      dataIndex: '',
    },
    {
      title: '促销商品版本号',
      width: 180,
      align: 'center',
      hideInSearch: true,
      dataIndex: '',
    }
  ]

  const exportTable = (e) => {
    e.stopPropagation();                                            // 防止Collapse组件收起
    const main = document.getElementsByClassName('curVerifyHideBox')[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-curVerify');                    // 给table添加id，值与按钮上的table字段对应

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

    setShowLoading(false)

    downloadBtnRef.current.handleDownload();
    setShowExportTable(false)
    tempTable.remove() // 防止重复打印一个内容
  }
  // 查询的条件
  const [searchParams, setSearchParams] = useState<any>()

  const getMenuDom = (data: any[], callback: (item: any) => void) => {
    return (data.map((element: any) => {
      // 绑定嵌套树的子节点
      if (element.children && element.children.length > 0) {
        return (
          <SubMenu title={<span>{element.label}</span>}
            icon={element.ico ? <Avatar src={element.ico} size={16} style={{ marginRight: 4 }} shape="square" /> : null}
            key={`${element.key || element.value}`}
            onTitleClick={(item) => {
              // 选中一级菜单
              if (!currenMenu || item.key !== `${currenMenu?.key}`) {
                callback.call(callback, item)
              }
              item.domEvent.stopPropagation();
            }}
          >
            {element.children && element.children.length > 0 && getMenuDom(element.children, callback)}
          </SubMenu>
        )
      }
      return (<Menu.Item icon={element.ico ? <Avatar src={element.ico} size={16} shape="square" /> : null}
        key={`${element.key || element.value}`}>{element.desc && element.desc !== '0/0' ? <><span>{element.label}</span>
          <span style={{ position: 'absolute', right: '10', top: '9px', lineHeight: '20px', padding: '2px 3px' }}>
            [<span style={{ color: 'red' }}>{element.desc.split('/')[0]}</span>/<span style={{ color: '#1890ff' }}>{element.desc.split('/')[1]}</span>]</span></> : element.label}</Menu.Item>)
    }))
  }

  const loadSelectedId = (item?: any) => {
    console.log('item', item)
    // 选中的子菜单key
    const [type, value] = item.key.split('-')
    if (type === '1') {
      setCurrenMenu(value)
      actionRef?.current?.reload()
    } else {
      setCurrenMenu('')
    }
  }

  return (
    <div ref={(el) => {
      // 打印报表
      if (!reqDetailList || reqDetailList.length === 0) return;
      setPrintOut(el);
    }} >

      {
        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={'curVerifyHideBox'} 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}
        >
          {!treeLoading && <Menu
            mode="inline"
            style={{ height: 'calc(100vh - 220px)', overflowY: 'auto', overflowX: 'hidden' }}
            selectedKeys={`1-${currenMenu}`}
            onSelect={(item) => {
              console.log('item', item)
              loadSelectedId(item)
            }}
          >
            {getMenuDom(treeViews, loadSelectedId)}
          </Menu>}
        </ProCard>
        <div style={{
          width: !collapsible ? 'calc(100% - 300px)' : 'calc(100% - 60px)',
          paddingTop: 0,
          paddingBottom: 0,
          paddingRight: 0
        }}>
          <ProTable
            actionRef={actionRef}
            formRef={formRef}
            columns={columns}
            bordered
            headerTitle={<PageTitleBox props={props} />}
            search={{ span: 6 }}
            scroll={{ x: 2000 }}
            request={async (params) => {
              if (!currenMenu) {
                return
              }
              const req = {
                ...params,
                provinceCode: currentUser?.ProvinceCode || '734100',
                ServerpartIds: currenMenu
              }
              handleCallLogs()
              setSearchParams(params)
              const data = await handleGetStateFeedBackList(req)
              console.log('data', data)
              if (data && data.length > 0) {
                setReqDetailList(data)
                return { data, success: true }
              }
              return { data: [], success: true }
            }}
            toolbar={{
              actions: [
                <span style={{ visibility: 'hidden' }}>
                  <ReactHTMLTableToExcel
                    buttonText={'导出excel'}
                    ref={downloadBtnRef}
                    table="table-to-xls-curVerify"
                    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('暂无数据可导出！')
                    }
                  }}
                >
                  导出excel
                </Button>
              ]
            }}

          />
        </div>
      </div>
    </div>
  )
}

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