import { usersPage, usersAdd, usersDelete, usersUpdate, updateUserLevel, userTransferHanging, exportUser, userRecharge, accountChange } from '@/services/user/user';


import React, { useRef, useEffect, useState } from 'react';
import { useIntl, useAccess } from '@umijs/max';
import { message, Tag, Image, Button, Select, Modal } from 'antd';
import { ActionType, PageContainer, ProTable } from '@ant-design/pro-components';
import UpdateForm from './edit';
import { PlusOutlined, LineChartOutlined } from '@ant-design/icons';
import { exportData } from '@/utils/func';
import LevelFormModal from './components/LevelFormModal';
import TempFormModal from './components/TempFormModal';
import ShopModal from './components/ShopModal';
import MoneyFormModal from './components/MoneyFormModal';
import TradeFormModal from './components/TradeFormModal';



/**
 * 添加节点
 *
 * @param fields
 */
const handleAdd = async (fields) => {
    const hide = message.loading('正在添加');
    try {
        fields.status = fields.status ? 0 : 1
        await usersAdd({ ...fields });
        hide();
        message.success('添加成功');
        return true;
    } catch (error) {
        hide();
        return false;
    }
};

/**
 * 更新节点
 *
 * @param fields
 */
const handleUpdate = async (fields: API.System.Menu) => {
    const hide = message.loading('正在修改');
    try {
        await usersUpdate(fields);
        hide();
        message.success('修改成功');
        return true;
    } catch (error) {
        hide();
        return false;
    }
};

const handleRemoveOne = async (selectedRow) => {
    const hide = message.loading('正在删除');
    if (!selectedRow) return true;
    try {
        const params = selectedRow;
        await usersDelete(params);
        hide();
        message.success('删除成功');
        return true;
    } catch (error) {
        hide();
        return false;
    }
};




