// 商城交易台账 交易台账管理
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 { handeGetSupplierSaleBillList } from "../service";
import moment from 'moment'
import OrderDetailModal from "../BookingMealOrder/components/orderDetailModal";
import { handleSetlogSave } from "@/utils/format";

const TradingLedger: 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 [currentRow, setCurrentRow] = useState<any>();
    const [modalVisible, handleModalVisible] = useState<boolean>(false);

    const columns: any = [
        {
            title: '查询内容',
            hideInTable: true,
            dataIndex: 'searchText',
            fieldprop: {
                placeholder: "请输入供应商名称/订单号等"
            }
        },
        {
            title: '下单时间',
            dataIndex: 'search_date',
            valueType: 'dateRange',
            hideInTable: true,
            hideInDescriptions: true,
            search: {
                transform: (value) => {
                    return {
                        ORDER_DATE_Start: value[0],
                        ORDER_DATE_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().subtract(1, 'M').format('YYYY-MM-DD'), moment().format('YYYY-MM-DD')],
            initialValue: [moment().startOf('M'), moment()],
        },

        {
            dataIndex: 'MERCHANTS_NAME',
            title: <div style={{ textAlign: 'center' }}>供应商名称</div>,
            align: 'left',
            width: 200,
            ellipsis: true,
            hideInSearch: true,
        },
        {
            dataIndex: 'SALEBILL_CODE',
            title: <div style={{ textAlign: 'center' }}>订单编码</div>,
            align: 'center',
            width: 220,
            ellipsis: true,
            hideInSearch: true,
            render: (_, record) => {
                return record?.SALEBILL_CODE ?
                    <a onClick={() => {
                        setCurrentRow(record);
                        handleModalVisible(true)
                        handleSetlogSave(`查询收货人【${record?.ORDER_PERSON}】编码【${record.SALEBILL_CODE}】订单`)

                    }}>{record?.SALEBILL_CODE}</a> : "-"
            }
        },
        {
            dataIndex: 'PAYMENT_CODE',
            title: <div style={{ textAlign: 'center' }}>交易单号</div>,
            align: 'center',
            width: 220,
            ellipsis: true,
            hideInSearch: true,
        },
        {
            dataIndex: 'COMMODITY_NAME',
            title: <div style={{ textAlign: 'center' }}>购买商品</div>,
            align: 'left',
            width: 300,
            ellipsis: true,
            hideInSearch: true,
        },
        {
            dataIndex: 'ORDER_PERSON',
            title: '收货人',
            align: 'center',
            width: 150,
            ellipsis: true,
            hideInSearch: true,
        },
        {
            dataIndex: 'ORDER_DATE',
            title: '下单时间',
            align: 'center',
            width: 150,
            ellipsis: true,
            hideInSearch: true,
            render: (_, record) => {
                return record?.ORDER_DATE ? moment(record?.ORDER_DATE).format('YYYY-MM-DD HH:mm:ss') : "-"
            },
            sorter: (a, b) => new Date(a.ORDER_DATE).getTime() - new Date(b.ORDER_DATE).getTime(),
            defaultSortOrder: 'descend',
        },
        {
            title: "订单类型",
            width: 150,
            dataIndex: "SALEBILL_TYPE",
            valueType: "select",
            align: 'center',
            valueEnum: {
                "0": "全部",
                "3000": "零售商城",
                "3001": "工会商城",
                "3002": "品诺商城",
                "3010": "积分商城"
            },
            initialValue: '0',
        },
        {
            title: "订单状态",
            dataIndex: "SALEBILL_STATE",
            width: 150,
            ellipsis: true,
            valueType: "select",
            valueEnum: {
                "0": "全部",
                "1005": "订单待支付",
                "1010": "订单待发货",
                "2010": "订单已发货",
                "3000": "订单已完成",
                "8000": "退款申请中",
                "8900": "订单已退款",
                "9000": "订单已关闭",
                "9999": "订单已撤销"
            },
            align: "center",
            initialValue: '0',
        },
        {
            dataIndex: 'ORDER_AMOUNT',
            title: '订单金额',
            align: 'center',
            width: 150,
            ellipsis: true,
            hideInSearch: true,
            sorter: (a, b) => a.ORDER_AMOUNT - b.ORDER_AMOUNT,
        },
        {
            dataIndex: 'PAY_AMOUNT',
            title: '实付金额',
            align: 'center',
            width: 150,
            ellipsis: true,
            hideInSearch: true,
            sorter: (a, b) => a.PAY_AMOUNT - b.PAY_AMOUNT,
        },
        {
            title: "支付方式",
            dataIndex: "CHANNEL_TYPE",
            valueType: "select",
            valueEnum: {
                "0": "全部",
                "支付宝": "支付宝",
                "微信": "微信",
                "积分兑换": "积分兑换",
                "余额支付": "余额支付",
            },
            width: 120,
            hideInSearch: true,
            ellipsis: true,
            align: "center",
            initialValue: '0',
        },

    ]

    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-TradingLedger');                    // 给table添加id，值与按钮上的table字段对应

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

        setShowLoading(false)

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

    const handleCloseModal = () => {
        handleModalVisible(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: '100%',
                    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) => {

                            const req: any = {
                                SearchParameter: {
                                    SALEBILL_IDS: "",
                                    SALEBILL_TYPES: params?.SALEBILL_TYPE === '0' ? '3000,3001,3002,3010' : params?.SALEBILL_TYPE,
                                    MEMBERSHIP_IDS: "",
                                    MERCHANTS_IDS: "",
                                    // PROVINCE_CODE: currentUser?.ProvinceCode,
                                    SERVERPART_IDS: "",
                                    SERVERPARTSHOP_IDS: "",
                                    ORDER_DATE_Start: params?.ORDER_DATE_Start || "",
                                    ORDER_DATE_End: params?.ORDER_DATE_End || "",
                                    SALEBILL_STATES: params?.SALEBILL_STATE === "0" ? "1010,2010,3000" : params?.SALEBILL_STATE || "",
                                    CHANNEL_TYPE: params?.CHANNEL_TYPE === "0" ? "" : params?.CHANNEL_TYPE || "",
                                    WECHATAPPSIGN_ID: "",
                                    WECHATAPP_APPID: "",
                                    OWNERUNIT_ID: currentUser?.OwnerUnitId,
                                    SearchKeyValue: params?.searchText || "",
                                },
                                PageIndex: 1,
                                PageSize: 999999
                            }

                            setSearchParams(params)

                            console.log('reqreqreqreq', req);
                            const data = await handeGetSupplierSaleBillList(req)
                            handleSetlogSave(`点击查询按钮`)
                            console.log('datadatadatadatadata', data);

                            setReqDetailList(data)
                            if (data && data.length > 0) {
                                return { data, success: true }
                            }
                            return { data: [], success: true }
                        }}
                        toolbar={{
                            actions: [
                                <span style={{ visibility: 'hidden' }}>
                                    <ReactHTMLTableToExcel
                                        buttonText={'导出excel'}
                                        ref={downloadBtnRef}
                                        table="table-to-xls-TradingLedger"
                                        filename={`交易台账${searchParams?.ORDER_DATE_Start}-${searchParams?.ORDER_DATE_End}`}
                                        sheet="sheet1"
                                    />
                                </span>,
                                <Button
                                    key="new"
                                    type="primary"
                                    onClick={(e) => {
                                        if (reqDetailList && reqDetailList.length > 0) {
                                            setShowLoading(true)
                                            setTimeout(() => {
                                                setShowExportTable(true)
                                                setTimeout(() => {
                                                    handleSetlogSave('导出Excel')
                                                    exportTable(e)
                                                }, 100)
                                            }, 100)
                                        } else {
                                            message.error('暂无数据可导出！')
                                        }
                                    }}
                                >
                                    导出excel
                                </Button>
                            ]
                        }}
                    />
                </div>
            </div>

            <OrderDetailModal modalVisible={modalVisible} handleCloseModal={handleCloseModal} currentRow={currentRow} />

        </div>
    )
}

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