import { connect } from "umi";
import type { CurrentUser } from "umi";
import type { ConnectState } from "@/models/connect";
import React, { useEffect, 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 PageTitleBox from "@/components/PageTitleBox";
import moment from "moment";
import { handleGetCHECKCOMMODITYList, handleGetINSALES_STATISTICList } from "../service";
import session from "@/utils/session";
import { getMyShopList } from "@/pages/account/center/sevice";
import { render } from "react-dom";
import { initial } from "lodash";
import InventoryDetailModal from "./components/InventoryDetailModal";
import { exportXlsxFromProColumnsExcelJS } from "@/utils/exportExcelFun";
import { formatTreeData } from "@/utils/format";


const InventoryDetails: React.FC<{ currentUser: CurrentUser, isComponents?: any, parentRow?: any, birthIn?: any, parentSearchForm?: any }> = (props) => {
    // birthIn 这个东西如果等于 InventoryCategory  说明是被嵌套在 进销存类别报表页面 这个嵌套很麻烦 所以单独跟组件的区分一下  parentSearchForm 只有在birthIn为InventoryCategory才有值
    const { currentUser, isComponents, parentRow, birthIn, parentSearchForm } = 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 [currentShopList, setCurrentShopList] = useState<any>()
    // 判断时间的列表
    const [timeList, setTimeList] = useState<any>()
    // 表格的合计字段
    const [tableSummary, setTableSummary] = useState<any>()
    // 拿到这次查询到的门店信息
    const [currentShopInfo, setCurrentShopInfo] = useState<any>()
    // 当前显示的数据类型
    const [currentDataType, setCurrentDataType] = useState<string>('1') // 1含税 2不含税
    // 显示详情
    const [showDetail, setShowDetail] = useState<boolean>(false)
    // 当前的行数据
    const [currentRow, setCurrentRow] = useState<any>()
    // 判断 是不是要禁用 表格的搜索条件
    const [handleDisabledTableSearch, setHandleDisabledTableSearch] = useState<boolean>(false)


    const columns: any = [
        {
            title: "服务区",
            dataIndex: "servicePartId",
            hideInTable: true,
            valueType: 'select',
            fieldProps: {
                showSearch: true,
                disabled: handleDisabledTableSearch,
                onChange: async (value: any, label: any) => {
                    console.log('value', value, label);
                    formRef.current?.setFieldsValue({ serverpartShopId: undefined, InventoryTime: undefined })
                    await handleGetShopList(value)
                }
            },
            request: async () => {
                const list = session.get('ServerpartIdsTree')
                return list || []
            },
        },
        {
            title: "门店",
            dataIndex: "serverpartShopId",
            hideInTable: true,
            valueType: 'select',
            fieldProps: {
                showSearch: true,
                options: currentShopList,
                disabled: handleDisabledTableSearch,
                onChange: async (value: any, label: any) => {
                    console.log('value', value, label);
                    formRef.current?.setFieldsValue({ InventoryTime: undefined })
                    await handleGetTimeList(value)
                }
            },
        },
        {
            title: "盘存时间",
            dataIndex: "InventoryTime",
            hideInTable: true,
            valueType: 'select',
            fieldProps: {
                showSearch: true,
                disabled: handleDisabledTableSearch,
                options: timeList
            },
        },
        {
            title: "数据类型",
            dataIndex: "dataType",
            valueType: 'select',
            hideInTable: true,
            fieldProps: {
                options: [{ label: "含税", value: '1' }, { label: "除税", value: '2' }],
            },
            initialValue: currentDataType,
        },

        {
            title: "商品信息",
            dataIndex: "COMMODITYINFO",
            align: 'center',
            hideInSearch: true,
            children: [
                {
                    title: "序号",
                    dataIndex: "index",
                    valueType: 'index',
                    align: 'center',
                    width: 80,
                    ellipsis: true,
                    hideInSearch: true,
                },
                {
                    title: "商品类型",
                    dataIndex: "COMMODITY_TYPE",
                    align: 'center',
                    width: 120,
                    ellipsis: true,
                    hideInSearch: true,
                },
                {
                    title: <div style={{ textAlign: 'center' }}>商品名称</div>,
                    dataIndex: "COMMODITY_NAME",
                    align: 'left',
                    width: 250,
                    ellipsis: true,
                    hideInSearch: true,
                    render: (_, record) => {
                        return <a onClick={() => {
                            setCurrentRow(record)
                            setShowDetail(true)
                        }}>{record?.COMMODITY_NAME}</a>
                    }
                },
                {
                    title: "商品条码",
                    dataIndex: "COMMODITY_BARCODE",
                    align: 'center',
                    width: 120,
                    ellipsis: true,
                    hideInSearch: true,
                },
                {
                    title: "商品规格",
                    dataIndex: "COMMODITY_RULE",
                    align: 'center',
                    width: 100,
                    ellipsis: true,
                    hideInSearch: true,
                },
            ]
        },
    ]

    // 含税的时候拼在coulmns后面的 
    const columnsType1: any = [
        {
            title: "本期结存",
            dataIndex: "OVERPLU",
            align: 'center',
            hideInSearch: true,
            children: [
                {
                    title: <div style={{ textAlign: 'center' }}>数量</div>,
                    dataIndex: "OVERPLUSCOUNT",
                    align: 'right',
                    valueType: 'digit',
                    width: 90,
                    ellipsis: true,
                    hideInSearch: true,
                },
                {
                    title: <div style={{ textAlign: 'center' }}>金额</div>,
                    dataIndex: "OVERPLUS_AMOUNT",
                    align: 'right',
                    valueType: 'digit',
                    width: 90,
                    ellipsis: true,
                    hideInSearch: true,
                },
            ]
        },
        {
            title: "本期损溢",
            dataIndex: "LOSSPROFIT",
            align: 'center',
            hideInSearch: true,
            children: [
                {
                    title: <div style={{ textAlign: 'center' }}>数量</div>,
                    dataIndex: "LOSSPROFIT_COUNT",
                    align: 'right',
                    valueType: 'digit',
                    width: 90,
                    ellipsis: true,
                    hideInSearch: true,
                },
                {
                    title: <div style={{ textAlign: 'center' }}>金额</div>,
                    dataIndex: "LOSSPROFIT_AMOUNT",
                    align: 'right',
                    valueType: 'digit',
                    width: 90,
                    ellipsis: true,
                    hideInSearch: true,
                },
                {
                    title: <div style={{ textAlign: 'center' }}>损溢率(‰)</div>,
                    dataIndex: "LOSSPROFIT_RATE",
                    align: 'right',
                    width: 90,
                    ellipsis: true,
                    hideInSearch: true,
                    render: (_, record) => {
                        return record?.SELL_TOTALTAXPRICE ? (record?.LOSSPROFIT_AMOUNT / record?.SELL_TOTALTAXPRICE * 1000).toFixed(2) + '%' : 0
                    }
                },
            ]
        },
        {
            title: "本期毛利",
            dataIndex: "GROSS",
            align: 'center',
            hideInSearch: true,
            children: [
                {
                    title: <div style={{ textAlign: 'center' }}>金额</div>,
                    dataIndex: "GROSS_PROFIT",
                    align: 'right',
                    valueType: 'digit',
                    width: 90,
                    ellipsis: true,
                    hideInSearch: true,
                },
                {
                    title: <div style={{ textAlign: 'center' }}>毛利率(%)</div>,
                    dataIndex: "GROSS_PROFITRATE",
                    align: 'right',
                    width: 90,
                    ellipsis: true,
                    hideInSearch: true,
                    render: (_, record) => {
                        return record?.SELL_TOTALTAXPRICE ? (record?.GROSS_PROFIT / record?.SELL_TOTALTAXPRICE * 100).toFixed(2) + '%' : 0
                    }
                },
            ]
        },
        {
            title: "上期结存",
            dataIndex: "LASTOVERPLUS",
            align: 'center',
            hideInSearch: true,
            children: [
                {
                    title: <div style={{ textAlign: 'center' }}>数量</div>,
                    dataIndex: "LAST_OVERPLUSCOUNT",
                    align: 'right',
                    valueType: 'digit',
                    width: 90,
                    ellipsis: true,
                    hideInSearch: true,
                },
                {
                    title: <div style={{ textAlign: 'center' }}>金额</div>,
                    dataIndex: "LAST_OVERPLUSAMOUNT",
                    align: 'right',
                    valueType: 'digit',
                    width: 90,
                    ellipsis: true,
                    hideInSearch: true,
                },
            ]
        },
        {
            title: "本期入库",
            dataIndex: "PURCHASE",
            align: 'center',
            hideInSearch: true,
            children: [
                {
                    title: <div style={{ textAlign: 'center' }}>数量</div>,
                    dataIndex: "PURCHASE_COUNT",
                    align: 'right',
                    valueType: 'digit',
                    width: 90,
                    ellipsis: true,
                    hideInSearch: true,
                },
                {
                    title: <div style={{ textAlign: 'center' }}>金额</div>,
                    dataIndex: "PURCHASE_TOTALTAXPRICE",
                    align: 'right',
                    valueType: 'digit',
                    width: 90,
                    ellipsis: true,
                    hideInSearch: true,
                },
            ]
        },
        {
            title: "本期销售",
            dataIndex: "SELL",
            align: 'center',
            hideInSearch: true,
            children: [
                {
                    title: <div style={{ textAlign: 'center' }}>数量</div>,
                    dataIndex: "SELL_COUNT",
                    align: 'right',
                    valueType: 'digit',
                    width: 90,
                    ellipsis: true,
                    hideInSearch: true,
                },
                {
                    title: <div style={{ textAlign: 'center' }}>单价</div>,
                    dataIndex: "SELL_UNITTAXPRICE",
                    align: 'right',
                    valueType: 'digit',
                    width: 90,
                    ellipsis: true,
                    hideInSearch: true,
                },
                {
                    title: <div style={{ textAlign: 'center' }}>金额</div>,
                    dataIndex: "SELL_TOTALTAXPRICE",
                    align: 'right',
                    valueType: 'digit',
                    width: 90,
                    ellipsis: true,
                    hideInSearch: true,
                },
                {
                    title: <div style={{ textAlign: 'center' }}>成本</div>,
                    dataIndex: "SELL_COST",
                    align: 'right',
                    valueType: 'digit',
                    width: 90,
                    ellipsis: true,
                    hideInSearch: true,
                },
            ]
        },
        {
            title: "本期调拨",
            dataIndex: "TRANSFER",
            align: 'center',
            hideInSearch: true,
            children: [
                {
                    title: <div style={{ textAlign: 'center' }}>数量</div>,
                    dataIndex: "TRANSFER_COUNT",
                    align: 'right',
                    valueType: 'digit',
                    width: 90,
                    ellipsis: true,
                    hideInSearch: true,
                },
                {
                    title: <div style={{ textAlign: 'center' }}>金额</div>,
                    dataIndex: "TRANSFER_AMOUNT",
                    align: 'right',
                    valueType: 'digit',
                    width: 90,
                    ellipsis: true,
                    hideInSearch: true,
                },
            ]
        },
        {
            title: "本期领用",
            dataIndex: "RECEIVE",
            align: 'center',
            hideInSearch: true,
            children: [
                {
                    title: <div style={{ textAlign: 'center' }}>数量</div>,
                    dataIndex: "RECEIVE_COUNT",
                    align: 'right',
                    valueType: 'digit',
                    width: 90,
                    ellipsis: true,
                    hideInSearch: true,
                },
                {
                    title: <div style={{ textAlign: 'center' }}>金额</div>,
                    dataIndex: "RECEIVE_AMOUNT",
                    align: 'right',
                    valueType: 'digit',
                    width: 90,
                    ellipsis: true,
                    hideInSearch: true,
                },
            ]
        },
        {
            title: "本期退货",
            dataIndex: "BACK",
            align: 'center',
            hideInSearch: true,
            children: [
                {
                    title: <div style={{ textAlign: 'center' }}>数量</div>,
                    dataIndex: "BACK_COUNT",
                    align: 'right',
                    valueType: 'digit',
                    width: 90,
                    ellipsis: true,
                    hideInSearch: true,
                },
                {
                    title: <div style={{ textAlign: 'center' }}>金额</div>,
                    dataIndex: "BACK_AMOUNT",
                    align: 'right',
                    valueType: 'digit',
                    width: 90,
                    ellipsis: true,
                    hideInSearch: true,
                },
            ]
        }
    ]

    // 除税的时候拼在coulmns后面的 
    const columnsType2: any = [
        {
            title: "本期结存",
            dataIndex: "OVERPLU",
            align: 'center',
            hideInSearch: true,
            children: [
                {
                    title: <div style={{ textAlign: 'center' }}>数量</div>,
                    dataIndex: "OVERPLUSCOUNT",
                    align: 'right',
                    valueType: 'digit',
                    width: 90,
                    ellipsis: true,
                    hideInSearch: true,
                },
                {
                    title: <div style={{ textAlign: 'center' }}>金额</div>,
                    dataIndex: "OVERPLUS_PRICE",
                    align: 'right',
                    valueType: 'digit',
                    width: 90,
                    ellipsis: true,
                    hideInSearch: true,
                },
            ]
        },
        {
            title: "本期损溢",
            dataIndex: "LOSSPROFIT",
            align: 'center',
            hideInSearch: true,
            children: [
                {
                    title: <div style={{ textAlign: 'center' }}>数量</div>,
                    dataIndex: "LOSSPROFIT_COUNT",
                    align: 'right',
                    valueType: 'digit',
                    width: 90,
                    ellipsis: true,
                    hideInSearch: true,
                },
                {
                    title: <div style={{ textAlign: 'center' }}>金额</div>,
                    dataIndex: "LOSSPROFIT_PRICE",
                    align: 'right',
                    valueType: 'digit',
                    width: 90,
                    ellipsis: true,
                    hideInSearch: true,
                },
                {
                    title: <div style={{ textAlign: 'center' }}>损溢率(‰)</div>,
                    dataIndex: "LOSSPROFIT_RATE",
                    align: 'right',
                    width: 90,
                    ellipsis: true,
                    hideInSearch: true,
                    render: (_, record) => {
                        return record?.SELL_TOTALPRICE ? (record?.LOSSPROFIT_PRICE / record?.SELL_TOTALPRICE * 1000).toFixed(2) + '%' : 0
                    }
                },
            ]
        },
        {
            title: "本期毛利",
            dataIndex: "GROSS",
            align: 'center',
            hideInSearch: true,
            children: [
                {
                    title: <div style={{ textAlign: 'center' }}>金额</div>,
                    dataIndex: "GROSS_PROFITPRICE",
                    align: 'right',
                    valueType: 'digit',
                    width: 90,
                    ellipsis: true,
                    hideInSearch: true,
                },
                {
                    title: <div style={{ textAlign: 'center' }}>毛利率(%)</div>,
                    dataIndex: "GROSS_PROFITRATE",
                    align: 'right',
                    width: 90,
                    ellipsis: true,
                    hideInSearch: true,
                    render: (_, record) => {
                        return record?.SELL_TOTALPRICE ? (record?.GROSS_PROFITPRICE / record?.SELL_TOTALPRICE * 100).toFixed(2) + '%' : 0
                    }
                },
            ]
        },
        {
            title: "上期结存",
            dataIndex: "LASTOVERPLUS",
            align: 'center',
            hideInSearch: true,
            children: [
                {
                    title: <div style={{ textAlign: 'center' }}>数量</div>,
                    dataIndex: "LAST_OVERPLUSCOUNT",
                    align: 'right',
                    valueType: 'digit',
                    width: 90,
                    ellipsis: true,
                    hideInSearch: true,
                },
                {
                    title: <div style={{ textAlign: 'center' }}>金额</div>,
                    dataIndex: "LAST_OVERPLUSPRICE",
                    align: 'right',
                    valueType: 'digit',
                    width: 90,
                    ellipsis: true,
                    hideInSearch: true,
                },
            ]
        },
        {
            title: "本期入库",
            dataIndex: "PURCHASE",
            align: 'center',
            hideInSearch: true,
            children: [
                {
                    title: <div style={{ textAlign: 'center' }}>数量</div>,
                    dataIndex: "PURCHASE_COUNT",
                    align: 'right',
                    valueType: 'digit',
                    width: 90,
                    ellipsis: true,
                    hideInSearch: true,
                },
                {
                    title: <div style={{ textAlign: 'center' }}>金额</div>,
                    dataIndex: "PURCHASE_TOTALPRICE",
                    align: 'right',
                    valueType: 'digit',
                    width: 90,
                    ellipsis: true,
                    hideInSearch: true,
                },
            ]
        },
        {
            title: "本期销售",
            dataIndex: "SELL",
            align: 'center',
            hideInSearch: true,
            children: [
                {
                    title: <div style={{ textAlign: 'center' }}>数量</div>,
                    dataIndex: "SELL_COUNT",
                    align: 'right',
                    valueType: 'digit',
                    width: 90,
                    ellipsis: true,
                    hideInSearch: true,
                },
                {
                    title: <div style={{ textAlign: 'center' }}>单价</div>,
                    dataIndex: "SELL_UNITPRICE",
                    align: 'right',
                    valueType: 'digit',
                    width: 90,
                    ellipsis: true,
                    hideInSearch: true,
                },
                {
                    title: <div style={{ textAlign: 'center' }}>金额</div>,
                    dataIndex: "SELL_TOTALPRICE",
                    align: 'right',
                    valueType: 'digit',
                    width: 90,
                    ellipsis: true,
                    hideInSearch: true,
                },
                {
                    title: <div style={{ textAlign: 'center' }}>成本</div>,
                    dataIndex: "SELL_COSTPRICE",
                    align: 'right',
                    valueType: 'digit',
                    width: 90,
                    ellipsis: true,
                    hideInSearch: true,
                },
            ]
        },
        {
            title: "本期调拨",
            dataIndex: "TRANSFER",
            align: 'center',
            hideInSearch: true,
            children: [
                {
                    title: <div style={{ textAlign: 'center' }}>数量</div>,
                    dataIndex: "TRANSFER_COUNT",
                    align: 'right',
                    valueType: 'digit',
                    width: 90,
                    ellipsis: true,
                    hideInSearch: true,
                },
                {
                    title: <div style={{ textAlign: 'center' }}>金额</div>,
                    dataIndex: "TRANSFER_PRICE",
                    align: 'right',
                    valueType: 'digit',
                    width: 90,
                    ellipsis: true,
                    hideInSearch: true,
                },
            ]
        },
        {
            title: "本期领用",
            dataIndex: "RECEIVE",
            align: 'center',
            hideInSearch: true,
            children: [
                {
                    title: <div style={{ textAlign: 'center' }}>数量</div>,
                    dataIndex: "RECEIVE_COUNT",
                    align: 'right',
                    valueType: 'digit',
                    width: 90,
                    ellipsis: true,
                    hideInSearch: true,
                },
                {
                    title: <div style={{ textAlign: 'center' }}>金额</div>,
                    dataIndex: "RECEIVE_PRICE",
                    align: 'right',
                    valueType: 'digit',
                    width: 90,
                    ellipsis: true,
                    hideInSearch: true,
                },
            ]
        },
        {
            title: "本期退货",
            dataIndex: "BACK",
            align: 'center',
            hideInSearch: true,
            children: [
                {
                    title: <div style={{ textAlign: 'center' }}>数量</div>,
                    dataIndex: "BACK_COUNT",
                    align: 'right',
                    valueType: 'digit',
                    width: 90,
                    ellipsis: true,
                    hideInSearch: true,
                },
                {
                    title: <div style={{ textAlign: 'center' }}>金额</div>,
                    dataIndex: "BACK_PRICE",
                    align: 'right',
                    valueType: 'digit',
                    width: 90,
                    ellipsis: true,
                    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 tableTop = document.createElement('div')
        tableTop.innerText = `${currentShopInfo?.SERVERPART_NAME}${currentShopInfo?.SHOPNAME}进销存报表`
        tableTop.setAttribute('style', 'font-size:20px;font-weight:600;display:flex;width:100%;justify-content: center;text-align: center;padding: 10px 0');

        const tableNav = document.createElement('div')
        tableNav.innerText = `统计方式：按成本结算(${currentDataType === '1' ? '含税' : '除税'})`

        const tempTable = document.createElement('table');
        tempTable.appendChild(tableTop)
        tempTable.appendChild(tableNav)

        tempTable.appendChild(thead);
        tempTable.appendChild(tbody);

        tempTable.setAttribute('id', 'table-to-xls-InventoryDetails');                    // 给table添加id，值与按钮上的table字段对应

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

        setShowLoading(false)

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

    // 拿到门店的列表数据
    const handleGetShopList = async (id: any) => {
        if (!id) {
            setCurrentShopList([])
            return
        }
        const req: any = {
            // 调用的接口 里面 自己包了一层
            // SearchParameter: {
            ISVALID: 1,
            SERVERPART_ID: id,
            INSALES_TYPE: 1,
            // },
            PageIndex: 1,
            PageSize: 999999,
            SortStr: "SHOPTRADE,SHOPREGION,SHOPCODE"
        }
        const data = await getMyShopList(req)
        let list: any = []
        if (data && data.length > 0) {
            data.forEach((item: any) => {
                list.push({ label: item.SHOPNAME, value: item.SERVERPARTSHOP_ID })
            })
        }
        setCurrentShopList(list)
    }

    // 拿到盘存时间的列表数据
    const handleGetTimeList = async (id: any) => {
        const req: any = {
            SearchParameter: {
                SERVERPARTSHOP_IDS: id,
                CHECK_STATES: 1,
                CHECK_TYPES: "1000,3000"
            },
            PageIndex: 1,
            PageSize: 999999,
        }
        const data = await handleGetCHECKCOMMODITYList(req)
        console.log('盘存时间', data);
        let list: any = []
        if (data && data.length > 0) {
            data.forEach((item: any) => {
                list.push({ label: item.CHECKDATE, value: item.CHECKDATE })
            })
        }
        setTimeList(list)
    }

    // 详情的 关闭方法
    const handleModalCancel = () => {
        setShowDetail(false)
        setCurrentRow(null)
    }

    useEffect(() => {
        // 监听一下 birthIn  如果是 InventoryCategory  就把页面变成配置的 嵌套了
        if (birthIn === 'InventoryCategory') {
            setHandleDisabledTableSearch(true)
            let fromRes: any = parentSearchForm.current?.getFieldsValue()
            handleGetShopList(fromRes.servicePartId)
            formRef.current?.setFieldsValue({
                servicePartId: fromRes.servicePartId,
                serverpartShopId: fromRes.serverpartShopId,
                InventoryTime: fromRes.InventoryTime ? fromRes.InventoryTime.split('-')[1] : "",
            })
            actionRef.current?.reload()
        }
    }, birthIn)

    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={currentDataType === '1' ? [...columns, ...columnsType1] : currentDataType === '2' ? [...columns, ...columnsType2] : []}
                            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' }}>
                {/* <LeftSelectTree setSelectedId={setSelectedId} setCollapsible={setCollapsible} collapsible={collapsible} onShowShop={true} /> */}
                <div style={{
                    width: '100%',
                    paddingTop: 0,
                    paddingBottom: 0,
                    paddingRight: 0
                }}>
                    <ProTable
                        actionRef={actionRef}
                        formRef={formRef}
                        columns={isComponents ? [...columns, ...columnsType1] : currentDataType === '1' ? [...columns, ...columnsType1] : currentDataType === '2' ? [...columns, ...columnsType2] : []}
                        bordered
                        expandable={{
                            expandRowByClick: true
                        }}
                        scroll={isComponents ? { x: "100%", y: "400px" } : { x: "100%", y: "calc(100vh - 540px)" }}
                        headerTitle={<PageTitleBox props={props} />} // 列表表头
                        search={isComponents ? false : { span: 4 }}
                        request={async (params) => {
                            if ((!params.servicePartId || !params.serverpartShopId || !params.InventoryTime) && !isComponents && birthIn !== 'InventoryCategory') {
                                setReqDetailList([])
                                setCurrentShopInfo(null)
                                return { data: [], success: true }
                            }
                            setCurrentDataType(params.dataType)

                            let req: any = {}
                            if (birthIn === 'InventoryCategory') {
                                let fromRes: any = parentSearchForm.current?.getFieldsValue()
                                console.log('fromResfromResfromResfromResfromRes', fromRes);

                                req = {
                                    SearchParameter: {
                                        COMMODITY_TYPE: parentRow?.COMMODITY_TYPE,
                                        SERVERPART_ID: fromRes.servicePartId ? fromRes.servicePartId : '',
                                        SERVERPARTSHOP_ID: fromRes.serverpartShopId ? fromRes.serverpartShopId : '',
                                    },
                                    PageIndex: 1,
                                    PageSize: 999999
                                }
                                setSearchParams(fromRes)
                                console.log('reqreqreqreqreqreqreqreq', req);
                            } else if (isComponents) {
                                req = {
                                    SearchParameter: {
                                        SERVERPART_ID: parentRow.SERVERPART_ID ? parentRow.SERVERPART_ID : '',
                                        SERVERPARTSHOP_ID: parentRow.SERVERPARTSHOP_ID ? parentRow.SERVERPARTSHOP_ID : '',
                                        CHECKDATE: parentRow.checkTime ? parentRow.checkTime : "",
                                        COMMODITY_IDS: parentRow?.COMMODITY_IDS || "",
                                    },
                                    PageIndex: 1,
                                    PageSize: 999999
                                }
                                setSearchParams(params)
                            } else {
                                req = {
                                    SearchParameter: {
                                        SERVERPART_ID: params.servicePartId ? params.servicePartId : '',
                                        SERVERPARTSHOP_ID: params.serverpartShopId ? params.serverpartShopId : '',
                                        CHECKDATE: params.InventoryTime ? params.InventoryTime : "",
                                    },
                                    PageIndex: 1,
                                    PageSize: 999999
                                }
                                setSearchParams(params)
                            }


                            const data = await handleGetINSALES_STATISTICList(req)
                            console.log('dkasjdkajd', data);
                            if (data && data.length > 0) {
                                let obj: any = data[0]
                                setCurrentShopInfo({
                                    SHOPNAME: obj.SHOPNAME,
                                    SERVERPART_NAME: obj.SERVERPART_NAME
                                })


                                let fieldData: any = [
                                    "OVERPLUSCOUNT",
                                    "OVERPLUS_PRICE",
                                    "LOSSPROFIT_COUNT",
                                    "LOSSPROFIT_PRICE",
                                    "GROSS_PROFITPRICE",
                                    "LAST_OVERPLUSCOUNT",
                                    "LAST_OVERPLUSPRICE",
                                    "PURCHASE_COUNT",
                                    "PURCHASE_TOTALPRICE",
                                    "SELL_COUNT",
                                    "SELL_UNITPRICE",
                                    "SELL_TOTALPRICE",
                                    "SELL_COSTPRICE",
                                    "TRANSFER_COUNT",
                                    "TRANSFER_PRICE",
                                    "RECEIVE_COUNT",
                                    "RECEIVE_PRICE",
                                    "BACK_COUNT",
                                    "BACK_PRICE",
                                    "OVERPLUS_AMOUNT",
                                    "LOSSPROFIT_AMOUNT",
                                    "GROSS_PROFIT",
                                    "LAST_OVERPLUSAMOUNT",
                                    "PURCHASE_TOTALTAXPRICE",
                                    "SELL_UNITTAXPRICE",
                                    "SELL_TOTALTAXPRICE",
                                    "SELL_COST",
                                    "TRANSFER_AMOUNT",
                                    "RECEIVE_AMOUNT",
                                    "BACK_AMOUNT",
                                ]
                                let enumList: any = []
                                let newPrintData: any = formatTreeData(JSON.parse(JSON.stringify(data)), fieldData, enumList, [], [])

                                setReqDetailList(newPrintData)
                                // 来计算全部的合计值 
                                // 本期结存数量
                                let total_OVERPLUSCOUNT = 0
                                // 本期结存金额
                                let total_OVERPLUSMONEY = 0
                                // 本期损溢数量
                                let total_LOSSPROFITCOUNT = 0
                                // 本期损溢金额
                                let total_LOSSPROFITMONEY = 0
                                // 本期损溢率
                                let total_LOSSPROFITRATE = 0
                                // 本期毛利金额
                                let total_GROSSMONEY = 0
                                // 本期毛利毛利率
                                let total_GROSSPROFITRATE = 0
                                // 上期结存数量
                                let total_LASTOVERPLUSCOUNT = 0
                                // 上期结存金额
                                let total_LASTOVERPLUSMONEY = 0
                                // 本期入库数量
                                let total_PURCHASECOUNT = 0
                                // 本期入库金额
                                let total_PURCHASEMONEY = 0
                                // 本期销售数量
                                let total_SELLCOUNT = 0
                                // 本期销售单价
                                let total_SELLPRICE = 0
                                // 本期销售金额
                                let total_SELLMONEY = 0
                                // 本期销售成本
                                let total_SELLCOST = 0
                                // 本期调拨数量
                                let total_TRANSFERCOUNT = 0
                                // 本期调拨金额
                                let total_TRANSFERMONEY = 0
                                // 本期领用数量
                                let total_RECEIVECOUNT = 0
                                // 本期领用金额
                                let total_RECEIVEMONEY = 0
                                // 本期退货数量
                                let total_BACKCOUNT = 0
                                // 本期退货金额
                                let total_BACKMONEY = 0

                                data.forEach((item: any) => {
                                    total_OVERPLUSCOUNT += item.OVERPLUSCOUNT ? Number(item.OVERPLUSCOUNT) : 0
                                    total_OVERPLUSMONEY += params.dataType === '1' || isComponents ? item.OVERPLUS_AMOUNT ? Number(item.OVERPLUS_AMOUNT) : 0 : item.OVERPLUS_PRICE ? Number(item.OVERPLUS_PRICE) : 0
                                    total_LOSSPROFITCOUNT += item.LOSSPROFIT_COUNT ? Number(item.LOSSPROFIT_COUNT) : 0
                                    total_LOSSPROFITMONEY += params.dataType === '1' || isComponents ? item.LOSSPROFIT_AMOUNT ? Number(item.LOSSPROFIT_AMOUNT) : 0 : item.LOSSPROFIT_PRICE ? Number(item.LOSSPROFIT_PRICE) : 0
                                    total_GROSSMONEY += params.dataType === '1' || isComponents ? item.GROSS_PROFIT ? Number(item.GROSS_PROFIT) : 0 : item.GROSS_PROFITPRICE ? Number(item.GROSS_PROFITPRICE) : 0
                                    total_LASTOVERPLUSCOUNT += item.LAST_OVERPLUSCOUNT ? Number(item.LAST_OVERPLUSCOUNT) : 0
                                    total_LASTOVERPLUSMONEY += params.dataType === '1' || isComponents ? item.LAST_OVERPLUSAMOUNT ? Number(item.LAST_OVERPLUSAMOUNT) : 0 : item.LAST_OVERPLUSPRICE ? Number(item.LAST_OVERPLUSPRICE) : 0
                                    total_PURCHASECOUNT += item.PURCHASE_COUNT ? Number(item.PURCHASE_COUNT) : 0
                                    total_PURCHASEMONEY += params.dataType === '1' || isComponents ? item.PURCHASE_TOTALTAXPRICE ? Number(item.PURCHASE_TOTALTAXPRICE) : 0 : item.PURCHASE_TOTALPRICE ? Number(item.PURCHASE_TOTALPRICE) : 0
                                    total_SELLCOUNT += item.SELL_COUNT ? Number(item.SELL_COUNT) : 0
                                    total_SELLPRICE += params.dataType === '1' || isComponents ? item.SELL_UNITTAXPRICE ? Number(item.SELL_UNITTAXPRICE) : 0 : item.SELL_UNITPRICE ? Number(item.SELL_UNITPRICE) : 0
                                    total_SELLMONEY += params.dataType === '1' || isComponents ? item.SELL_TOTALTAXPRICE ? Number(item.SELL_TOTALTAXPRICE) : 0 : item.SELL_TOTALPRICE ? Number(item.SELL_TOTALPRICE) : 0
                                    total_SELLCOST += params.dataType === '1' || isComponents ? item.SELL_COST ? Number(item.SELL_COST) : 0 : item.SELL_COSTPRICE ? Number(item.SELL_COSTPRICE) : 0
                                    total_TRANSFERCOUNT += item.TRANSFER_COUNT ? Number(item.TRANSFER_COUNT) : 0
                                    total_TRANSFERMONEY += params.dataType === '1' || isComponents ? item.TRANSFER_AMOUNT ? Number(item.TRANSFER_AMOUNT) : 0 : item.TRANSFER_PRICE ? Number(item.TRANSFER_PRICE) : 0
                                    total_RECEIVECOUNT += item.RECEIVE_COUNT ? Number(item.RECEIVE_COUNT) : 0
                                    total_RECEIVEMONEY += params.dataType === '1' || isComponents ? item.RECEIVE_AMOUNT ? Number(item.RECEIVE_AMOUNT) : 0 : item.RECEIVE_PRICE ? Number(item.RECEIVE_PRICE) : 0
                                    total_BACKCOUNT += item.BACK_COUNT ? Number(item.BACK_COUNT) : 0
                                    total_BACKMONEY += params.dataType === '1' || isComponents ? item.BACK_AMOUNT ? Number(item.BACK_AMOUNT) : 0 : item.BACK_PRICE ? Number(item.BACK_PRICE) : 0
                                })

                                setTableSummary({
                                    OVERPLUSCOUNT: total_OVERPLUSCOUNT.toFixed(2),
                                    OVERPLUS_AMOUNT: total_OVERPLUSMONEY.toFixed(2),
                                    LOSSPROFIT_COUNT: total_LOSSPROFITCOUNT.toFixed(2),
                                    LOSSPROFIT_AMOUNT: total_LOSSPROFITMONEY.toFixed(2),
                                    GROSS_PROFIT: total_GROSSMONEY.toFixed(2),
                                    LAST_OVERPLUSCOUNT: total_LASTOVERPLUSCOUNT.toFixed(2),
                                    LAST_OVERPLUSAMOUNT: total_LASTOVERPLUSMONEY.toFixed(2),
                                    PURCHASE_COUNT: total_PURCHASECOUNT.toFixed(2),
                                    PURCHASE_TOTALTAXPRICE: total_PURCHASEMONEY.toFixed(2),
                                    SELL_COUNT: total_SELLCOUNT.toFixed(2),
                                    SELL_UNITTAXPRICE: total_SELLPRICE.toFixed(2),
                                    SELL_TOTALTAXPRICE: total_SELLMONEY.toFixed(2),
                                    SELL_COST: total_SELLCOST.toFixed(2),
                                    TRANSFER_COUNT: total_TRANSFERCOUNT.toFixed(2),
                                    TRANSFER_AMOUNT: total_TRANSFERMONEY.toFixed(2),
                                    RECEIVE_COUNT: total_RECEIVECOUNT.toFixed(2),
                                    RECEIVE_AMOUNT: total_RECEIVEMONEY.toFixed(2),
                                    BACK_COUNT: total_BACKCOUNT.toFixed(2),
                                    BACK_AMOUNT: total_BACKMONEY.toFixed(2),

                                    LOSSPROFIT_RATE: total_SELLMONEY ? (total_LOSSPROFITMONEY / total_SELLMONEY * 1000).toFixed(2) + '%' : '', // 损溢率
                                    GROSS_PROFITRATE: total_SELLMONEY ? (total_GROSSMONEY / total_SELLMONEY * 100).toFixed(2) + '%' : '',// 毛利率
                                })


                                return { data: data, success: true }
                            }
                            setCurrentShopInfo(null)
                            return { data: [], success: true }
                        }}
                        toolbar={{
                            actions: isComponents ? [] : [
                                // <span style={{ visibility: 'hidden' }}>
                                //     <ReactHTMLTableToExcel
                                //         buttonText={'导出excel'}
                                //         ref={downloadBtnRef}
                                //         table="table-to-xls-InventoryDetails"
                                //         filename={`进销存明细报表${searchParams?.InventoryTime || ""}`}
                                //         sheet="sheet1"
                                //     />
                                // </span>,
                                <Button
                                    key="new"
                                    type="primary"
                                    onClick={(e) => {
                                        if (reqDetailList && reqDetailList.length > 0) {
                                            // 尝试一下 导出新方法 
                                            exportXlsxFromProColumnsExcelJS(isComponents ? [...columns, ...columnsType1] : currentDataType === '1' ? [...columns, ...columnsType1] : currentDataType === '2' ? [...columns, ...columnsType2] : [],
                                                reqDetailList,
                                                `进销存明细报表${searchParams?.InventoryTime || ""}`,
                                                {
                                                    topTitle: `${currentShopInfo?.SERVERPART_NAME}${currentShopInfo?.SHOPNAME}进销存报表`, // 顶部大标题
                                                    infoRowLeft: `统计方式：按成本结算(${currentDataType === '1' ? '含税' : '除税'})`,//左侧文字
                                                    footerMaker: currentUser?.Name,
                                                    footerMakerTime: moment().format('YYYY-MM-DD HH:mm:ss'),
                                                    footerStatsTime: ""
                                                }
                                            )
                                        } else {
                                            message.error('暂无数据可导出！')
                                        }

                                        // if (reqDetailList && reqDetailList.length > 0) {
                                        //     setShowLoading(true)
                                        //     setTimeout(() => {
                                        //         setShowExportTable(true)
                                        //         setTimeout(() => {
                                        //             exportTable(e)
                                        //         }, 100)
                                        //     }, 100)
                                        // } else {
                                        //     message.error('暂无数据可导出！')
                                        // }
                                    }}
                                >
                                    导出excel
                                </Button>
                            ]
                        }}
                        summary={() => {
                            return (
                                <ProTable.Summary fixed="top">
                                    <ProTable.Summary.Row>
                                        <ProTable.Summary.Cell index={0} colSpan={5} align="center">总合计</ProTable.Summary.Cell>
                                        <ProTable.Summary.Cell index={1} align="right">{tableSummary?.OVERPLUSCOUNT ? Number(tableSummary?.OVERPLUSCOUNT).toLocaleString('zh-CN') : "0"}</ProTable.Summary.Cell>
                                        <ProTable.Summary.Cell index={2} align="right">{tableSummary?.OVERPLUS_AMOUNT ? Number(tableSummary?.OVERPLUS_AMOUNT).toLocaleString('zh-CN') : "0"}</ProTable.Summary.Cell>
                                        <ProTable.Summary.Cell index={3} align="right">{tableSummary?.LOSSPROFIT_COUNT ? Number(tableSummary?.LOSSPROFIT_COUNT).toLocaleString('zh-CN') : "0"}</ProTable.Summary.Cell>
                                        <ProTable.Summary.Cell index={4} align="right">{tableSummary?.LOSSPROFIT_AMOUNT ? Number(tableSummary?.LOSSPROFIT_AMOUNT).toLocaleString('zh-CN') : "0"}</ProTable.Summary.Cell>
                                        <ProTable.Summary.Cell index={5} align="right">{tableSummary?.LOSSPROFIT_RATE || ""}</ProTable.Summary.Cell>
                                        <ProTable.Summary.Cell index={6} align="right">{tableSummary?.GROSS_PROFIT ? Number(tableSummary?.GROSS_PROFIT).toLocaleString('zh-CN') : "0"}</ProTable.Summary.Cell>
                                        <ProTable.Summary.Cell index={7} align="right">{tableSummary?.GROSS_PROFITRATE || ""}</ProTable.Summary.Cell>
                                        <ProTable.Summary.Cell index={8} align="right">{tableSummary?.LAST_OVERPLUSCOUNT ? Number(tableSummary?.LAST_OVERPLUSCOUNT).toLocaleString('zh-CN') : "0"}</ProTable.Summary.Cell>
                                        <ProTable.Summary.Cell index={9} align="right">{tableSummary?.LAST_OVERPLUSAMOUNT ? Number(tableSummary?.LAST_OVERPLUSAMOUNT).toLocaleString('zh-CN') : "0"}</ProTable.Summary.Cell>
                                        <ProTable.Summary.Cell index={10} align="right">{tableSummary?.PURCHASE_COUNT ? Number(tableSummary?.PURCHASE_COUNT).toLocaleString('zh-CN') : "0"}</ProTable.Summary.Cell>
                                        <ProTable.Summary.Cell index={11} align="right">{tableSummary?.PURCHASE_TOTALTAXPRICE ? Number(tableSummary?.PURCHASE_TOTALTAXPRICE).toLocaleString('zh-CN') : "0"}</ProTable.Summary.Cell>
                                        <ProTable.Summary.Cell index={12} align="right">{tableSummary?.SELL_COUNT ? Number(tableSummary?.SELL_COUNT).toLocaleString('zh-CN') : "0"}</ProTable.Summary.Cell>
                                        <ProTable.Summary.Cell index={13} align="right">{ }</ProTable.Summary.Cell>
                                        <ProTable.Summary.Cell index={14} align="right">{tableSummary?.SELL_TOTALTAXPRICE ? Number(tableSummary?.SELL_TOTALTAXPRICE).toLocaleString('zh-CN') : "0"}</ProTable.Summary.Cell>
                                        <ProTable.Summary.Cell index={15} align="right">{tableSummary?.SELL_COST ? Number(tableSummary?.SELL_COST).toLocaleString('zh-CN') : "0"}</ProTable.Summary.Cell>
                                        <ProTable.Summary.Cell index={16} align="right">{tableSummary?.TRANSFER_COUNT ? Number(tableSummary?.TRANSFER_COUNT).toLocaleString('zh-CN') : "0"}</ProTable.Summary.Cell>
                                        <ProTable.Summary.Cell index={17} align="right">{tableSummary?.TRANSFER_AMOUNT ? Number(tableSummary?.TRANSFER_AMOUNT).toLocaleString('zh-CN') : "0"}</ProTable.Summary.Cell>
                                        <ProTable.Summary.Cell index={18} align="right">{tableSummary?.RECEIVE_COUNT ? Number(tableSummary?.RECEIVE_COUNT).toLocaleString('zh-CN') : "0"}</ProTable.Summary.Cell>
                                        <ProTable.Summary.Cell index={19} align="right">{tableSummary?.RECEIVE_AMOUNT ? Number(tableSummary?.RECEIVE_AMOUNT).toLocaleString('zh-CN') : "0"}</ProTable.Summary.Cell>
                                        <ProTable.Summary.Cell index={20} align="right">{tableSummary?.BACK_COUNT ? Number(tableSummary?.BACK_COUNT).toLocaleString('zh-CN') : "0"}</ProTable.Summary.Cell>
                                        <ProTable.Summary.Cell index={21} align="right">{tableSummary?.BACK_AMOUNT ? Number(tableSummary?.BACK_AMOUNT).toLocaleString('zh-CN') : "0"}</ProTable.Summary.Cell>
                                    </ProTable.Summary.Row>
                                </ProTable.Summary>
                            );
                        }}
                    />
                </div>
            </div>

            {/* 进销存明细的悬浮框 */}
            <InventoryDetailModal onShow={showDetail} parentRow={currentRow} onCancel={handleModalCancel} />

        </div>
    )
}

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