import React, { useRef, useEffect, useState } from 'react';
import { history } from '@umijs/max';

import { Select, Space, Image, Button, message, Upload } from 'antd';
import { TrophyOutlined, UploadOutlined } from '@ant-design/icons';

import {
    PageContainer,
    ProTable,
} from '@ant-design/pro-components';

import dayjs from 'dayjs';

import { exportLink } from '@/utils/func';

// import { getToken, setAuthority } from '@/utils/auth';


import { pointsRecordItems } from '@/services/invest/money';
import { userPage } from '@/services/invest/user';

export default () => {

    const actionRef = useRef();

    const [config, setConfig] = useState();
    const [searchParams, setSearchParams] = useState(null);
    const [shopOption, setShopOption] = useState([]);

    const initRow = {
        id: ''
    };
    const [row, setRow] = useState(initRow);




    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: '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?.shopName}</div>
                    <div>{record?.phone}</div>
                    <div>{record?.level}</div>
                </>
            },
        },
        {
            title: '金额',
            dataIndex: 'money',
            search: false,
        },
        {
            title: '当前余额',
            dataIndex: 'curMoney',
            search: false,
        },
        {
            title: '类型',
            dataIndex: 'type',
            search: true,
            renderFormItem: (
                _,
                { type, defaultRender, formItemProps, fieldProps, ...rest },
                form,
            ) => {
                const data = [];

                for (let index in config?.type) {
                    if (config?.type.hasOwnProperty(index)) {
                        data.push({
                            label: config?.type[index],
                            key: index
                        })
                    }
                }

                return <Select
                    {...fieldProps}
                    allowClear
                    style={{ width: "100%" }}
                    filterOption={false}
                    fieldNames={{
                        label: "label",
                        value: "key"
                    }}
                    options={data}
                />
            },
        },
        {
            title: '积分类型',
            dataIndex: 'moneyType',
            search: true,
            renderFormItem: (
                _,
                { type, defaultRender, formItemProps, fieldProps, ...rest },
                form,
            ) => {
                const data = [{
                    label: '基础',
                    key: 'money'
                }, {
                    label: '增值',
                    key: 'money2'
                }];

                return <Select
                    {...fieldProps}
                    allowClear
                    style={{ width: "100%" }}
                    filterOption={false}
                    fieldNames={{
                        label: "label",
                        value: "key"
                    }}
                    options={data}
                />
            },
        },
        {
            title: '充电桩类型',
            dataIndex: 'goodsPrice',
            search: false,
        },
        {
            title: '收益时间',
            dataIndex: 'todate',
            search: false,
        },
        {
            title: '来源',
            dataIndex: 'model',
            search: false,
        },
        {
            title: '来源ID',
            dataIndex: 'modelId',
            search: false,
        },
        {
            title: '备注',
            dataIndex: 'note',
            search: false,
        },
        {
            title: '创建时间',
            dataIndex: 'createdAt',
            search: true,
            valueType: 'dateRange',
            search: {
                transform: (value) => {
                    return {
                        start_date: value[0],
                        end_date: value[1],
                    };
                },
            },
            render: (_, record) => {
                return record?.created_at;
            },
        },
    ];

    return (
        <PageContainer
            ghost
        >
            <>
                <ProTable
                    actionRef={actionRef}
                    rowKey="id"
                    search={{
                        defaultCollapsed: false,
                    }}
                    toolBarRender={() => [
                        <Button type="primary" key={'/admin/invest/users/points/record/export'} onClick={() => {
                            const params = new URLSearchParams(searchParams);
                            fetch(`${process.env.API_URL}/admin/invest/users/points/record/export?${params}`, {
                              method: 'GET',
                              headers: {
                                'Content-Type': 'application/json',
                                'Authorization': localStorage.getItem('token'),
                              }
                            })
                              .then(response => response.blob())
                              .then(data => {
                                const link = document.createElement('a');
                                link.href = URL.createObjectURL(data);
                                link.download = '提现记录.xlsx';
                                link.click();
                              })
                              .catch(error => console.error('Error:', error));
                        }}>导出积分列表</Button>
                    ]}
                    request={async (params, sorter, filter) => {
                        setSearchParams({ token: '', ...params });
                        const { data, success } = await pointsRecordItems({
                            ...params,
                            sorter,
                            filter,
                        });

                        

                        setConfig({
                            type:data?.records[0].typeEnumMap
                        });
                        return {
                            data: data?.records || [],
                            total: data?.total,
                            success,
                        };
                    }}
                    columns={columns}
                />
            </>
        </PageContainer>
    );
};
