import { connect } from "umi";
import type { CurrentUser } from "umi";
import type { ConnectState } from "@/models/connect";
import React, { useEffect, useRef, useState } from "react";
import { FormInstance, Select } from "antd";
import { Button, message, Space, Spin, Tree } from "antd";
import type { ActionType } from "@ant-design/pro-table";
import ProTable from "@ant-design/pro-table";
import ReactHTMLTableToExcel from "react-html-table-to-excel";
import { handleGetServerpartTree } from "@/pages/basicManage/serverpartAssets/service";
import useRequest from "@ahooksjs/use-request";
import { handleGetEndaccountHisList, handleGetServiceShopList } from "../service";
import { getFieldEnumTreeNoSession } from "@/services/options";
import moment from 'moment'
import { exportXlsxFromProColumnsExcelJS } from "@/utils/exportExcelFun";


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

    // 导出的加载效果
    const [showLoading, setShowLoading] = useState<boolean>(false)
    // 是否显示打印的表格
    const [showExportTable, setShowExportTable] = useState<boolean>(false)
    // 查询的条件
    const [searchParams, setSearchParams] = useState<any>()
    // 服务区列表
    const [serverPartList, setServerPartList] = useState<any>()
    // 当前选择服务区所对应的门店列表
    const [shopList, setShopList] = useState<any>()
    // 当前选择的服务区
    const [selectServerPart, setSelectServerPart] = useState<any>()
    // 当前选择的门店
    const [selectShop, setSelectShop] = useState<any>()
    // 默认查询时间
    const [defaultSearchTime, setDefaultSearchTime] = useState<any>()
    // 判断有时间了没
    const [isHaveTime, setIsHaveTime] = useState<boolean>(false)
    // 第一次进入直接请求 全部服务区需要很久 所以第一次不请求 除非手动
    const [isFirst, setIsFirst] = useState<boolean>(true)

    const { loading: treeLoading, data: treeView = [] } = useRequest(async () => {
        const req: any = {
            ProvinceCode: currentUser?.ProvinceCode,
            ServerpartType: 1000,
            ShowWholePower: false,
            ShowSPRegion: false,
            ShowRoyalty: false,
            ShowCompactCount: false,
        }
        const data = await handleGetServerpartTree(req)
        let list: any = []
        // 测试服务区放最后
        let testObj: any = {}
        if (data && data.length > 0) {
            data.forEach((item: any) => {
                if (item.value !== 424) {
                    if (item.value === 586) {
                        testObj = item
                    } else {
                        list.push(item)
                    }
                }
            })
        }
        if (testObj.value) {
            list.push(testObj)
        }
        // list.push({ label: '全部', value: '' })
        list.unshift({ label: '全部', value: '' })
        setServerPartList(list)
    })

    // 拿到当前服务区的门店列表
    const handleGetShopList = async (id: any) => {
        const req = {
            ProvinceCode: currentUser?.ProvinceCode,
            ServerpartId: id,
            ShowWholePower: true
        }
        const data = await handleGetServiceShopList(req)
        console.log('shop', data);
        setShopList(data.List)

    }

    // 处理状态的list (全部 待我处理 财务审核 财务审结 主任复核 主任审结)
    const EndaccountStateList: any = ["all", 0, 1, 2, 3, 4]
    // 异常类型的list (全部 短款日结 长款日结 异常校验 手工录入 扫码上传)
    const ExceptionStateList: any = ["all", 0, 1, 2, 3, 4]

    const columns: any = [
        {
            title: '序号',
            width: 70,
            dataIndex: 'index',
            valueType: 'index',
            hideInSearch: true,
            align: 'center'
        },
        {
            title: '处理状态',
            width: 100,
            dataIndex: 'Treatment_MarkState',
            valueType: 'select',
            valueEnum: {
                "0": "未校验",
                "1": "待审核",
                "2": "已审结",
                "3": "主任复核",
                "4": "主任审结",
            },
            hideInSearch: true,
            align: 'center'
        },
        {
            title: '服务区名称',
            width: 150,
            dataIndex: 'Serverpart_Name',
            ellipsis: true,
            renderFormItem: () => {
                return <Select
                    options={serverPartList}
                    onChange={(e: any) => {
                        console.log('e', e);
                        if (e) {
                            handleGetShopList(e)
                            setSelectServerPart(e)
                        } else {
                            setShopList([])
                            setSelectServerPart(undefined)
                        }
                    }}
                    allowClear
                    showSearch={true}
                    optionFilterProp="label"
                />
            },
        },
        {
            title: '门店名称',
            width: 180,
            dataIndex: 'ServerpartShop_Name',
            ellipsis: true,
            hideInSearch: true,
            // renderFormItem: () => {
            //     return <Select
            //         options={shopList}
            //         onChange={(e: any) => {
            //             console.log('e', e);
            //             if (e) {
            //                 handleGetShopList(e)
            //                 setSelectShop(e)
            //             } else {
            //                 setShopList([])
            //                 setSelectShop(undefined)
            //             }
            //         }}
            //         allowClear
            //         showSearch={true}
            //         optionFilterProp="label"
            //     />
            // },
        },
        {
            title: '处理状态',
            dataIndex: 'EndaccountState',
            valueType: 'select',
            valueEnum: {
                "0": '全部',
                "1": "待我处理",
                "2": "财务审核",
                "3": "财务审结",
                "4": "主任复核",
                "5": "主任审结",
            },
            hideInTable: true,
            initialValue: "0"
        },
        {
            title: '异常类型',
            dataIndex: 'ExceptionState',
            valueType: 'select',
            valueEnum: {
                "0": '全部',
                "1": "短款日结",
                "2": "长款日结",
                "3": "异常校验",
                "4": "手工录入",
                "5": "扫码上传",
            },
            hideInTable: true,
            initialValue: "0"
        },
        {
            title: '统计时间',
            dataIndex: 'search_date',
            valueType: 'dateRange',
            hideInTable: true,
            initialValue: new Date().getMonth() + 1 === 1 ? [moment().subtract(2, 'y').endOf('y').format('YYYY-MM-DD'), moment().subtract(2, 'y').endOf('y').format('YYYY-MM-DD')]
                : [moment().subtract(1, 'y').endOf('y').format('YYYY-MM-DD'), moment().subtract(1, 'y').endOf('y').format('YYYY-MM-DD')],
            search: {
                transform: (value) => {
                    return {
                        StartDate: value[0],
                        EndDate: value[1],
                    };
                },
            },
            fieldProps: {
                disabledDate: (current: any) => current && current > moment().endOf('day')
            }
        },
        {
            title: '日结校验',
            width: 350,
            dataIndex: 'Description_Info',
            ellipsis: true,
            hideInSearch: true,
            render: (_, record) => {
                return `${record?.Description_Staff ? record?.Description_Staff + '：' : ''}${record?.Description_Info || ''} | ${record?.Approved_Staff ? record?.Approved_Staff + '：' : ''}${record?.Approved_Info || ''}`
            }
        },
        {
            title: <div style={{ textAlign: 'center' }}>客单数量</div>,
            width: 100,
            dataIndex: 'Ticket_Count',
            valueType: 'digit',
            ellipsis: true,
            hideInSearch: true,
            align: 'right'
        },
        // {
        //     title: <div style={{ textAlign: 'center' }}>销售数量</div>,
        //     width: 100,
        //     dataIndex: '',
        //     valueType: 'digit',
        //     ellipsis: true,
        //     hideInSearch: true,
        //     align: 'right'
        // },
        {
            title: <div style={{ textAlign: 'center' }}>总销售额</div>,
            width: 100,
            dataIndex: 'TotalSell_Amount',
            valueType: 'digit',
            ellipsis: true,
            hideInSearch: true,
            align: 'right'
        },
        {
            title: <div style={{ textAlign: 'center' }}>长短款</div>,
            width: 100,
            dataIndex: 'Difference_Amount   ',
            valueType: 'digit',
            ellipsis: true,
            hideInSearch: true,
            align: 'right'
        },
        // {
        //     title: <div style={{ textAlign: 'center' }}>客单均价</div>,
        //     width: 100,
        //     dataIndex: '',
        //     valueType: 'digit',
        //     ellipsis: true,
        //     hideInSearch: true,
        //     align: 'right'
        // },
        {
            title: <div style={{ textAlign: 'center' }}>实收金额</div>,
            width: 100,
            dataIndex: 'Revenue_Amount',
            valueType: 'digit',
            ellipsis: true,
            hideInSearch: true,
            align: 'right'
        },
        {
            title: <div style={{ textAlign: 'center' }}>结账时间</div>,
            width: 150,
            dataIndex: 'Endaccount_EndDate',
            ellipsis: true,
            hideInSearch: true,
            align: 'right',
            sorter: (a, b) => new Date(a.Endaccount_EndDate).getTime() - new Date(b.Endaccount_EndDate).getTime(),
            defaultSortOrder: 'descend',
            render: (_, record) => {
                return record?.Endaccount_EndDate ? moment(record?.Endaccount_EndDate).format('YYYY-MM-DD HH:mm:ss') : ''
            }
        }
    ]



    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-HistoricalAccounting');                    // 给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={`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
                        }}
                        search={{ span: 6, collapsed: false }}
                        scroll={{ y: 'calc(100vh - 450px)' }}
                        request={async (params) => {
                            if (isFirst) {
                                setIsFirst(false)
                                return { data: [], success: true }
                            }

                            console.log('params', params);
                            const req: any = {
                                ServerpartIds: selectServerPart,
                                StartDate: params?.StartDate,
                                EndDate: params?.EndDate,
                                TreatmentMarkState: params?.EndaccountState ? EndaccountStateList[params?.EndaccountState] === 'all' ? '' : EndaccountStateList[params?.EndaccountState] : '',
                                ExceptionState: params?.ExceptionState ? ExceptionStateList[params?.ExceptionState] === 'all' ? '' : ExceptionStateList[params?.ExceptionState] : '',
                                EndaccountState: 1,
                                PageIndex: 1,
                                PageSize: 999999
                            }
                            console.log('req', req);

                            setSearchParams(params)
                            const data = await handleGetEndaccountHisList(req)
                            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-HistoricalAccounting"
                                //         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
}))(HistoricalAccounting);
