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 { handleGetSALESTOREPROINSTList } from "../service";
import ReturnGoodsTable from "./components/returnGoodsTable";
import { exportXlsxFromProColumnsExcelJS } from "@/utils/exportExcelFun";
import { formatTreeData } from "@/utils/format";


const returnProcess: React.FC<{ currentUser: CurrentUser }> = (props) => {
    const { currentUser } = props
    const downloadBtnRef = useRef<any>()
    const actionRef = useRef<ActionType>();
    const formRef = useRef<FormInstance>();
    const [reqDetailList, setReqDetailList] = useState<any>(); // 合计项数据源
    const [printOut, setPrintOut] = useState<any>(); // 打印数据的内容
    const [collapsible, setCollapsible] = useState<boolean>(false)
    const [treeView, setTreeView] = useState<any>()
    const [printIndex, setPrintIndex] = useState<number>(new Date().getTime())

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

    // 显示配送单
    const [onShow, setOnShow] = useState<boolean>(false)
    // 当前行数据
    const [currentRow, setCurrentRow] = useState<any>()

    const columns: any = [
        {
            dataIndex: 'searchText',
            title: '查询内容',
            hideInTable: true,
            fieldProps: {
                placeholder: "请输入商品名称/商品条码"
            }
        },
        {
            title: '查询时间',
            dataIndex: 'search_date',
            valueType: 'dateRange',
            hideInTable: true,
            hideInDescriptions: true,
            search: {
                transform: (value) => {
                    return {
                        CREATEDATE_Start: value[0],
                        CREATEDATE_End: 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: "",
        //     align: 'center',
        //     valueType: 'select',
        //     width: 120,
        //     ellipsis: true,
        //     hideInTable: true,
        //     fieldProps: {
        //         options: [{ label: "全部", value: '' }, { label: "自采", value: 5 }, { label: "统配", value: 107 }]
        //     },
        //     initialValue: ''
        // },

        {
            title: "序号",
            dataIndex: "index",
            valueType: 'index',
            align: 'center',
            width: 80,
            ellipsis: true,
            hideInSearch: true,
        },
        {
            title: <div style={{ textAlign: 'center' }}>服务区名称</div>,
            dataIndex: "DEPT_NAME",
            align: 'left',
            width: 150,
            ellipsis: true,
            hideInSearch: true,
        },
        // {
        //     title: <div style={{ textAlign: 'center' }}>退货门店</div>,
        //     dataIndex: "",
        //     align: 'center',
        //     width: 150,
        //     ellipsis: true,
        //     hideInSearch: true,
        // },
        // {
        //     title: <div style={{ textAlign: 'center' }}>退货说明</div>,
        //     dataIndex: "PROINST_DESC",
        //     align: 'left',
        //     width: 150,
        //     ellipsis: true,
        //     hideInSearch: true,
        // },
        {
            title: <div style={{ textAlign: 'center' }}>退货数量</div>,
            dataIndex: "OPERATE_COUNT",
            align: 'right',
            width: 150,
            ellipsis: true,
            // sorter: true,
            sorter: (a, b) => a.OPERATE_COUNT - b.OPERATE_COUNT,
            hideInSearch: true,
            render: (_, record) => {
                return <a onClick={() => {
                    console.log('recordrecordrecord', record);

                    setCurrentRow(record)
                    setOnShow(true)
                }}>
                    {record?.OPERATE_COUNT ? record?.OPERATE_COUNT.toLocaleString() : ""}
                </a>
            }
        },
        {
            title: <div style={{ textAlign: 'center' }}>合计含税进价</div>,
            dataIndex: "OPERATE_TAXAMOUNT",
            valueType: 'digit',
            align: 'right',
            width: 150,
            sorter: (a, b) => a.OPERATE_TAXAMOUNT - b.OPERATE_TAXAMOUNT,
            ellipsis: true,
            hideInSearch: true,
        },
        {
            title: <div style={{ textAlign: 'center' }}>合计除税进价</div>,
            dataIndex: "OPERATE_AMOUNT",
            align: 'right',
            valueType: 'digit',
            width: 150,
            sorter: (a, b) => a.OPERATE_AMOUNT - b.OPERATE_AMOUNT,
            ellipsis: true,
            hideInSearch: true,
        },
        // {
        //     title: "待审核人",
        //     dataIndex: "待审核人",
        //     align: 'center',
        //     width: 150,
        //     ellipsis: true,
        //     hideInSearch: true,
        // },
        // {
        //     title: "流程名称",
        //     dataIndex: "流程名称",
        //     align: 'center',
        //     width: 150,
        //     ellipsis: true,
        //     hideInSearch: true,
        // },
        {
            title: "流程开始时间",
            dataIndex: "CREATEDATE",
            align: 'center',
            width: 150,
            sorter: (a, b) => new Date(a.CREATEDATE).getTime() - new Date(b.CREATEDATE).getTime(),
            ellipsis: true,
            hideInSearch: true,
        },
        {
            title: "流程结束时间",
            dataIndex: "ENDDATE",
            align: 'center',
            defaultSortOrder: 'descend',
            width: 150,
            sorter: (a, b) => new Date(a.ENDDATE).getTime() - new Date(b.ENDDATE).getTime(),
            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-returnProcess');                    // 给table添加id，值与按钮上的table字段对应

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

        setShowLoading(false)

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

    // 关闭方法
    const handleCloseModal = () => {
        setCurrentRow(null)
        setOnShow(false)
    }

    return (
        <div ref={(el) => {
            // 打印报表
            if (!reqDetailList || reqDetailList.length === 0) return;
            setPrintOut(el);
        }} >

            {
                showLoading ?
                    <div
                        style={{
                            width: '100%',
                            height: '100%',
                            background: 'rgba(0,0,0,0.1)',
                            position: 'fixed',
                            zIndex: 5,
                            display: 'flex',
                            alignItems: 'center',
                            justifyContent: 'center'
                        }}
                    >
                        <div style={{
                            display: 'flex',
                            alignItems: 'center',
                            justifyContent: 'center',
                            padding: '15px 20px 10px',
                            background: '#fff',
                            borderRadius: '8px',
                            width: '200px'
                        }}>
                            <Spin />
                            <span style={{ marginLeft: '5px' }}>数据导出中...</span>
                        </div>
                    </div> : ''
            }

            <div className={`saleReportHideBox${printIndex}`} style={{ position: 'fixed', zIndex: -1, top: 0, left: 0 }}>
                {
                    showExportTable && reqDetailList && reqDetailList.length > 0 ?
                        <ProTable
                            columns={columns}
                            dataSource={reqDetailList}
                            pagination={false}
                            expandable={{
                                defaultExpandAllRows: true
                            }}
                        /> : ''
                }
            </div>
            <div id='hiddenBox' style={{ position: 'fixed', zIndex: -1, top: 0, left: 0 }} />

            <div style={{ backgroundColor: '#fff', display: 'flex' }}>
                <LeftSelectTree setSelectedId={setSelectedId} setCollapsible={setCollapsible} collapsible={collapsible} />
                <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
                        }}
                        scroll={{ x: "100%", y: "calc(100vh - 430px)" }}
                        headerTitle={<PageTitleBox props={props} />} // 列表表头
                        search={{ span: 6 }}
                        request={async (params, sorter) => {

                            if (!selectedId) {
                                return
                            }
                            // 排序字段
                            const sortstr = Object.keys(sorter).map(n => {
                                const value = sorter[n]
                                return value ? `${n} ${value.replace('end', '')}` : ''
                            })
                            const req: any = {
                                SearchParameter: {
                                    DEPT_IDS: selectedId,
                                    CREATEDATE_Start: params.CREATEDATE_Start || "",
                                    CREATEDATE_End: params.CREATEDATE_End || "",
                                    ACCEPT_CODE: "200300",
                                    SearchOtherKeyName: "COMMODITY_NAME,COMMODITY_BARCODE",
                                    SearchOtherKeyValue: params?.searchText || '',
                                },
                                PageIndex: 1,
                                PageSize: 999999,
                                // sortstr: sortstr.length ? sortstr.toString() : "",
                                sortstr: "ENDDATE desc",
                            }
                            setSearchParams(params)

                            const data = await handleGetSALESTOREPROINSTList(req)
                            console.log('datadatadata', data);
                            if (data && data.length > 0) {

                                let fieldData: any = [
                                    "OPERATE_COUNT",
                                    "OPERATE_TAXAMOUNT",
                                    "OPERATE_AMOUNT"
                                ]


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

                                return { data, success: true }
                            }
                            return { data: [], success: true }
                        }}
                        toolbar={{
                            actions: [
                                // <span style={{ visibility: 'hidden' }}>
                                //     <ReactHTMLTableToExcel
                                //         buttonText={'导出excel'}
                                //         ref={downloadBtnRef}
                                //         table="table-to-xls-returnProcess"
                                //         filename={`调拨流程统计${searchParams?.StartDate}-${searchParams?.EndDate}`}
                                //         sheet="sheet1"
                                //     />
                                // </span>,
                                <Button
                                    key="new"
                                    type="primary"
                                    onClick={(e) => {
                                        if (reqDetailList && reqDetailList.length > 0) {
                                            // 尝试一下 导出新方法 
                                            exportXlsxFromProColumnsExcelJS(columns,
                                                reqDetailList,
                                                `退货流程统计${searchParams?.CREATEDATE_Start}-${searchParams?.CREATEDATE_End}`,
                                                {
                                                    topTitle: `退货流程统计表`, // 顶部大标题
                                                    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>
                            ]
                        }}
                    />
                </div>
            </div>

            {/* 退货单 */}
            <ReturnGoodsTable showDetail={onShow} parentRow={currentRow} onCencel={handleCloseModal} searchParams={searchParams} />
        </div>
    )
}

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