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

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 [currentSearchText, setCurrentSearchText] = useState<string>('')
    // 获取导出数据的loading
    const [getExportDataLoading, setGetExportDataLoading] = useState<boolean>(false);

    // 获取所属单位
    const { loading: companyLoading, data: companyList = [] } = useRequest(async () => {
        const startReq: any = {
            SearchParameter: {
                OWNERUNIT_ID: "911",
                COMPANY_STATE: 1000
            },
            PageIndex: 1,
            PageSize: 999999
        }
        const startData: any = await handeGetCOMPANYList(startReq)
        console.log('fdsjfhsjlaf', startData);
        let list: any = []
        if (startData && startData.length > 0) {
            startData.forEach((item: any) => {
                list.push({ label: item.COMPANY_NAME, value: item.COMPANY_ID })
            })
        }
        return list
    })

    // 页面显示的表格内容
    const columns: any = [
        {
            dataIndex: 'searchText',
            title: '查询内容',
            hideInTable: true,
            fieldProps: {
                placeholder: "请输入供货商/购买的商品/订单编号"
            }
        },
        {
            dataIndex: "CompanyId",
            title: "所属单位",
            hideInTable: true,
            valueType: 'select',
            fieldProps: {
                showSearch: true,
                options: companyList,
                filterOption: (input: any, option: any) => (option?.label ?? '').toLowerCase().includes(input.toLowerCase()),
            }
        },
        {
            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()],
        },
        {
            title: "序号",
            dataIndex: "index",
            width: 80,
            hideInSearch: true,
            ellipsis: true,
            align: 'center',
            valueType: 'index'
        },
        {
            dataIndex: 'SupplierName',
            title: <div style={{ textAlign: 'center' }}>供应商名称</div>,
            align: 'left',
            width: 250,
            ellipsis: true,
            hideInSearch: true,
            render: (_, record) => {
                return highlightText(record?.SupplierName, currentSearchText)
            }
        },
        {
            dataIndex: "SupplierName",
            title: <div style={{ textAlign: 'center' }}>所属单位</div>,
            hideInSearch: true,
            width: 250,
            ellipsis: true,
        },
        {
            dataIndex: 'OrderPerson',
            title: <div style={{ textAlign: 'center' }}>会员名称</div>,
            align: 'center',
            width: 150,
            ellipsis: true,
            hideInSearch: true,
            render: (_, record) => {
                return record?.OrderPerson ? `${record?.OrderPerson}${record?.ReceiverPhone ? `【${record?.ReceiverPhone}】` : ""}` : ""
            }
        },
        {
            dataIndex: 'ReceiverName',
            title: <div style={{ textAlign: 'center' }}>收货人员</div>,
            align: 'center',
            width: 150,
            ellipsis: true,
            hideInSearch: true
        },
        {
            dataIndex: 'ReceiverPhone',
            title: <div style={{ textAlign: 'center' }}>联系电话</div>,
            align: 'center',
            width: 150,
            ellipsis: true,
            hideInSearch: true
        },
        {
            dataIndex: 'CommodityName',
            title: <div style={{ textAlign: 'center' }}>购买的商品</div>,
            align: 'left',
            width: 300,
            ellipsis: true,
            hideInSearch: true,
            render: (_, record) => {
                return highlightText(record?.CommodityName, currentSearchText)
            }
        },
        {
            dataIndex: 'SaleTotalTaxAmount',
            title: '订单金额',
            align: 'right',
            width: 150,
            ellipsis: true,
            hideInSearch: true,
            sorter: (a, b) => a.ORDER_AMOUNT - b.ORDER_AMOUNT,
        },
        {
            dataIndex: 'PayAmount',
            title: '实付金额',
            align: 'right',
            width: 150,
            ellipsis: true,
            hideInSearch: true,
            sorter: (a, b) => a.PayAmount - b.PayAmount,
        },
        {
            dataIndex: 'BalancePayment',
            title: <div style={{ textAlign: 'center' }}>工会积分</div>,
            align: 'right',
            valueType: 'digit',
            width: 150,
            ellipsis: true,
            hideInSearch: true,
        },
        {
            title: "订单类型",
            width: 150,
            dataIndex: "SaleBillType",
            valueType: "select",
            align: 'center',
            valueEnum: {
                "0": "全部",
                "3000": "零售商城",
                "3001": "工会商城",
                "3002": "品诺商城",
                "3010": "积分商城"
            },
            initialValue: '0',
        },
        {
            title: "支付方式",
            dataIndex: "PaymentMethod",
            valueType: "select",
            valueEnum: {
                "0": "全部",
                "支付宝": "支付宝",
                "微信": "微信",
                "积分兑换": "积分兑换",
                "余额支付": "余额支付",
            },
            width: 120,
            hideInSearch: true,
            ellipsis: true,
            align: "center",
            initialValue: '0',
        },
        {
            dataIndex: 'PaymentTime',
            title: '下单时间',
            align: 'center',
            width: 150,
            ellipsis: true,
            hideInSearch: true,
            render: (_, record) => {
                return record?.PaymentTime ? moment(record?.PaymentTime).format('YYYY-MM-DD HH:mm:ss') : "-"
            },
            sorter: (a, b) => new Date(a.PaymentTime).getTime() - new Date(b.PaymentTime).getTime(),
            defaultSortOrder: 'descend',
        },
        {
            dataIndex: 'OrderCode',
            title: <div style={{ textAlign: 'center' }}>订单编码</div>,
            align: 'center',
            width: 220,
            ellipsis: true,
            hideInSearch: true,
            render: (_, record) => {
                return record?.OrderCode ?
                    <a onClick={() => {
                        setCurrentRow(record);
                        handleModalVisible(true)
                        handleSetlogSave(`查询收货人【${record?.ORDER_PERSON}】编码【${record.OrderCode}】订单`)

                    }}>
                        {/* {record?.OrderCode} */}
                        {highlightText(record?.OrderCode, currentSearchText)}
                    </a> : "-"
            }
        },
        // {
        //     dataIndex: 'PAYMENT_CODE',
        //     title: <div style={{ textAlign: 'center' }}>交易单号</div>,
        //     align: 'center',
        //     width: 220,
        //     ellipsis: true,
        //     hideInSearch: true,
        // },
        {
            title: "订单状态",
            dataIndex: "OrderStatus",
            width: 150,
            ellipsis: true,
            valueType: "select",
            valueEnum: {
                "0": "全部",
                "1005": "订单待支付",
                "1010": "订单待发货",
                "2010": "订单已发货",
                "3000": "订单已完成",
                "8000": "退款申请中",
                "8900": "订单已退款",
                "9000": "订单已关闭",
                "9999": "订单已撤销"
            },
            align: "center",
            initialValue: '0',
        },
        // {
        //     dataIndex: 'desc',
        //     title: <div style={{ textAlign: 'center' }}>备注说明</div>,
        //     align: 'left',
        //     width: 150,
        //     ellipsis: true,
        //     hideInSearch: true,
        // },
    ]

    // 导出excel的表格内容
    const exportColumns: any = [
        {
            title: "订单编码",
            width: 250,
            dataIndex: "OrderCode",
        },
        {
            title: "会员名称",
            width: 150,
            dataIndex: "OrderPerson",
        },
        {
            title: "收货人",
            width: 150,
            dataIndex: "ReceiverName",
        },
        {
            title: "收货人电话",
            width: 150,
            dataIndex: "ReceiverPhone",
        },
        {
            title: "收货地址",
            width: 250,
            dataIndex: "ReceiverAddress",
        },
        {
            title: "物流信息",
            width: 250,
            dataIndex: "LogisticsInfo",
        },
        {
            title: "商品名称",
            width: 250,
            dataIndex: "CommodityName",
        },
        {
            title: "商品条码",
            width: 150,
            dataIndex: "CommodityBarcode",
        },
        {
            title: "供货商",
            width: 250,
            dataIndex: "SupplierName",
        },
        {
            title: "商品规格",
            width: 120,
            dataIndex: "CommodityRule",
        },
        {
            title: "下单数量",
            width: 120,
            dataIndex: "OrderCount",
            valueType: "digit",
        },
        {
            title: "采购单价",
            width: 120,
            dataIndex: "PurchaseTaxPrice",
            valueType: "digit",
        },
        {
            title: "采购合计金额",
            width: 120,
            dataIndex: "PurchaseTotalTaxAmount",
            valueType: "digit",
        },
        {
            title: "采购不含税合计金额",
            width: 120,
            dataIndex: "PurchaseTotalAmount",
            valueType: "digit",
        },
        {
            title: "销售单价",
            width: 120,
            dataIndex: "SaleTaxPrice",
            valueType: "digit",
        },
        {
            title: "销售合计金额",
            width: 120,
            dataIndex: "SaleTotalTaxAmount",
            valueType: "digit",
        },
        {
            title: "销售不含税合计金额",
            width: 120,
            dataIndex: "SaleTotalAmount",
            valueType: "digit",
        },
        {
            title: "平台手续费",
            width: 120,
            dataIndex: "PlatformFee",
            valueType: "digit",
        },
        {
            title: "财务到账含税金额",
            width: 120,
            dataIndex: "FinancialReceivedAmount",
            valueType: "digit",
        },
        {
            title: "税率",
            width: 120,
            dataIndex: "TaxRate",
        },
        {
            title: "单位名称",
            width: 250,
            dataIndex: "CompanyName",
        },
        {
            title: "付款积分",
            width: 120,
            dataIndex: "BalancePayment",
        },
        {
            title: "实付总金额",
            width: 120,
            dataIndex: "PayAmount",
            valueType: "digit",
        },
        {
            title: "支付方式",
            width: 150,
            dataIndex: "PaymentMethod",
        },
        {
            title: "支付时间",
            width: 180,
            dataIndex: "PaymentTime",
        },
        {
            title: "支付订单号",
            width: 150,
            dataIndex: "PaymentOrderCode",
        },
        {
            title: "订单状态",
            width: 150,
            dataIndex: "OrderStatus",
        },
        {
            title: "工会订单",
            width: 150,
            dataIndex: "IsUnionOrder",
        }
    ]
    // 导出财务的结算excel表格内容
    const exportFinanceColumns: any = [
        {
            title: "支付订单号",
            width: 250,
            dataIndex: "PaymentOrderCode",
        },
        {
            title: "会员名称",
            width: 150,
            dataIndex: "OrderPerson",
        },
        {
            title: "支付时间",
            width: 180,
            dataIndex: "PaymentTime",
        },
        {
            title: "下单数量",
            width: 120,
            valueType: 'digit',
            dataIndex: "OrderCount",
        },
        {
            title: "采购合计金额",
            width: 120,
            valueType: 'digit',
            dataIndex: "PurchaseTotalTaxAmount",
        },
        {
            title: "采购不含税合计金额",
            width: 120,
            valueType: 'digit',
            dataIndex: "PurchaseTotalAmount",
        },
        {
            title: "销售合计金额",
            width: 120,
            valueType: 'digit',
            dataIndex: "SaleTotalTaxAmount",
        },
        {
            title: "销售不含税合计金额",
            width: 120,
            valueType: 'digit',
            dataIndex: "SaleTotalAmount",
        },
        {
            title: "平台手续费",
            width: 120,
            valueType: 'digit',
            dataIndex: "PlatformFee",
        },
        {
            title: "财务到账含税金额",
            width: 120,
            valueType: 'digit',
            dataIndex: "FinancialReceivedAmount",
        },
        {
            title: "单位名称",
            width: 250,
            dataIndex: "CompanyName",
        },
        {
            title: "付款积分",
            width: 120,
            valueType: 'digit',
            dataIndex: "BalancePayment",
        },
        {
            title: "实付总金额",
            width: 120,
            valueType: 'digit',
            dataIndex: "PayAmount",
        },
        {
            title: "支付方式",
            width: 150,
            dataIndex: "PaymentMethod",
        },
        {
            title: "订单状态",
            width: 150,
            dataIndex: "OrderStatus",
        },
        {
            title: "工会订单",
            width: 150,
            dataIndex: "IsUnionOrder",
        }
    ]


    const handleCloseModal = () => {
        handleModalVisible(false)
    }

    // 获取导出数据
    const handleGetExportData = async (type: number) => {
        // type ：1商品明细，2财务结算表
        setGetExportDataLoading(true)
        const req: any = {
            ExportType: type,
            OwnerUnitId: "911",
            CompanyId: searchParams?.CompanyId || "",
            MerchantId: "",
            SaleBillState: searchParams?.OrderStatus === '0' ? '' : (searchParams?.OrderStatus || ""),
            SaleBillType: searchParams?.SaleBillType === '0' ? '' : (searchParams?.SaleBillType || ""),
            ChannelType: searchParams?.PaymentMethod || "",
            StartDate: searchParams?.ORDER_DATE_Start || "",
            EndDate: searchParams?.ORDER_DATE_End || "",
            // SearchKeyName: "SupplierName,CommodityName,OrderCode",
            // SearchKeyValue: searchParams?.searchText || "",
            // SortStr: ""
        }
        console.log('reqreqreq', req);

        const data = await handeGetOnlineBillAccountList(req)
        console.log('djskadjas', data);
        setGetExportDataLoading(false)
        if (data && data.length > 0) {
            // 用于导出的最后数据
            let res: any = []
            let enumList: any = ["PaymentMethod", "OrderStatus", "IsUnionOrder"]
            let PaymentMethodList: any = [
                { label: "支付宝", value: "支付宝" },
                { label: "微信", value: "微信" },
                { label: "积分兑换", value: "积分兑换" },
                { label: "余额支付", value: "余额支付" },
            ]
            let OrderStatusList: any = [
                { label: "订单待支付", value: 1005 },
                { label: "订单待发货", value: 1010 },
                { label: "订单已发货", value: 2010 },
                { label: "订单已完成", value: 3000 },
                { label: "退款申请中", value: 8000 },
                { label: "订单已退款", value: 8900 },
                { label: "订单已关闭", value: 9000 },
                { label: "订单已撤销", value: 9999 },
            ]
            let IsUnionOrder: any = [
                { label: "是", value: 1 },
                { label: "否", value: 0 }
            ]
            res = formatTreeData(JSON.parse(JSON.stringify(data)), [], enumList, [PaymentMethodList, OrderStatusList, IsUnionOrder], [])

            console.log('resresres', res);

            exportXlsxFromProColumnsExcelJS(type === 1 ? exportColumns : type === 2 ? exportFinanceColumns : [],
                res,
                `${type === 1 ? `云南交投集团经营开发有限公司彩云驿商业管理分公司销售出库单(${searchParams.ORDER_DATE_Start}-${searchParams.ORDER_DATE_End})` :
                    `云南交投集团经营开发有限公司彩云驿商业管理分公司财务结算单(${searchParams.ORDER_DATE_Start}-${searchParams.ORDER_DATE_End})`}`,
                {
                    topTitle: `${type === 1 ? `云南交投集团经营开发有限公司彩云驿商业管理分公司销售出库单(${searchParams.ORDER_DATE_Start}-${searchParams.ORDER_DATE_End})` :
                        `云南交投集团经营开发有限公司彩云驿商业管理分公司财务结算单(${searchParams.ORDER_DATE_Start}-${searchParams.ORDER_DATE_End})`}`,
                    footerItems: type === 1 ? [
                        { label: "审核", value: "", labelSpan: 1, valueSpan: 2, labelAlign: "left", align: "left", startCol: 7 },
                        { label: "验收", value: "", labelSpan: 1, valueSpan: 2, labelAlign: "left", align: "left", startCol: 12 },
                        { label: "经办", value: "", labelSpan: 1, valueSpan: 2, labelAlign: "left", align: "left", startCol: 15 }
                    ] : []
                }
            )
        } else {
            message.error('暂无导出数据！')
        }
    }

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

            <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 - 470px)" }}
                        headerTitle={<PageTitleBox props={props} />} // 列表表头
                        search={{ span: 6, defaultCollapsed: false }}
                        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)

                            const req: any = {
                                // SearchParameter: {
                                OwnerUnitId: "911",
                                CompanyId: params?.CompanyId || "",
                                MerchantId: "",
                                SaleBillState: params?.OrderStatus === '0' ? '' : (params?.OrderStatus || ""),
                                SaleBillType: params?.SaleBillType === '0' ? '' : (params?.SaleBillType || ""),
                                ChannelType: params?.PaymentMethod || "",
                                StartDate: params?.ORDER_DATE_Start || "",
                                EndDate: params?.ORDER_DATE_End || "",
                                SearchKeyName: "SupplierName,CommodityName,OrderCode",
                                SearchKeyValue: params?.searchText || "",
                                SortStr: ""
                            }
                            const data = await handeGetSalebillAccountList(req)
                            setSearchParams(params)
                            setCurrentSearchText(params?.searchText || "")
                            handleSetlogSave(`点击查询按钮`)
                            console.log('datadatadatadatadata', data);

                            setReqDetailList(data)
                            if (data && data.length > 0) {
                                return { data, success: true }
                            }
                            return { data: [], success: true }
                        }}
                        toolbar={{
                            actions: [
                                <Button
                                    key="new"
                                    type="primary"
                                    loading={getExportDataLoading}
                                    onClick={(e) => {
                                        handleGetExportData(1)
                                    }}
                                >
                                    导出Excel
                                </Button>,
                                <Button
                                    key="new"
                                    type="primary"
                                    loading={getExportDataLoading}
                                    onClick={(e) => {
                                        handleGetExportData(2)
                                    }}
                                >
                                    导出财务结算Excel
                                </Button>
                            ]
                        }}
                    />
                </div>
            </div>

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

        </div>
    )
}

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