import { ExclamationCircleOutlined, PlusOutlined, DeleteOutlined } from '@ant-design/icons';
import { Button, message, Modal, Switch } from 'antd';
import React, { useRef, useState, useEffect } from 'react';
import { FormattedMessage, useIntl } from 'umi';
import { FooterToolbar, PageContainer } from '@ant-design/pro-layout';
import type { ActionType, ProColumns } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import type { FormInstance } from 'antd';
import { getRewardList, removeReward, updateReward, addReward } from './service';
import UpdateForm from './components/UpdateForm';
import { getDictValueEnum } from '@/services/system/dict';
import DictTag from '@/components/DictTag';
import { useAccess } from 'umi';
import { RewardItem, RewardListParams } from './data';

/**
 * 删除节点
 *
 * @param selectedRows
 */
const handleRemove = async (selectedRows: RewardItem[]) => {
    const hide = message.loading('正在删除');
    if (!selectedRows) return true;
    try {
        await removeReward(selectedRows.map((row) => row.rewardId).join(','));
        hide();
        message.success('删除成功');
        return true;
    } catch (error) {
        hide();
        message.error('删除失败，请重试');
        return false;
    }
};

const handleUpdate = async (fields: RewardItem) => {
    const hide = message.loading('正在更新');
    try {
        const resp = await updateReward(fields);
        hide();
        if (resp.code === 200) {
            message.success('更新成功');
        } else {
            message.error(resp.msg);
        }
        return true;
    } catch (error) {
        hide();
        message.error('配置失败请重试！');
        return false;
    }
};

const handleAdd = async (fields: RewardItem) => {
    const hide = message.loading('正在添加');
    try {
        const resp = await addReward(fields);
        hide();
        if (resp.code === 200) {
            message.success('添加成功');
        } else {
            message.error(resp.msg);
        }
        return true;
    } catch (error) {
        hide();
        message.error('配置失败请重试！');
        return false;
    }
};