const LogTableList: React.FC = () => {
    const actionRef = useRef<ActionType>();
    const [modalVisible, setModalVisible] = useState<boolean>(false);
    const [currentRow, setCurrentRow] = useState();
    const [selectedRowsState, setSelectedRows] = useState([]);
    const [levelFormModal, setLevelFormModal] = useState(false);
    const [tempFormModal, setTempFormModal] = useState(false);
    const [searchParams, setSearchParams] = useState(null);
    const [shopModal, setBonusFormModal] = useState(false);
    const [row, setRow] = useState();
    const [moneyFormModal, setMoneyFormModal] = useState(false);
    const [tradeFormModal, setTradeFormModal] = useState(false);
    const access = useAccess()

    // 更改等级
    const handleLevel = async (fields) => {
        const { success } = await updateUserLevel({ ...fields });
        if (success) {
            message.success('等级变更成功');
            actionRef.current.reload();
            setLevelFormModal(false);
        }
    };

    const handleTemp = async (fields) => {
        const { success } = await userTransferHanging(fields);
        if (success) {
            message.success('转挂成功');
            actionRef.current?.reload();
            setTempFormModal(false);
        }
    };

    const handleMoney = async (fields) => {
        const { success } = await userRecharge(fields);
        if (success) {
            message.success('余额变更成功');
            actionRef.current?.reload();
            setMoneyFormModal(false);
        }
    }

    const columns = [
        {
            title: 'ID',
            dataIndex: 'id',
            valueType: 'text',
            search: false,
            render: (_: any, record: any) => {
                return <div className={'flex items-center'}>
                    {record.id}
                    <Button type="link" onClick={() => {
                        setRow(record);
                        setBonusFormModal(true);
                    }}>查看</Button>
                </div>
            }
        },
        {
            title: '头像',
            dataIndex: 'avatar',
            valueType: 'image',
            search: false,
        },
        {
            title: '用户名',
            dataIndex: 'userName',
            valueType: 'text',
            search: true,
        },
        {
            title: '用户昵称',
            dataIndex: 'nickName',
            valueType: 'text',
            search: true,
        },
        {
            title: '手机号',
            dataIndex: 'phone',
            valueType: 'text',
            search: true,
        },
        {
            title: '钱包',
            dataIndex: 'points2',
            valueType: 'text',
            search: false,
        },
        {
            title: '收益',
            dataIndex: 'points1',
            valueType: 'text',
            search: false,
        },
        {
            title: '等级',
            dataIndex: 'level',
            valueType: 'text',
            search: false,
        },
        {
            title: '邀请码',
            dataIndex: 'shareCode',
            valueType: 'text',
            search: true,
        },
        {
            title: '状态',
            dataIndex: 'status',
            valueType: 'text',
            search: false,
            render: (_, record) => {
                return <Tag color={record.status == 1 ? 'green' : 'red'}>{record.status == 1 ? '正常' : '禁用'}</Tag>
            }
        },
        {
            title: '推广码',
            dataIndex: 'qrCode',
            valueType: 'text',
            search: false,
            render: (_, record) => {
                return record.qrCode ? <Image src={record.qrCode} width={60} height={60}></Image> : '-'
            }
        },
        {
            title: '创建时间',
            dataIndex: 'createTime',
            valueType: 'text',
            search: false,
        },
        // {
        //     title: '操作',
        //     dataIndex: 'option',
        //     width: '220px',
        //     valueType: 'option',
        //     render: (_, record) => [
        //         // <Button
        //         //     type="link"
        //         //     size="small"
        //         //     // hidden={!access.hasPerms('admin/banner/update')}
        //         //     onClick={() => {
        //         //         setModalVisible(true);
        //         //         setCurrentRow(record);
        //         //     }}
        //         // >
        //         //     编辑
        //         // </Button>,
        //         // <Button
        //         //     type="link"
        //         //     size="small"
        //         //     danger
        //         //     // hidden={!access.hasPerms('admin:banner:update')}
        //         //     onClick={async () => {
        //         //         Modal.confirm({
        //         //             title: '删除',
        //         //             content: '确定删除该项吗？',
        //         //             okText: '确认',
        //         //             cancelText: '取消',
        //         //             onOk: async () => {
        //         //                 const success = await handleRemoveOne(record);
        //         //                 if (success) {
        //         //                     if (actionRef.current) {
        //         //                         actionRef.current.reload();
        //         //                     }
        //         //                 }
        //         //             },
        //         //         });
        //         //     }}
        //         // >
        //         //     删除
        //         // </Button>,
        //     ],
        // },
    ];

    const handleTrade = async (fields) => {

        const { success } = await accountChange(fields);
        if (success) {
            actionRef.current?.reload();
            setTradeFormModal(false);
            message.success('变更成功');
        }
    };



    return (
        <PageContainer>
            <div style={{ width: '100%', float: 'right' }}>
                <TradeFormModal
                    modalOpenState={tradeFormModal}
                    onModalOpenState={setTradeFormModal}
                    onSubmit={handleTrade}
                />

                <ShopModal
                    values={row}
                    modalOpenState={shopModal}
                    onModalOpenState={setBonusFormModal}
                />
                <LevelFormModal
                    modalOpenState={levelFormModal}
                    onModalOpenState={setLevelFormModal}
                    onSubmit={handleLevel}
                />
                <TempFormModal
                    modalOpenState={tempFormModal}
                    onModalOpenState={setTempFormModal}
                    onSubmit={handleTemp}
                />
                <MoneyFormModal
                    modalOpenState={moneyFormModal}
                    onModalOpenState={setMoneyFormModal}
                    onSubmit={handleMoney}
                />

                <ProTable
                    actionRef={actionRef}
                    rowKey="id"
                    key="logList"
                    search={{
                        labelWidth: 120,
                        defaultCollapsed: false,
                    }}
                    toolBarRender={() => [
                        <Button
                            danger
                            hidden={!access.hasPerms('/api/users/userRecharge')}
                            onClick={() => {
                                setMoneyFormModal(true)
                            }}
                        >
                            余额变更
                        </Button>,
                        <Button
                            danger
                            hidden={!access.hasPerms('/api/users/accountChange')}
                            onClick={() => {
                                setTradeFormModal(true)
                            }}
                        >
                            账号变更
                        </Button>,
                        <Button
                            danger
                            hidden={!access.hasPerms('/api/users/userTransferHanging')}
                            onClick={() => {
                                setTempFormModal(true)
                            }}
                        >
                            转挂
                        </Button>,
                        <Button
                            danger
                            hidden={!access.hasPerms('/api/users/updateUserLevel')}
                            onClick={() => {
                                setLevelFormModal(true)
                            }}
                        >
                            等级变更
                        </Button>,
                        <Button
                            danger
                            hidden={!access.hasPerms('/api/users/deleteBatchByIds')}
                            onClick={() => {
                                Modal.confirm({
                                    title: '删除',
                                    content: '确定删除该项吗？',
                                    okText: '确认',
                                    cancelText: '取消',
                                    onOk: async () => {
                                        let data = selectedRowsState.map((item, index) => {
                                            return item.id
                                        })
                                        const success = await handleRemoveOne(data);
                                        if (success) {
                                            if (actionRef.current) {
                                                actionRef.current.reload();
                                            }
                                        }
                                    },
                                });
                            }}
                        >
                            删除
                        </Button>,
                        <Button
                            type="primary"
                            hidden={!access.hasPerms('/api/users/export')}
                            onClick={async () => {
                                let _res: any = await exportUser(searchParams)
                                exportData(_res, '用户信息')
                            }}
                        >
                            <LineChartOutlined /> 导出
                        </Button>,
                        <Button
                            type="primary"
                            hidden={!access.hasPerms('/api/users/add')}
                            onClick={async () => {
                                setCurrentRow(undefined);
                                setModalVisible(true);
                            }}
                        >
                            <PlusOutlined /> 新建
                        </Button>,
                    ]}
                    request={async (params, sorter, filter) => {
                        setSearchParams({ token: '', ...params });
                        let { data } = await usersPage(params)
                        return {
                            data: data?.records || [],
                            total: data?.total,
                        };
                    }}
                    columns={columns}
                    rowSelection={{
                        onChange: (_, selectedRows) => {
                            setSelectedRows(selectedRows)
                        },
                    }}
                />
            </div>
            <UpdateForm
                onSubmit={async (values) => {
                    let success = false;
                    if (values.id) {
                        success = await handleUpdate({ ...values });
                    } else {
                        success = await handleAdd({ ...values });
                    }
                    if (success) {
                        setModalVisible(false);
                        setCurrentRow(undefined);
                        if (actionRef.current) {
                            actionRef.current.reload();
                        }
                    }
                }}
                onCancel={() => {
                    setModalVisible(false);
                    setCurrentRow(undefined);
                }}
                open={modalVisible}
                values={currentRow || {}}
            />
        </PageContainer>
    );
};

export default LogTableList;
