import { usersPage, usersAdd, usersDelete, usersUpdate, updateUserLevel, userTransferHanging, exportUser, userRecharge, accountChange, updateUserRoleType, updateUserPemType } 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';
import UpRole from './components/UpRole';
import UpPem from './components/UpPem';



/**
 * 添加节点
 *
 * @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 [upRoleDatd, setUpRoleDatd] = useState(false);
    const [upPemData, setUpPemData] = useState(false);






    const access = useAccess()

    const [shopOption, setShopOption] = useState([]);
    const searchShop = async (value) => {
        const { success, data } = await usersPage({
            userId: value
        });
        data.records.map((i) => {
            i.userName = i.userName + ' ' + i.phone
        })
        setShopOption(data.records)
    }

    // 更改等级
    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 handleUpRole = async (fields) => {
        const { success } = await updateUserRoleType(fields);
        if (success) {
            message.success('角色修改成功');
            actionRef.current?.reload();
            setUpRoleDatd(false);
        }
    }

    const handleUpPem = async (fields) => {
        const { success } = await updateUserPemType(fields);
        if (success) {
            message.success('推广权限修改成功');
            actionRef.current?.reload();
            setUpPemData(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: 'id',
            valueType: 'text',
            search: true,
            render: (_: any, record: any) => {
                return <div>
                    <div>用户昵称：{record?.nickName}</div>
                    <div>用户名：{record?.userName}</div>
                    <div>手机号：{record?.phone}</div>
                    <div>等级：{record?.level}</div>
                </div>
            },
            renderFormItem: (
                _,
                { type, defaultRender, formItemProps, fieldProps, ...rest },
                form,
            ) => {
                return <Select
                    {...fieldProps}
                    allowClear
                    showSearch
                    placeholder="请输入用户名或手机号"
                    style={{ width: "100%" }}
                    filterOption={false}
                    onSearch={
                        (e) => {
                            if (!e) {
                                return;
                            }
                            searchShop(e);
                        }
                    }
                    fieldNames={{
                        label: "userName",
                        value: "id"
                    }}
                    options={shopOption}
                />
            },
        },
        {
            title: '邀请人信息',
            dataIndex: 'formUserId',
            valueType: 'text',
            search: true,
            render: (_: any, record: any) => {
                return <div>
                    <div>邀请人昵称：{record?.formUser?.nickName}</div>
                    <div>邀请人用户名：{record?.formUser?.userName}</div>
                    <div>邀请人手机号：{record?.formUser?.phone}</div>
                    <div>邀请人等级：{record?.formUser?.level}</div>
                </div>
            },
            renderFormItem: (
                _,
                { type, defaultRender, formItemProps, fieldProps, ...rest },
                form,
            ) => {
                return <Select
                    {...fieldProps}
                    allowClear
                    showSearch
                    placeholder="请输入用户名或手机号"
                    style={{ width: "100%" }}
                    filterOption={false}
                    onSearch={
                        (e) => {
                            if (!e) {
                                return;
                            }
                            searchShop(e);
                        }
                    }
                    fieldNames={{
                        label: "userName",
                        value: "id"
                    }}
                    options={shopOption}
                />
            },
        },
        {
            title: '钱包',
            dataIndex: 'points2',
            valueType: 'text',
            search: false,
        },
        {
            title: '收益',
            dataIndex: 'points1',
            valueType: 'text',
            search: false,
        },
        {
            title: '邀请码',
            dataIndex: 'shareCode',
            valueType: 'text',
            search: true,
        },
        {
            title: '角色类型',
            dataIndex: 'userRole',
            valueType: 'text',
            search: false,
            render: (_, record) => {
                return _ == 0 ? '普通用户' : '公司用户'
            }
        },
        {
            title: '推广权限',
            dataIndex: 'pemType',
            valueType: 'text',
            search: false,
            render: (_, record) => {
                return _ == 0 ? '不能邀请' : '可以邀请'
            }
        },
        {
            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: 'remark',
            valueType: 'text',
            search: false,
        },
        {
            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}
                />

                <UpRole
                    modalOpenState={upRoleDatd}
                    onModalOpenState={setUpRoleDatd}
                    onSubmit={handleUpRole}
                />

                <UpPem
                    modalOpenState={upPemData}
                    onModalOpenState={setUpPemData}
                    onSubmit={handleUpPem}
                />


                <ProTable
                    actionRef={actionRef}
                    rowKey="id"
                    key="logList"
                    search={{
                        labelWidth: 120,
                        defaultCollapsed: false,
                    }}
                    toolBarRender={() => [
                        <Button
                            danger
                            hidden={!access.hasPerms('/api/users/updateUserPemType')}
                            onClick={() => {
                                setUpPemData(true)
                            }}
                        >
                            推广权限
                        </Button>,
                        <Button
                            danger
                            hidden={!access.hasPerms('/api/users/updateUserRoleType')}
                            onClick={() => {
                                setUpRoleDatd(true)
                            }}
                        >
                            修改用户角色
                        </Button>,
                        <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;