const RewardTableList: React.FC = () => {
    const formTableRef = useRef<FormInstance>();

    const [modalVisible, setModalVisible] = useState<boolean>(false);
    const [readOnly, setReadOnly] = useState<boolean>(false);

    const actionRef = useRef<ActionType>();
    const [currentRow, setCurrentRow] = useState<RewardItem>();
    const [selectedRows, setSelectedRows] = useState<RewardItem[]>([]);

    const [statusOptions, setStatusOptions] = useState<any>([]);

    const access = useAccess();

    /** 国际化配置 */
    const intl = useIntl();

    useEffect(() => {
        getDictValueEnum('reward_status').then((data) => {
            setStatusOptions(data);
        });
    }, []);

    const columns: ProColumns<RewardItem>[] = [
        {
            title: '悬赏ID',
            dataIndex: 'rewardId',
            valueType: 'text',
            hideInSearch: true,
        },
        {
            title: '悬赏标题',
            dataIndex: 'title',
            valueType: 'text',
        },
        {
            title: '悬赏金额',
            dataIndex: 'amount',
            valueType: 'money',
            hideInSearch: true,
        },
        // {
        //     title: '悬赏状态',
        //     dataIndex: 'status',
        //     valueType: 'select',
        //     valueEnum: statusOptions,
        //     render: (_, record) => {
        //         return (<DictTag enums={statusOptions} value={record.status} />);
        //     },
        // },
        {
            title: '发布时间',
            dataIndex: 'createTime',
            valueType: 'dateRange',
            render: (_, record) => {
                return (<span>{record.createTime?.toString()}</span>);
            },
            search: {
                transform: (value) => {
                    return {
                        'params[beginTime]': value[0],
                        'params[endTime]': value[1],
                    };
                },
            },
        },
        {
            title: '备注',
            dataIndex: 'remark',
            valueType: 'text',
            hideInSearch: true,
        },
        {
            title: <FormattedMessage id="pages.searchTable.titleOption" defaultMessage="操作" />,
            dataIndex: 'option',
            width: '220px',
            valueType: 'option',
            render: (_, record) => [
                <Button
                    type="link"
                    size="small"
                    key="view"
                    onClick={() => {
                        setModalVisible(true);
                        setCurrentRow(record);
                        // 设置只读模式
                        setReadOnly(true);
                    }}
                >
                    查看
                </Button>,
                <Button
                    type="link"
                    size="small"
                    key="edit"
                    hidden={!access.hasPerms('reward:reward:edit')}
                    onClick={() => {
                        setModalVisible(true);
                        setCurrentRow(record);
                        setReadOnly(false);
                    }}
                >
                    编辑
                </Button>,
                <Button
                    type="link"
                    size="small"
                    danger
                    key="batchRemove"
                    hidden={!access.hasPerms('reward:reward:remove')}
                    onClick={async () => {
                        Modal.confirm({
                            title: '删除',
                            content: '确定删除该项吗？',
                            okText: '确认',
                            cancelText: '取消',
                            onOk: async () => {
                                const success = await handleRemove([record]);
                                if (success) {
                                    if (actionRef.current) {
                                        actionRef.current.reload();
                                    }
                                }
                            },
                        });
                    }}
                >
                    删除
                </Button>,
            ],
        },
    ];

    return (
        <PageContainer>
            <div style={{ width: '100%', float: 'right' }}>
                <ProTable<RewardItem>
                    headerTitle={intl.formatMessage({
                        id: 'pages.searchTable.title',
                        defaultMessage: '信息',
                    })}
                    actionRef={actionRef}
                    formRef={formTableRef}
                    rowKey="rewardId"
                    key="rewardList"
                    search={{
                        labelWidth: 120,
                    }}
                    toolBarRender={() => [
                        <Button
                            type="primary"
                            key="add"
                            hidden={!access.hasPerms('reward:reward:add')}
                            onClick={async () => {
                                setCurrentRow(undefined);
                                setModalVisible(true);
                            }}
                        >
                            <PlusOutlined /> <FormattedMessage id="pages.searchTable.new" defaultMessage="新建" />
                        </Button>,
                        <Button
                            type="primary"
                            key="remove"
                            danger
                            hidden={selectedRows?.length === 0 || !access.hasPerms('reward:reward:remove')}
                            onClick={async () => {
                                Modal.confirm({
                                    title: '是否确认删除所选数据项?',
                                    icon: <ExclamationCircleOutlined />,
                                    content: '请谨慎操作',
                                    async onOk() {
                                        const success = await handleRemove(selectedRows);
                                        if (success) {
                                            setSelectedRows([]);
                                            actionRef.current?.reloadAndRest?.();
                                        }
                                    },
                                    onCancel() { },
                                });
                            }}
                        >
                            <DeleteOutlined />
                            <FormattedMessage id="pages.searchTable.delete" defaultMessage="删除" />
                        </Button>,
                    ]}
                    request={(params) =>
                        getRewardList({ ...params } as RewardListParams).then((res) => {
                            return {
                                data: res.rows,
                                total: res.total,
                                success: true,
                            };
                        })
                    }
                    columns={columns}
                    rowSelection={{
                        onChange: (_, selectedRows) => {
                            setSelectedRows(selectedRows);
                        },
                    }}
                />
            </div>
            {selectedRows?.length > 0 && (
                <FooterToolbar
                    extra={
                        <div>
                            <FormattedMessage id="pages.searchTable.chosen" defaultMessage="已选择" />
                            <a style={{ fontWeight: 600 }}>{selectedRows.length}</a>
                            <FormattedMessage id="pages.searchTable.item" defaultMessage="项" />
                        </div>
                    }
                >
                    <Button
                        key="remove"
                        danger
                        hidden={!access.hasPerms('reward:reward:remove')}
                        onClick={async () => {
                            Modal.confirm({
                                title: '删除',
                                content: '确定删除该项吗？',
                                okText: '确认',
                                cancelText: '取消',
                                onOk: async () => {
                                    const success = await handleRemove(selectedRows);
                                    if (success) {
                                        setSelectedRows([]);
                                        actionRef.current?.reloadAndRest?.();
                                    }
                                },
                            });
                        }}
                    >
                        <FormattedMessage id="pages.searchTable.batchDeletion" defaultMessage="批量删除" />
                    </Button>
                </FooterToolbar>
            )}
            <UpdateForm
                readOnly={readOnly}
                onSubmit={async (values) => {
                    let success = false;
                    if (values.rewardId) {
                        success = await handleUpdate({ ...values } as RewardItem);
                    } else {
                        success = await handleAdd({ ...values } as RewardItem);
                    }
                    if (success) {
                        setModalVisible(false);
                        setCurrentRow(undefined);
                        if (actionRef.current) {
                            actionRef.current.reload();
                        }
                    }
                }}
                onCancel={() => {
                    setModalVisible(false);
                    setCurrentRow(undefined);
                    setReadOnly(false);
                }}
                open={modalVisible}
                values={currentRow || {}}
                statusOptions={statusOptions}
            />
        </PageContainer>
    );
};

export default RewardTableList;