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 PageTitleBox from "@/components/PageTitleBox";
import moment from "moment";
import { handleGetMERCHANTSList, handleGetStorageBackSummary } from "../service";
import { exportXlsxFromProColumnsExcelJS } from "@/utils/exportExcelFun";
import { formatTreeData, sortTreeData } from "@/utils/format";


const purchaseReceiving: 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 [reqDefaultDetailList, setReqDefaultDetailList] = 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>()
    // 拿到服务区下的所有门店id集合
    const [handleAllShopId, sethandleAllShopId] = useState<any>()
    // 判断是不是点击了 排序、分页等
    const isNoTableReload = useRef<boolean>(false)
    // 表格数据
    const [tableData, setTableData] = useState<any>()

    const columns: any = [
        {
            title: '统计时间',
            dataIndex: 'search_date',
            valueType: 'dateRange',
            hideInTable: true,
            hideInDescriptions: true,
            search: {
                transform: (value) => {
                    return {
                        StartDate: value[0],
                        EndDate: value[1],
                    };
                },
            },
            fieldProps: {
                ranges: {
                    "本月": [moment().startOf('M'), moment()],
                    "上月": [moment().subtract(1, 'M').startOf('M'), moment().subtract(1, 'M').endOf('M')],
                    "近三月": [moment().subtract(3, 'M').startOf('M'), moment().endOf('M')],
                    "近半年": [moment().subtract(6, 'M').startOf('M'), moment().endOf('M')],
                }
            },
            initialValue: [moment().startOf('M'), moment()],
        },
        {
            title: "供应商",
            dataIndex: "SupplierId",
            valueType: 'select',
            request: async () => {
                const req: any = {
                    SearchParameter: {
                        PROVINCE_CODE: currentUser?.ProvinceCode,
                        MERCHANTS_STATE: 1
                    },
                    PageIndex: 1,
                    PageSize: 999999

                }
                const data = await handleGetMERCHANTSList(req)
                console.log('datadatadatadata', data);
                let list: any = []
                if (data && data.length > 0) {
                    data.forEach((item: any) => {
                        list.push({ label: item.MERCHANTS_NAME, value: item.MERCHANTS_ID })
                    })

                    list.unshift({ label: "全部", value: "" })
                }
                return list
            },
            fieldProps: {
                showSearch: true,
                filterOption: (input: any, option: any) => (option?.label ?? '').toLowerCase().includes(input.toLowerCase()),
            },
            initialValue: "",
            hideInTable: true,
        },
        {
            title: "序号",
            dataIndex: "index",
            valueType: 'index',
            align: 'center',
            width: 90,
            ellipsis: true,
            hideInSearch: true,
        },
        {
            title: <div style={{ textAlign: 'center' }}>供应商/服务区名</div>,
            dataIndex: "Serverpart_Name",
            align: 'left',
            width: 200,
            ellipsis: true,
            hideInSearch: true,
            render: (_, record) => {
                return record?.Serverpart_Name || record?.Supplier_Name
            }
        },
        {
            title: <div style={{ textAlign: 'center' }}>门店名称</div>,
            dataIndex: "ServerpartShop_Name",
            align: 'center',
            width: 150,
            ellipsis: true,
            hideInSearch: true,
        },
        {
            title: <div style={{ textAlign: 'center' }}>商品名称</div>,
            dataIndex: "Commodity_Name",
            align: 'left',
            width: 200,
            ellipsis: true,
            hideInSearch: true,
        },

        // defaultSortOrder: 'descend',
        // 如果要默认排序的话 默认的那一项 要在导出里面单独去写
        {
            title: <div style={{ textAlign: 'center' }}>采购总数量</div>,
            dataIndex: "Storage_Count",
            align: 'right',
            valueType: 'digit',
            width: 120,
            sorter: (a, b) => a.Storage_Count - b.Storage_Count,
            ellipsis: true,
            hideInSearch: true,
        },
        {
            title: <div style={{ textAlign: 'center' }}>采购含税金额</div>,
            dataIndex: "Storage_TaxAmount",
            align: 'right',
            valueType: 'digit',
            width: 120,
            sorter: (a, b) => a.Storage_TaxAmount - b.Storage_TaxAmount,
            ellipsis: true,
            hideInSearch: true,
        },
        {
            title: <div style={{ textAlign: 'center' }}>采购除税金额</div>,
            dataIndex: "Storage_Amount",
            align: 'right',
            valueType: 'digit',
            width: 120,
            sorter: (a, b) => a.Storage_Amount - b.Storage_Amount,
            ellipsis: true,
            hideInSearch: true,
        },
        {
            title: <div style={{ textAlign: 'center' }}>退货数量</div>,
            dataIndex: "Back_Count",
            align: 'right',
            valueType: 'digit',
            width: 120,
            sorter: (a, b) => a.Back_Count - b.Back_Count,
            ellipsis: true,
            hideInSearch: true,
        },
        {
            title: <div style={{ textAlign: 'center' }}>退货含税金额</div>,
            dataIndex: "Back_TaxAmount",
            align: 'right',
            valueType: 'digit',
            width: 120,
            sorter: (a, b) => a.Back_TaxAmount - b.Back_TaxAmount,
            ellipsis: true,
            hideInSearch: true,
        },
        {
            title: <div style={{ textAlign: 'center' }}>退货除税金额</div>,
            dataIndex: "Back_Amount",
            align: 'right',
            valueType: 'digit',
            width: 120,
            sorter: (a, b) => a.Back_Amount - b.Back_Amount,
            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 tempTable = document.createElement('table');
        tempTable.appendChild(thead);
        tempTable.appendChild(tbody);

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

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

        setShowLoading(false)

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

    const exportColumns: any = [
        {
            title: "序号",
            dataIndex: "index",
            valueType: 'index',
            align: 'center',
            width: 90,
            ellipsis: true,
            hideInSearch: true,
        },
        {
            title: <div style={{ textAlign: 'center' }}>服务区名</div>,
            dataIndex: "Serverpart_Name",
            align: 'left',
            width: 200,
            ellipsis: true,
            hideInSearch: true,
        },
        {
            title: <div style={{ textAlign: 'center' }}>供应商名</div>,
            dataIndex: "Supplier_Name",
            align: 'left',
            width: 200,
            ellipsis: true,
            hideInSearch: true,
        },
        {
            title: <div style={{ textAlign: 'center' }}>门店名称</div>,
            dataIndex: "ServerpartShop_Name",
            align: 'center',
            width: 150,
            ellipsis: true,
            hideInSearch: true,
        },
    ]

    type SortState = { field?: string; order?: 'ascend' | 'descend' };
    type KeyOf<T> = Extract<keyof T, string>;

    interface SortTreeOptions<T = any> {
        childrenKey?: KeyOf<T>;      // 子节点字段名，默认 'children'
    }

    /** 树形排序：父与父排，父内的子与子排（递归） */
    const sortListByState = <T extends Record<string, any>>(
        list: T[] = [],
        state?: SortState,
        options?: SortTreeOptions<T>
    ): T[] => {
        const { childrenKey = 'children' } = options || {};

        // 拷贝数组，避免改原数据
        const arr = Array.isArray(list) ? list.slice() : [];
        if (!state?.field || !state?.order) {
            // 即便无排序条件也返回副本，避免引用共享
            return arr.map(cloneNode);
        }

        const { field, order } = state;
        const factor = order === 'ascend' ? 1 : -1;

        // 取可比较值：数值 > 时间 > 字符串 > 其它；null/undefined 放最后
        const getComparable = (v: any) => {
            if (v == null) return { type: 9, v: Number.POSITIVE_INFINITY };
            if (typeof v === 'number') return { type: 0, v };
            if (v instanceof Date) return { type: 1, v: v.getTime() };
            if (typeof v === 'string') {
                const t = Date.parse(v);
                if (!Number.isNaN(t)) return { type: 1, v: t };
                const n = Number(v);
                if (!Number.isNaN(n) && v.trim() !== '' && String(n) === v.trim()) {
                    return { type: 0, v: n };
                }
                return { type: 2, v };
            }
            return { type: 3, v: String(v) };
        };

        // 比较器：同层内比较 field，值相等用原始下标保证稳定
        const withIndex = arr.map((item, idx) => ({ item, idx }));

        const compare = (a: any, b: any) => {
            const va = getComparable(a?.[field as string]);
            const vb = getComparable(b?.[field as string]);

            if (va.type !== vb.type) return (va.type - vb.type) * factor;
            if (va.v < vb.v) return -1 * factor;
            if (va.v > vb.v) return 1 * factor;
            return 0; // 真正稳定通过 map 阶段的 idx 来保证
        };

        // 顶层排序（父与父）
        const topSorted = withIndex
            .slice()
            .sort((A, B) => {
                const c = compare(A.item, B.item);
                return c !== 0 ? c : A.idx - B.idx;
            })
            .map(({ item }) => item);

        // 递归对子节点排序（每个父内子与子）
        return topSorted.map((node) => {
            const cloned = cloneNode(node);
            const children = cloned?.[childrenKey] as T[] | undefined;

            if (Array.isArray(children) && children.length) {
                // 同样做稳定排序
                const childrenWithIndex = children.map((ch, i) => ({ ch, i }));
                const childSorted = childrenWithIndex
                    .slice()
                    .sort((A, B) => {
                        const c = compare(A.ch, B.ch);
                        return c !== 0 ? c : A.i - B.i;
                    })
                    .map(({ ch }) => ch);

                // 递归：若还有下一级，继续排
                cloned[childrenKey] = sortListByState(childSorted, state, { childrenKey });
            }

            return cloned;
        });

        function cloneNode<N extends Record<string, any>>(n: N): N {
            if (!n || typeof n !== 'object') return n;
            const c: any = { ...n };
            // children 数组引用也要分离（排序时会重建，保险起见先浅拷贝）
            if (Array.isArray(c[childrenKey])) c[childrenKey] = c[childrenKey].slice();
            return c;
        }
    };

    const isParent = (r: any) => !r?.Commodity_Id;
    // 父级行合并单元格里要显示的自定义内容（你可按需改）
    const renderParentCell = (record: any) => {
        // 你可以自由拼接：服务区/供应商/门店等
        return (
            <div style={{ paddingLeft: 8, fontWeight: 600 }}>
                {record?.Supplier_Name}-{record?.Serverpart_Name}-{record?.ServerpartShop_Name}合计
            </div>
        );
    };
    const EXPORT_COLSPAN = exportColumns.length;
    const mergedExportColumns = [
        {
            ...exportColumns[0],
            // 第一列：父级→合并整段导出列；子级→显示序号（原 valueType:'index' 需手动展示）
            render: (_: any, record: any, index: number) => {
                if (isParent(record)) {
                    return {
                        children: renderParentCell(record),
                        props: { colSpan: EXPORT_COLSPAN },
                    };
                }
                // 子级：正常显示序号
                return { children: index + 1, props: {} };
            },
        },
        // 其余导出列：父级隐藏（colSpan:0），子级正常显示
        ...exportColumns.slice(1).map((col: any) => ({
            ...col,
            render: (text: any, record: any) => {
                if (isParent(record)) {
                    return { children: null, props: { colSpan: 0 } };
                }
                return { children: text, props: {} };
            },
        })),
    ];


    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={[...mergedExportColumns, ...columns.slice(5, columns.length)]}
                            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} setAllServiceShop={sethandleAllShopId} collapsible={collapsible} pageType={'ahjg'} collapsibleTitle={'请选择门店'} />
                <div style={{
                    width: !collapsible ? 'calc(100% - 300px)' : 'calc(100% - 60px)',
                    paddingTop: 0,
                    paddingBottom: 0,
                    paddingRight: 0
                }}>
                    <ProTable
                        actionRef={actionRef}
                        formRef={formRef}
                        columns={columns}
                        bordered
                        expandable={{
                            expandRowByClick: true
                        }}
                        rowKey={(record: any) => {
                            return `${record?.Supplier_Id}-${record?.Serverpart_Id}-${record?.ServerpartShop_Name}-${record?.Commodity_Id}-${record?.Commodity_BarCode}`
                        }}
                        scroll={{ x: "100%", y: "calc(100vh - 410px)" }}
                        headerTitle={<PageTitleBox props={props} />} // 列表表头
                        search={{ span: 6 }}
                        dataSource={tableData}
                        request={async (params, sorter) => {
                            console.log('selectedIdselectedIdselectedId', selectedId);

                            if (!selectedId || isNoTableReload.current) {
                                isNoTableReload.current = false
                                return
                            }

                            // 根据门店去判断 是哪个服务区里面的 再把服务区的id 记录下来 而且要去重
                            let serverpartId: any = []

                            if (selectedId) {
                                let list: any = selectedId.split(',')
                                if (list && list.length > 0) {
                                    list.forEach((item: any) => {
                                        for (let key in handleAllShopId) {
                                            if (handleAllShopId[key] && handleAllShopId[key].length > 0) {
                                                if (handleAllShopId[key].indexOf(Number(item)) !== -1) {
                                                    if (serverpartId && serverpartId.length > 0) {
                                                        if (serverpartId.indexOf(key) === -1) {
                                                            serverpartId.push(key)
                                                        }
                                                    } else {
                                                        serverpartId.push(key)
                                                    }
                                                }
                                            }
                                        }
                                    })
                                }
                            }
                            // 排序字段
                            const sortstr = Object.keys(sorter).map(n => {
                                const value = sorter[n]
                                return value ? `${n} ${value.replace('end', '')}` : ''
                            })
                            const req: any = {
                                ServerpartId: serverpartId && serverpartId.length > 0 ? serverpartId.toString() : "",
                                ServerpartShopId: selectedId,
                                SupplierId: params?.SupplierId || "",
                                StartDate: params?.StartDate || "",
                                EndDate: params?.EndDate || "",
                                SearchKeyName: "",
                                SearchKeyValue: "",
                                // sortstr: sortstr.length ? sortstr.toString() : "",
                            }
                            setSearchParams(params)

                            const data = await handleGetStorageBackSummary(req)
                            console.log('dafjkdjaf', data);
                            if (data && data.length > 0) {
                                let exportList: any = []
                                data.forEach((item: any) => {
                                    if (item.children && item.children.length > 0) {
                                        item.children.forEach((subItem: any) => {
                                            let newChildren: any = []
                                            if (subItem.children && subItem.children.length > 0) {
                                                subItem.children.forEach((thirdItem: any) => {
                                                    // exportList.push(thirdItem)
                                                    newChildren.push(thirdItem)
                                                })
                                            }
                                            subItem.children = newChildren
                                            exportList.push(subItem)
                                        })
                                    }
                                })


                                let sorterList: any = sortTreeData(JSON.parse(JSON.stringify(exportList)), sortstr.toString())

                                let fieldData: any = [
                                    "Storage_Count",
                                    "Storage_TaxAmount",
                                    "Storage_Amount",
                                    "Back_Count",
                                    "Back_TaxAmount",
                                    "Back_Amount",
                                ]

                                let enumList: any = []
                                let newPrintData: any = formatTreeData(JSON.parse(JSON.stringify(sorterList)), fieldData, enumList, [], [])


                                setReqDetailList(newPrintData)
                                setReqDefaultDetailList(exportList)
                                setTableData(data)
                                // return { data, success: true }
                            } else {
                                setTableData([])
                                // return { data: [], success: true }
                            }
                        }}
                        toolbar={{
                            actions: [
                                // <span style={{ visibility: 'hidden' }}>
                                //     <ReactHTMLTableToExcel
                                //         buttonText={'导出excel'}
                                //         ref={downloadBtnRef}
                                //         table="table-to-xls-purchaseReceiving"
                                //         filename={`入库退货统计表${searchParams?.StartDate}-${searchParams?.EndDate}`}
                                //         sheet="sheet1"
                                //     />
                                // </span>,
                                <Button
                                    key="new"
                                    type="primary"
                                    onClick={(e) => {
                                        console.log('reqDetailListreqDetailListreqDetailList', reqDetailList);
                                        if (reqDetailList && reqDetailList.length > 0) {
                                            // 尝试一下 导出新方法 
                                            exportXlsxFromProColumnsExcelJS(columns,
                                                reqDetailList,
                                                `入库退货统计表${searchParams?.StartDate}-${searchParams?.EndDate}`,
                                                {
                                                    topTitle: `入库退货统计表`, // 顶部大标题
                                                    footerMaker: currentUser?.Name,
                                                    footerMakerTime: moment().format('YYYY-MM-DD HH:mm:ss'),
                                                    footerStatsTime: `${searchParams?.StartDate}-${searchParams?.EndDate}`
                                                }
                                            )
                                        } else {
                                            message.error('暂无数据可导出！')
                                        }
                                        // if (reqDetailList && reqDetailList.length > 0) {
                                        //     setShowLoading(true)
                                        //     setTimeout(() => {
                                        //         setShowExportTable(true)
                                        //         setTimeout(() => {
                                        //             exportTable(e)
                                        //         }, 100)
                                        //     }, 100)
                                        // } else {
                                        //     message.error('暂无数据可导出！')
                                        // }
                                    }}
                                >
                                    导出excel
                                </Button>
                            ]
                        }}
                        onChange={(_pagination: any, _filters: any, sorter: any, extra: any) => {
                            isNoTableReload.current = true
                            if (extra?.action === 'sort') {
                                const field = Array.isArray(sorter) ? sorter[0]?.field : sorter?.field;
                                const order = Array.isArray(sorter) ? sorter[0]?.order : sorter?.order;
                                const newList: any = sortListByState(reqDefaultDetailList, { field, order }, { childrenKey: 'children' })

                                let fieldData: any = [
                                    "Storage_Count",
                                    "Storage_TaxAmount",
                                    "Storage_Amount",
                                    "Back_Count",
                                    "Back_TaxAmount",
                                    "Back_Amount",
                                ]

                                let enumList: any = []
                                let newPrintData: any = formatTreeData(JSON.parse(JSON.stringify(newList)), fieldData, enumList, [], [])

                                setReqDetailList(newPrintData)
                            }
                        }}
                    />
                </div>
            </div>
        </div>
    )
}

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