import { orderPage, ordersExport, ordersCount, shopOrderRefund } from '@/services/shop/order';
import { userPage } from '@/services/invest/user';

import { history } from '@umijs/max';

import React, { useRef, useEffect, useState } from 'react';
import { useIntl, useAccess } from '@umijs/max';
import { message, Tag, Button, Modal, Image, Switch, Space, Select, Card, Col, Row } from 'antd';
import { ActionType, PageContainer, ProTable } from '@ant-design/pro-components';
import { PlusOutlined } from '@ant-design/icons';
import dayjs from 'dayjs';
import BonusFormModal from './components/BonusFormModal';
import { debounce } from 'lodash';
import RefundFormModal from './components/RefundFormModal';

const GoodsTableList: React.FC = () => {
    const actionRef = useRef<ActionType>();
    const [row, setRow] = useState(null);
    const [bonusFormModal, setBonusFormModal] = useState(false);
    const [refundFormModal, setRefundFormModal] = useState(false);
    const [searchParams, setSearchParams] = useState({});

    const [count, setCount] = useState(null);
    const [shopOption, setShopOption] = useState([]);

    const handleRefund = async (fields) => {
        const { success } = await shopOrderRefund({ ...fields });

        if (success) {
            actionRef.current?.reload();
            setRefundFormModal(false);
        }
    };


    const fetchOptions = async (keyword = '') => {
        try {
            const { data } = await userPage({ userName: keyword });

            setShopOption((data?.records || []).map(item => ({
                label: item.username + ' ' + item.mobile, // 根据实际字段调整
                value: Number(item.id),   // 根据实际字段调整
            })));
        } catch (error) {
            console.error('加载选项失败:', error);
            return []; // 失败时返回空数组
        }
    };

    const columns = [
        {
            title: '订单ID',
            dataIndex: 'id',
            search: false,
        },
        {
            title: '订单号',
            dataIndex: 'orderNo',
            search: true,
            render: (_, record) => {
                return <Space>
                    <div>{record?.orderNo}</div>
                    <Button
                        type="link"
                        onClick={() => {
                            setRow(record);
                            setBonusFormModal(true);
                        }}
                    >
                        查看
                    </Button>
                </Space>;
            },
        },
        {
            title: '投资人',
            dataIndex: 'shopId',
            valueType: 'select',
            search: {
                fieldProps: {
                    placeholder: '输入用户名',
                    showSearch: true,
                    filterOption: false,
                    onSearch: async (keyword) => {
                        if (!keyword) {
                            return;
                        }
                        await fetchOptions(keyword);
                    },
                    options: shopOption,
                },
            },
            render: (_, record) => {
                return <>
                    <div>{record?.investUsersEntity?.nickname}</div>
                    <div>{record?.investUsersEntity?.username}</div>
                    <div>{record?.investUsersEntity?.mobile}</div>
                    {/* <div>{config?.level.find((val) => val.level == record?.shop?.vip).name}</div> */}
                    <div>注册时间：{record?.investUsersEntity?.createdAt ? dayjs(record?.investUsersEntity?.createdAt).format('YYYY-MM-DD HH:mm:ss') : ''}</div>
                </>
            },
        },
        {
            title: '商品信息',
            dataIndex: 'goods',
            search: false,
            render: (_, record) => {
                return <>
                    <Image src={record?.goodsEntity?.cover} width={50} />
                    <div>商品数量：{record?.num}</div>
                    <div>商品名称：{record?.goodsEntity?.name}</div>
                    <div>商品价格：{record?.goodsEntity?.currentPrice}</div>
                </>
            },
        },
        {
            title: '订单金额',
            dataIndex: 'payMoney',
            search: false,
        },
        {
            title: '支付方式',
            dataIndex: 'payType',
            search: false,
        },
        {
            title: '付款时间',
            dataIndex: 'payTime',
            valueType: 'dateTimeRange',
            // initialValue: [moment().format('YYYY-MM-DD'), moment().format('YYYY-MM-DD')],
            search: {
                transform: (value) => {
                    return {
                        startPayTime: value[0],
                        endPayTime: value[1],
                    };
                },
            },
            render: (_, record) => {
                return record?.payTime ? dayjs(record?.payTime * 1000).format('YYYY-MM-DD HH:mm:ss') : ''
            },
        },
        {
            title: '状态',
            dataIndex: 'status',
            search: true,
            renderFormItem: (
                _,
                { type, defaultRender, formItemProps, fieldProps, ...rest },
                form,
            ) => {
                const data = [{
                    key: "WAITPAY",
                    label: "待支付",
                }, {
                    key: "PAY_SUSCCESS",
                    label: "支付成功",
                }, {
                    key: "PAY_CANCEL",
                    label: "取消支付",
                }, {
                    key: "REFUND",
                    label: "退款",
                }];


                return <Select
                    {...fieldProps}
                    allowClear
                    style={{ width: "100%" }}
                    filterOption={false}
                    fieldNames={{
                        label: "label",
                        value: "key"
                    }}
                    options={data}
                />
            }
        },
        {
            title: '退单原因',
            dataIndex: 'refundNote',
            search: false,
        },
        {
            title: '创建时间',
            dataIndex: 'createdAt',
            search: false,
        },
        {
            title: '操作',
            dataIndex: 'option',
            valueType: 'option',
            render: (_, record) => (
                <Button
                    danger
                    onClick={() => {
                        setRow({ ...record, orderId: record.id });
                        setRefundFormModal(true);
                    }}
                >
                    退单
                </Button>
            ),
        },
    ];

    return (
        <PageContainer>

            <Row gutter={10}>
                <Col span={8}>
                    <Card>
                        <div>汇总</div>
                        <div>金额: {count?.totalAmount}</div>
                        <div className='flex '>
                            <div>订单数：{count?.orderNum}</div>
                            <div className='w-6'></div>
                            <div>商品数：{count?.goodsNum}</div>
                        </div>
                    </Card>
                </Col>
                <Col span={8}>
                    <Card>
                        <div>微信支付</div>
                        <div>金额: {count?.wxAmount}</div>
                        <div className='flex '>
                            <div>订单数：{count?.wxOrderNum}</div>
                            <div className='w-6'></div>
                            <div>商品数：{count?.wxGoodsAmount}</div>
                        </div>
                    </Card>
                </Col>
                <Col span={8}>
                    <Card>
                        <div>余额支付</div>
                        <div>金额: {count?.balanceAmount}</div>
                        <div className='flex '>
                            <div>订单数：{count?.balanceOrderNum}</div>
                            <div className='w-6'></div>
                            <div>商品数：{count?.balanceGoodsAmount}</div>
                        </div>
                    </Card>
                </Col>
                {/* <Col span={6}>
                    <Card>
                        <div>线下支付</div>
                        <div>金额: {count?.all4?.money}</div>
                        <div className='flex '>
                            <div>订单数：{count?.all4?.order_num}</div>
                            <div className='w-6'></div>
                            <div>商品数：{count?.all4?.goods_num}</div>
                        </div>
                    </Card>
                </Col> */}
            </Row>

            <div style={{ height: '15px' }}></div>

            <div style={{ width: '100%', float: 'right' }}>
                <BonusFormModal
                    values={row}
                    modalOpenState={bonusFormModal}
                    onModalOpenState={setBonusFormModal}
                />


                <RefundFormModal
                    values={row}
                    modalOpenState={refundFormModal}
                    onModalOpenState={setRefundFormModal}
                    onSubmit={handleRefund}
                />
                <ProTable
                    actionRef={actionRef}
                    rowKey="id"
                    key="goodsList"
                    search={{
                        labelWidth: 120,
                        defaultCollapsed: false,
                    }}
                    toolBarRender={() => [

                        // <Button
                        //     key={'tui'}
                        //     danger
                        //     onClick={() => {
                        //         setRefundFormModal(true);
                        //     }}
                        // >
                        //     退单
                        // </Button>,
                        <Button
                            type="primary"
                            key="add"
                            // hidden={!access.hasPerms('/api/goods/add')}
                            onClick={async () => {
                                ordersExport(searchParams)
                                    .then(blob => {
                                        const link = document.createElement('a');
                                        link.href = URL.createObjectURL(blob);
                                        link.download = '订单.xlsx';
                                        document.body.appendChild(link);
                                        link.click();
                                        document.body.removeChild(link);
                                        setTimeout(() => URL.revokeObjectURL(link.href), 100);
                                    });
                            }}
                        >
                            导出
                        </Button>
                    ]}
                    request={async (params, sorter, filter) => {
                        setSearchParams(params)

                        ordersCount(params).then((res) => {
                            setCount(res.data)
                        })

                        let { data } = await orderPage(params)
                        return {
                            data: data?.records || [],
                            total: data?.total,
                        };
                    }}
                    columns={columns}
                />
            </div>
        </PageContainer >
    );
};

export default GoodsTableList;
