import React, { useRef, useState } from "react";
import styles from "./index.less";
import { PageContainer } from '@ant-design/pro-layout';
import { PlusOutlined, UserOutlined } from '@ant-design/icons';
import ProTable from '@ant-design/pro-table';
import { Button, Form, Input, message, Modal, Select, Drawer, Avatar } from 'antd';
import cardAPI from "../service";

/**
 * 储值卡管理
 * @returns 
 */
const storedValueCard = () => {
    const actionRef = useRef();
    const [modalForm] = Form.useForm();
    const [isModalOpen, setIsModalOpen] = useState(false);
    const [currentOption, setCurrentOption] = useState({ id: '' });

    const [current, setCurrent] = useState(1);
    const [pageSize, setPageSize] = useState(10);
    const [total, setTotal] = useState(0);

    // 绑定会员弹窗
    const [bindMemberDrawer, setBindMemberDrawer] = useState(false);
    const [bindCurrentPage, setBindCurrentPage] = useState(1);
    const [bindPageSize, setBindPageSize] = useState(10);
    const [bindTotal, setBindTotal] = useState(0);
    const [bindMemeber, setBindMember] = useState([]);

    /**
     * 点击编辑按钮
     * @param {*} record
     */
    const onEditTableRow = (record) => {
        modalForm.setFieldsValue(record);
        setCurrentOption(record);
        setIsModalOpen(true);
    }

    /**
     * 点击新建
     */
    const onCreateTableRow = () => {
        modalForm.resetFields();
        setCurrentOption({ id: '' })
        setIsModalOpen(true);
    }

    /**
     * 点击绑定会员按钮
     * @param {*} record 
     */
    const onBindMember = (record) => {
        setBindMemberDrawer(true);
        setCurrentOption(record);
        setBindMember([]);
        if (record.memberInfoId) {
            setBindMember([record.memberInfoId]);
        }
    }

    //确定绑定会员
    const onHandleBindMember = async () => {
        if (bindMemeber.length === 0) {
            message.info('请选择要绑定的会员');
            return;
        }
        const response = await cardAPI.OnBindMember({
            "memberInfoId": bindMemeber[0],
            "memberCardId": currentOption.id
        });
        if (response.data === true) {
            message.success('绑定成功');
            actionRef.current.reload();
            setBindMemberDrawer(false);
        } else {
            message.error('绑定失败');
        }
    }

    /**
     * 删除数据
     * @param {*} record 
     */
    const onDeleteTableRow = (record) => {
        console.log('删除', record)
    }

    /**
     * 提交表单
     */
    const onFinish = async (values) => {
        if (values.id) {
            const response = await cardAPI.UpdateMemberCardState({
                id: values.id,
                type: values.type,
                state: values.state
            });
            if (response.statusCode === 200) {
                message.success('更新成功');
                setIsModalOpen(false);
                actionRef.current.reload();
            } else {
                message.error(response.errors || '更新储值卡失败');
            }
        } else {
            const response = await cardAPI.AddMemberCard({
                type: values.type,
                state: values.state
            });
            if (response.statusCode === 200) {
                message.success('添加成功');
                setIsModalOpen(false);
                actionRef.current.reload();
            } else {
                message.error(response.errors || '添加储值卡失败');
            }
        }
    }

    const columns = [
        {
            title: '卡号',
            dataIndex: 'cardNum',
            ellipsis: true,
        },
        {
            title: '会员名称',
            dataIndex: 'memberName',
            ellipsis: true,
            hideInSearch: true
        },
        {
            title: '会员头像',
            dataIndex: 'headImgUrl',
            ellipsis: true,
            width: 100,
            align: 'center',
            hideInSearch: true,
            render: (text, record) => {
                return <Avatar size={64} shape="square" icon={<UserOutlined />} src={record.headImgUrl} />
            }
        },
        {
            title: '会员电话',
            dataIndex: 'phone',
            ellipsis: true,
            hideInSearch: true,
        },
        {
            title: '状态',
            dataIndex: 'state',
            valueType: 'select',
            hideInSearch: true,
            valueEnum: {
                0: {
                    text: '禁用',
                    status: 'Error',
                },
                1: {
                    text: '正常',
                    status: 'Success',
                },
                2: {
                    text: '挂失',
                    status: 'Error',
                },
                3: {
                    text: '作废',
                    status: 'Error',
                },
            },
        },
        {
            title: '类型',
            dataIndex: 'type',
            valueType: 'select',
            hideInSearch: true,
            valueEnum: {
                1: {
                    text: '人脸',
                    status: 'Success',
                },
                2: {
                    text: '实体卡',
                    status: 'Success',
                },
                3: {
                    text: '指纹',
                    status: 'Success',
                }
            },
        },
        {
            title: '操作',
            valueType: 'option',
            key: 'option',
            render: (text, record, _, action) => [
                <a onClick={() => onEditTableRow(record)}>编辑</a>,
                <a onClick={() => onBindMember(record)}>绑定会员</a>,
            ],
        },
    ];

    //选中 当前绑定的会员
    const binRowSelection = {
        onChange: (selectedRowKeys) => {
            setBindMember(selectedRowKeys);
        },
        selectedRowKeys: bindMemeber
    };

    const bindColums = [
        {
            title: '会员头像',
            dataIndex: 'headImgUrl',
            ellipsis: true,
            width: 100,
            align: 'center',
            hideInSearch: true,
            render: (text, record) => {
                return <Avatar size={64} shape="square" icon={<UserOutlined />} src={record.headImgUrl} />
            }
        },
        {
            title: '真实姓名',
            dataIndex: 'realName',
            ellipsis: true,
        },
        {
            title: '联系方式',
            dataIndex: 'phone',
            ellipsis: true,
        }
    ]


    return (
        <PageContainer>
            <div className={styles.member_card_container}>
                <ProTable
                    columns={columns}
                    actionRef={actionRef}
                    request={
                        async (values) => {
                            const response = await cardAPI.GetMemberCardPageList(values);
                            return {
                                data: response.data.data,
                                success: true,
                                total: response.data.total,
                            }
                        }
                    }
                    cardBordered
                    editable={{
                        type: 'multiple',
                    }}
                    rowKey="id"
                    options={{
                        setting: {
                            listsHeight: 400,
                        },
                    }}
                    pagination={{
                        pageSize: pageSize,
                        onChange: (page) => setCurrent(page),
                    }}
                    dateFormatter="string"
                    headerTitle="储值卡管理"
                    toolBarRender={() => [
                        <Button key="button" icon={<PlusOutlined />} type="primary" onClick={onCreateTableRow}>
                            新建
                        </Button>
                    ]}
                />
                <Modal width={600} title={currentOption.id ? '编辑储值卡' : '添加储值卡'} visible={isModalOpen} footer={false} onCancel={() => setIsModalOpen(false)}>
                    <Form
                        name="basic"
                        onFinish={onFinish}
                        form={modalForm}
                        labelCol={{ span: 4 }}
                    >

                        <Form.Item
                            label="id"
                            name="id"
                            hidden={true}
                        >
                            <Input />
                        </Form.Item>

                        <Form.Item
                            label="卡号"
                            name="cardNum"
                        >
                            <Input disabled={true} />
                        </Form.Item>

                        <Form.Item
                            label="状态"
                            name="state"
                            rules={[
                                {
                                    required: true,
                                    message: '请输入选择状态！',
                                },
                            ]}
                        >
                            <Select>
                                <Select.Option value={0}>禁用</Select.Option>
                                <Select.Option value={1}>正常</Select.Option>
                                <Select.Option value={2}>挂失</Select.Option>
                                <Select.Option value={3}>作废</Select.Option>
                            </Select>
                        </Form.Item>

                        <Form.Item
                            label="类型"
                            name="type"
                            rules={[
                                {
                                    required: true,
                                    message: '请输入类型！',
                                },
                            ]}
                        >
                            <Select>
                                <Select.Option value={1}>人脸</Select.Option>
                                <Select.Option value={2}>实体卡</Select.Option>
                                <Select.Option value={3}>指纹</Select.Option>
                            </Select>
                        </Form.Item>

                        <Form.Item>
                            <Button type="primary" htmlType="submit">
                                确定
                            </Button>
                        </Form.Item>
                    </Form>
                </Modal>
                <Drawer width={600} title="绑定会员" placement="right" onClose={() => setBindMemberDrawer(false)} visible={bindMemberDrawer}>
                    <ProTable
                        toolBarRender={() => [
                            <Button key="button" icon={<PlusOutlined />} type="primary" onClick={onHandleBindMember}>
                                确定绑定
                            </Button>
                        ]}
                        rowSelection={{
                            type: 'radio',
                            ...binRowSelection,
                        }}
                        columns={bindColums}
                        cardBordered
                        request={async (params = {}) => {
                            const response = await cardAPI.GetMemberListByPage(params);
                            if (response.statusCode === 200) {
                                setBindTotal(response.data.total);
                                return {
                                    data: response.data.data,
                                    success: true,
                                    total: response.data.total,
                                }
                            }
                        }}
                        rowKey="id"
                        search={{
                            labelWidth: 'auto',
                        }}
                        pagination={{
                            pageSize: bindPageSize,
                            onChange: (page) => setBindCurrentPage(page),
                        }}
                        dateFormatter="string"
                        headerTitle="会员列表"
                    />
                </Drawer>
            </div>
        </PageContainer>
    )
}

export default storedValueCard;