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, message, Space, Spin, Tree } from "antd";
import useRequest from "@ahooksjs/use-request";
import { getServerpartTree } 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 LeftSelectTree from "@/pages/reports/settlementAccount/component/leftSelectTree";
import { handleGetOPERATELOGList } from "./service";
import moment from 'moment'


const saleRankReport: 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 [printIndex, setPrintIndex] = useState<number>(new Date().getTime())


    // 树相关的属性和方法
    const [selectedId, setSelectedId] = useState<string>()
    // 导出的加载效果
    const [showLoading, setShowLoading] = useState<boolean>(false)
    // 是否显示打印的表格
    const [showExportTable, setShowExportTable] = useState<boolean>(false)
    // 查询的条件
    const [searchParams, setSearchParams] = useState<any>()

    const columns: any = [
        {
            title: '查询内容',
            width: 120,
            ellipsis: true,
            dataIndex: 'searchValue',
            hideInTable: true,
        },
        {
            title: '查询日期',
            width: 160,
            valueType: 'date',
            hideInTable: true,
            dataIndex: 'searchDate',
            initialValue: moment(),
        },
        {
            title: '访问编码',
            width: 120,
            ellipsis: true,
            hideInSearch: true,
            dataIndex: 'OPERATELOG_ID'
        },
        {
            dataIndex: 'USER_PASSPORT',
            title: '登录账号',
            width: 200,
            ellipsis: true,
            align: 'center',
            hideInSearch: true,
        },
        {
            dataIndex: 'USER_LOGINIP',
            title: '登录地址',
            ellipsis: true,
            width: 160,
            align: 'center',
            hideInSearch: true,
        },
        {
            dataIndex: 'USER_LOGINPLACE',
            title: '登录地点',
            ellipsis: true,
            width: 160,
            align: 'center',
            hideInSearch: true,
        },
        {
            dataIndex: 'BROWSER_VERSION',
            title: '浏览器版本',
            width: 140,
            ellipsis: true,
            align: 'center',
            hideInSearch: true,
        },
        {
            dataIndex: 'OPERATING_SYSTEM',
            title: '操作系统',
            width: 120,
            align: 'center',
            hideInSearch: true,
        },
        {
            dataIndex: 'OPERATELOG_TYPE',
            title: '登录状态',
            width: 120,
            align: 'center',
            valueType: 'select',
            valueEnum: {
                1000: { text: '成功', status: 'Processing' },
                1001: { text: '失败', status: 'Default' },
            }
        },
        {
            dataIndex: 'OPERATELOG_DESC',
            title: <div style={{ textAlign: 'center' }}>备注说明</div>,
            ellipsis: true,
            width: 160,
            align: 'left',
            hideInSearch: true,
        },
        {
            dataIndex: 'OPERATE_DATE',
            title: '登录时间',
            ellipsis: true,
            width: 160,
            align: 'center',
            hideInSearch: true,
        },
    ]

    const exportTable = (e) => {
        e.stopPropagation();                                            // 防止Collapse组件收起
        const main = document.getElementsByClassName(`saleReportHideBox${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 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={`saleReportHideBox${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' }}>
                <div style={{
                    width: '100%',
                    paddingTop: 0,
                    paddingBottom: 0,
                    paddingRight: 0
                }}>
                    <ProTable
                        actionRef={actionRef}
                        formRef={formRef}
                        columns={columns}
                        bordered
                        expandable={{
                            expandRowByClick: true
                        }}
                        headerTitle={'登录日志列表'}
                        scroll={{ y: 'calc(100vh - 450px)' }}
                        search={{ span: 6 }}
                        pagination={{ pageSize: 100 }}
                        request={async (params) => {
                            const req: any = {
                                SearchParameter: {
                                    OPERATELOG_TYPES: params?.OPERATELOG_TYPE ? params?.OPERATELOG_TYPE : '1000,1001',
                                    OPERATE_DATE_Start: moment(params?.searchDate).format('YYYY-MM-DD'),
                                    OPERATE_DATE_End: moment(params?.searchDate).format('YYYY-MM-DD'),
                                    Province_Code: '734100',
                                },
                                SortStr: 'OPERATE_DATE desc',
                                KeyWord: {
                                    Key: 'USER_NAME,USER_LOGINIP,USER_LOGINPLACE,BROWSER_VERSION,OPERATING_SYSTEM',
                                    Value: params?.searchValue || ''
                                },
                                Province_Code: '734100',
                                PageIndex: 1,
                                PageSize: 999999
                            }
                            setSearchParams(params)
                            const data = await handleGetOPERATELOGList(req)
                            console.log('login', 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-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>
                            ]
                        }}
                    />
                </div>
            </div>
        </div>
    )
}

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