import { connect } from "umi";
import type { ConnectState } from "@/models/connect";
import { Button, Descriptions, FormInstance, message, Modal, Spin, Table } from "antd";
import { useRef, useState } from "react";
import React from "react";
import Draggable from "react-draggable";
import ProTable, { ActionType } from "@ant-design/pro-table";
import ReactHTMLTableToExcel from "react-html-table-to-excel";
import { handleGetRECEIVEDETAILSERVERPARTList, handleGetRECEIVESERVERPARTDetail } from "../../service";
import { highlightText } from "@/utils/highlightText";
import { exportXlsxFromProColumnsExcelJS } from "@/utils/exportExcelFun";

type DetailProps = {
    onShow: boolean;
    parentRow: any;
    onCencel: any
    searchParams?: any // 如果需要高亮查询文字  这个就有值
}
const warehouseInfo = ({ onShow, parentRow, onCencel, searchParams }: DetailProps) => {
    const actionRef = useRef<ActionType>();
    const formRef = useRef<FormInstance>();
    const draggleRef = React.createRef<any>()
    const downloadBtnRef = useRef<any>()

    // 当前的入库单详情信息
    const [currentModalDetail, setCurrentModalDetail] = useState<any>()
    const [reqDetailList, setReqDetailList] = useState<any>(); // 合计项数据源
    // 是否显示打印的表格
    const [showExportTable, setShowExportTable] = useState<boolean>(false)
    // 导出的加载效果
    const [showLoading, setShowLoading] = useState<boolean>(false)
    const [printIndex, setPrintIndex] = useState<number>(new Date().getTime())
    // 表格数据合计
    const [tableDataSum, setTableDataSum] = useState<any>()

    // 弹出框拖动效果
    const [bounds, setBounds] = useState<{ left: number, right: number, top: number, bottom: number }>() // 移动的位置
    const [disabled, setDraggleDisabled] = useState<boolean>() // 是否拖动
    const onDraggaleStart = (event, uiData) => {
        const { clientWidth, clientHeight } = window.document.documentElement;
        const targetRect = draggleRef.current?.getBoundingClientRect();
        if (!targetRect) {
            return;
        }
        setBounds({
            left: -targetRect.left + uiData.x,
            right: clientWidth - (targetRect.right - uiData.x),
            top: -targetRect.top + uiData.y,
            bottom: clientHeight - (targetRect.bottom - uiData.y),
        });
    };

    const columns: any = [
        {
            title: "序号",
            dataIndex: "index",
            valueType: 'index',
            align: 'center',
            width: 80,
            ellipsis: true,
            hideInSearch: true,
        },
        {
            title: <div style={{ textAlign: 'center' }}>商品名称</div>,
            dataIndex: "COMMODITY_NAME",
            align: 'left',
            width: 200,
            ellipsis: true,
            hideInSearch: true,
            render: (_, record) => {
                return highlightText(record?.COMMODITY_NAME, searchParams?.searchText)
            }
        },
        {
            title: <div style={{ textAlign: 'center' }}>商品条码</div>,
            dataIndex: "COMMODITY_BARCODE",
            align: 'left',
            width: 120,
            ellipsis: true,
            hideInSearch: true,
            render: (_, record) => {
                return highlightText(record?.COMMODITY_BARCODE, searchParams?.searchText)
            }
        },
        {
            title: <div style={{ textAlign: 'center' }}>商品规格</div>,
            dataIndex: "COMMODITY_RULE",
            align: 'left',
            width: 120,
            ellipsis: true,
            hideInSearch: true,
        },
        {
            title: <div style={{ textAlign: 'center' }}>入库总数</div>,
            dataIndex: "DELIVERCOUNT",
            align: 'right',
            valueType: 'digit',
            width: 120,
            ellipsis: true,
            hideInSearch: true,
        },
        {
            title: <div style={{ textAlign: 'center' }}>进价税率</div>,
            dataIndex: "DUTY_PARAGRAPH",
            align: 'right',
            width: 120,
            ellipsis: true,
            hideInSearch: true,
        },
        {
            title: <div style={{ textAlign: 'center' }}>含税进价</div>,
            dataIndex: "PURCHASE_TAXPRICE",
            align: 'right',
            valueType: 'digit',
            width: 120,
            ellipsis: true,
            hideInSearch: true,
        },
        {
            title: <div style={{ textAlign: 'center' }}>合计含税金额</div>,
            dataIndex: "RECEIVE_TOTALPRICE",
            align: 'right',
            valueType: 'digit',
            width: 120,
            ellipsis: true,
            hideInSearch: true,
        },
        {
            title: <div style={{ textAlign: 'center' }}>零售单价</div>,
            dataIndex: "SUPPORT_PRICE",
            align: 'right',
            valueType: 'digit',
            width: 120,
            ellipsis: true,
            hideInSearch: true,
        },
        {
            title: <div style={{ textAlign: 'center' }}>零售金额</div>,
            dataIndex: "PURCHASE_TAXSELLPRICE",
            align: 'right',
            valueType: 'digit',
            width: 120,
            ellipsis: true,
            hideInSearch: true,
        }
    ]


    const exportTable = (e) => {
        e.stopPropagation();

        const main = document.getElementsByClassName(`warehouseInfo${printIndex}`)[0];
        const thead = main.querySelector('thead').cloneNode(true);
        const tbody = main.querySelector('tbody').cloneNode(true);
        const tfoot = main.querySelector('tfoot').cloneNode(true);  // 深克隆DOM节点
        const container = document.querySelector('#hiddenBox');
        const tempTable = document.createElement('table');

        const title = document.createElement('div');
        title.innerText = `${currentModalDetail?.SERVERPART_NAME || ''}${currentModalDetail?.SHOPNAME || ''}入库单`;
        title.setAttribute('style', 'width:100%;text-align:center;font-size:20px;font-weight: 600;')

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

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

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

        setShowLoading(false)

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

    };


    return (
        <div>
            <div className={`warehouseInfo${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
                            }}
                            summary={() => {
                                return (
                                    <ProTable.Summary fixed="bottom">
                                        <ProTable.Summary.Cell index={0} colSpan={4} align="center">合计</ProTable.Summary.Cell>
                                        <ProTable.Summary.Cell index={1} colSpan={1} align="right">{tableDataSum?.DELIVERCOUNT || ""}</ProTable.Summary.Cell>
                                        <ProTable.Summary.Cell index={2} colSpan={1} align="right"></ProTable.Summary.Cell>
                                        <ProTable.Summary.Cell index={3} colSpan={1} align="right"></ProTable.Summary.Cell>
                                        <ProTable.Summary.Cell index={4} colSpan={1} align="right">{tableDataSum?.RECEIVE_TOTALPRICE || ""}</ProTable.Summary.Cell>
                                        <ProTable.Summary.Cell index={5} colSpan={1} align="right"></ProTable.Summary.Cell>
                                        <ProTable.Summary.Cell index={6} colSpan={1} align="right">{tableDataSum?.PURCHASE_TAXSELLPRICE || ""}</ProTable.Summary.Cell>
                                    </ProTable.Summary>
                                )
                            }}
                        /> : ''
                }
            </div>
            <div id='hiddenBox' style={{ position: 'fixed', zIndex: -1, top: 0, left: 0 }} />

            <Modal
                title={
                    <div
                        className="warehouseInfoTitle"
                        style={{
                            width: '100%',
                            cursor: 'move',
                        }}
                        onMouseOver={() => {
                            if (disabled) {
                                setDraggleDisabled(false)
                            }
                        }}
                        onMouseOut={() => {
                            setDraggleDisabled(true)
                        }}

                        onFocus={() => { }}
                        onBlur={() => { }}
                    >入库信息</div>
                }
                destroyOnClose={true}
                width={'80%'}
                bodyStyle={{
                    height: '700px', // 你可以根据需要调整高度
                    overflowY: 'auto',
                }}
                visible={onShow}
                onCancel={() => {
                    if (onCencel) {
                        onCencel()
                    }
                }}
                footer={false}
                modalRender={(modal) => {
                    return <Draggable
                        disabled={disabled}
                        bounds={bounds}
                        onStart={(event, uiData) => onDraggaleStart(event, uiData)}
                        handle=".warehouseInfoTitle"
                    >
                        <div ref={draggleRef}>{modal}</div>
                    </Draggable>
                }}
            >
                <div style={{ fontSize: '28px', width: '100%', display: 'flex', alignItems: 'center', justifyContent: 'center', padding: '10px 0', fontWeight: 600 }}>{`${parentRow?.SERVERPART_NAME}入库验收单`}</div>

                <ProTable
                    actionRef={actionRef}
                    formRef={formRef}
                    columns={columns}
                    bordered
                    scroll={{ x: '100%', y: 270 }}
                    search={false}
                    options={false}
                    request={async (params) => {
                        // 接收单明细
                        const req: any = {
                            RECEIVESERVERPARTId: parentRow?.RECEIVESERVERPART_ID
                        }
                        const data = await handleGetRECEIVESERVERPARTDetail(req)
                        console.log('datadatadata', data);
                        setCurrentModalDetail(data)


                        // 表格数据 即 入库单里面的具体商品信息
                        const shopReq: any = {
                            SearchParameter: {
                                RECEIVESERVERPART_IDS: parentRow?.RECEIVESERVERPART_ID
                            },
                            PageIndex: 1,
                            PageSize: 999999
                        }

                        const shopData: any = await handleGetRECEIVEDETAILSERVERPARTList(shopReq)
                        console.log('shopDatashopDatashopDatashopData', shopData);
                        setReqDetailList(shopData)
                        if (shopData && shopData.length > 0) {
                            let DELIVERCOUNTSUM: number = 0 // 入库总数
                            let RECEIVE_TOTALPRICESUM: number = 0 // 合计含税金额
                            let PURCHASE_TAXSELLPRICESUM: number = 0 // 零售金额

                            shopData.forEach((item: any) => {
                                DELIVERCOUNTSUM += item.DELIVERCOUNT
                                RECEIVE_TOTALPRICESUM += item.RECEIVE_TOTALPRICE
                                PURCHASE_TAXSELLPRICESUM += item.PURCHASE_TAXSELLPRICE
                            })

                            setTableDataSum({
                                DELIVERCOUNT: Number(DELIVERCOUNTSUM.toFixed(2)).toLocaleString('zh-CN'),
                                RECEIVE_TOTALPRICE: Number(RECEIVE_TOTALPRICESUM.toFixed(2)).toLocaleString('zh-CN'),
                                PURCHASE_TAXSELLPRICE: Number(PURCHASE_TAXSELLPRICESUM.toFixed(2)).toLocaleString('zh-CN')
                            })

                            return { data: shopData, success: true }
                        }
                        setTableDataSum(null)
                        return { data: [], success: true }
                    }}
                    tableExtraRender={(_, data) => {
                        return <div>
                            <Descriptions
                                size="small" column={4}
                                className="commity-sale-description"
                                contentStyle={{ fontWeight: "bolder" }} labelStyle={{ color: "#00000073" }}
                            >
                                <Descriptions.Item label="门店名称">{currentModalDetail?.SHOPNAME || ""}</Descriptions.Item>
                                <Descriptions.Item label="入库单号">{currentModalDetail?.RECEIVECENTER_CODE || ""}</Descriptions.Item>
                                <Descriptions.Item label="入库时间">{currentModalDetail?.RECEIVECENTER_DATE || ""}</Descriptions.Item>
                                <Descriptions.Item label="入库说明">{currentModalDetail?.RECEIVESERVERPART_DESC || ""}</Descriptions.Item>

                                <Descriptions.Item label="入库总数">{currentModalDetail?.RECEIVE_TOTALCOUNT.toLocaleString('zh-CN') || ""}</Descriptions.Item>
                                <Descriptions.Item label="合计含税金额">{currentModalDetail?.RECEIVE_TOTALPRICE.toLocaleString('zh-CN') || ""}</Descriptions.Item>
                                <Descriptions.Item label="零售金额">{""}</Descriptions.Item>


                            </Descriptions>
                        </div>
                    }}
                    toolbar={{
                        actions: [
                            <span style={{ visibility: 'hidden' }}>
                                <ReactHTMLTableToExcel
                                    buttonText={'导出excel'}
                                    ref={downloadBtnRef}
                                    table="table-to-xls-warehouseInfo"
                                    filename={`${parentRow?.SERVERPART_NAME}入库验收单${parentRow?.RECEIVECENTER_DATE || ""}`}
                                    sheet="sheet1"
                                />
                            </span>,
                            <Button
                                key="new"
                                type="primary"
                                loading={showLoading}
                                onClick={(e) => {
                                    if (reqDetailList && reqDetailList.length > 0) {
                                        // 尝试一下 导出新方法 
                                        exportXlsxFromProColumnsExcelJS(columns,
                                            reqDetailList,
                                            `${parentRow?.SERVERPART_NAME}入库验收单${parentRow?.RECEIVECENTER_DATE || ""}`,
                                            {
                                                topTitle: `${currentModalDetail?.SERVERPART_NAME || ''}${currentModalDetail?.SHOPNAME || ''}入库单`, // 顶部大标题
                                            }
                                        )
                                    } else {
                                        message.error('暂无数据可导出！')
                                    }


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

                        ]
                    }}
                    summary={(pageData) => {
                        let DELIVERCOUNTSUM: number = 0
                        let RECEIVE_TOTALPRICESUM: number = 0
                        let PURCHASE_TAXSELLPRICESUM: number = 0

                        if (pageData && pageData.length > 0) {
                            pageData.forEach((item: any) => {
                                DELIVERCOUNTSUM += item.DELIVERCOUNT
                                RECEIVE_TOTALPRICESUM += item.RECEIVE_TOTALPRICE
                                PURCHASE_TAXSELLPRICESUM += item.PURCHASE_TAXSELLPRICE
                            })
                        }

                        return (
                            <Table.Summary fixed="top">
                                <Table.Summary.Row>
                                    {/* 注意：colSpan 的总和要和列数对齐，否则边框会看起来“不完整” */}
                                    <Table.Summary.Cell index={0} colSpan={4}>
                                        <div style={{ textAlign: 'center', fontWeight: 600 }}>本页合计</div>
                                    </Table.Summary.Cell>

                                    <Table.Summary.Cell index={4}>
                                        <div style={{ textAlign: 'right' }}>
                                            {DELIVERCOUNTSUM ? Number(DELIVERCOUNTSUM.toFixed(2)).toLocaleString('zh-CN') : ""}
                                        </div>
                                    </Table.Summary.Cell>

                                    <Table.Summary.Cell index={5}>
                                        <div style={{ textAlign: 'right' }} />
                                    </Table.Summary.Cell>

                                    <Table.Summary.Cell index={6}>
                                        <div style={{ textAlign: 'right' }} />
                                    </Table.Summary.Cell>

                                    <Table.Summary.Cell index={7}>
                                        <div style={{ textAlign: 'right' }}>
                                            {RECEIVE_TOTALPRICESUM ? Number(RECEIVE_TOTALPRICESUM.toFixed(2)).toLocaleString('zh-CN') : ""}
                                        </div>
                                    </Table.Summary.Cell>

                                    <Table.Summary.Cell index={8}>
                                        <div style={{ textAlign: 'right' }} />
                                    </Table.Summary.Cell>

                                    <Table.Summary.Cell index={9}>
                                        <div style={{ textAlign: 'right' }}>
                                            {PURCHASE_TAXSELLPRICESUM ? Number(PURCHASE_TAXSELLPRICESUM.toFixed(2)).toLocaleString('zh-CN') : ""}
                                        </div>
                                    </Table.Summary.Cell>
                                </Table.Summary.Row>
                            </Table.Summary>
                        )
                    }}
                />
            </Modal>
        </div>
    )
}

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