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

/**
 * 储值卡账户管理
 * @returns 
 */
const memberAccount = () => {
    const actionRef = useRef();
    const [isModalOpen, setIsModalOpen] = useState(false);
    const [currentOption, setCurrentOption] = useState({
        functionName: '',
        record: {},
        type: 0
    });
    const [current, setCurrent] = useState(1);
    const [pageSize, setPageSize] = useState(10);
    const [total, setTotal] = useState(0);

    //消费记录
    const [consList, setConsList] = useState();
    const [consCurrent, setConsCurrent] = useState(1);
    const [consPageSize, setConsPageSize] = useState(10);
    const [consTotal, setConsTotal] = useState(0);

    const [expendTotalCount, setExpendTotalCount] = useState(0);
    const [personTotalcCount, setPersonTotalcCount] = useState(0);
    const [dateRange, setDateRange] = useState();

    /**
     * 获取账户消费、充值记录
     * @param {*} record 
     */
    const onFetchAccountConsRecord = async (record, type) => {
        const jsonData = {
            "current": consCurrent,
            "pageSize": consPageSize,
            "memberInfoId": record.memberInfoId,
            "memberCardId": "",
            "type": type
        }
        if (dateRange) {
            jsonData.startTime = dateRange[0];
            jsonData.endTime = dateRange[1];
        }
        const response = await cardAPI.GetMemberAccountCardConsRecord(jsonData);
        setCurrentOption({
            functionName: 'onFetchAccountConsRecord',
            record: JSON.parse(JSON.stringify(record)),
            type
        });
        if (response.statusCode === 200) {
            setConsList(response.data.data);
            setConsTotal(response.data.total);
            setIsModalOpen(true);
        } else {
            message.error(response.errors);
        }
    }

    /**
     * 查询会员卡消费、充值记录
     * @param {*} record 
     */
    const onFetchCardConsRecord = async (record, type) => {
        const jsonData = {
            "current": consCurrent,
            "pageSize": consPageSize,
            "memberInfoId": record.memberInfoId,
            "memberCardId": record.id,
            "type": type
        }
        if (dateRange) {
            jsonData.startTime = dateRange[0];
            jsonData.endTime = dateRange[1];
        }
        const response = await cardAPI.GetMemberAccountCardConsRecord(jsonData);
        setCurrentOption({
            functionName: 'onFetchCardConsRecord',
            record: JSON.parse(JSON.stringify(record)),
            type
        });
        if (response.statusCode === 200) {
            setConsList(response.data.data);
            setConsTotal(response.data.total);
            setIsModalOpen(true);
        } else {
            message.error(response.errors);
        }
    }

    //账号列表
    const columns = [
        {
            title: '起止时间',
            dataIndex: 'dateRange',
            hideInTable: true,
            valueType: 'dateRange'
        },
        {
            title: '头像',
            dataIndex: 'headImgUrl',
            ellipsis: true,
            width: 100,
            hideInSearch: true,
            align: 'center',
            render: (text, record) => {
                return <Avatar size={64} shape="square" icon={<UserOutlined />} src={record.headImgUrl} />
            }
        },
        {
            title: '姓名',
            dataIndex: 'name',
            ellipsis: true,
        },
        {
            title: '卡号',
            dataIndex: 'memberCardNum',
            ellipsis: true,
        },
        {
            title: '联系方式',
            dataIndex: 'memberPhone',
            ellipsis: true,
            hideInSearch: true,
        },
        {
            title: '余额',
            dataIndex: 'money',
            hideInSearch: true,
        },

        {
            title: '操作',
            valueType: 'option',
            key: 'option',
            render: (text, record) => [
                <a onClick={() => onFetchAccountConsRecord(record, -1)}>账户消费记录</a>,
                // <a onClick={() => onFetchAccountConsRecord(record, 1)}>账户充值记录</a>,
            ],
        },
    ];

    //会员卡列表
    const expandedRowRender = (record) => {
        const expandedColumns = [
            {
                title: '卡号',
                dataIndex: 'cardNum',
                key: 'cardNum',
            },
            {
                title: '状态',
                dataIndex: 'state',
                valueType: 'select',
                valueEnum: {
                    0: {
                        text: '禁用',
                        status: 'Error',
                    },
                    1: {
                        text: '正常',
                        status: 'Success',
                    },
                    2: {
                        text: '挂失',
                        status: 'Error',
                    },
                    3: {
                        text: '作废',
                        status: 'Error',
                    },
                },
            },
            {
                title: '类型',
                dataIndex: 'type',
                valueType: 'select',
                valueEnum: {
                    1: {
                        text: '人脸',
                        status: 'Success',
                    },
                    2: {
                        text: '实体卡',
                        status: 'Success',
                    },
                    3: {
                        text: '指纹',
                        status: 'Success',
                    }
                },
            },
            {
                title: '操作',
                valueType: 'option',
                key: 'option',
                render: (text, record) => [
                    <a onClick={() => onFetchCardConsRecord(record, -1)}>会员卡消费记录</a>,
                    // <a onClick={() => onFetchCardConsRecord(record, 1)}>会员卡充值记录</a>,
                ],
            }
        ];
        return <ProTable toolBarRender={false} search={false} rowKey="id" columns={expandedColumns} dataSource={record.cards} pagination={false} />;
    };

    //消费列表
    const consColumns = [
        {
            title: '时间',
            dataIndex: 'createAt',
            width: 200
        },
        {
            title: '类型',
            dataIndex: 'type',
            ellipsis: true,
            render: (_, record) => {
                return <div>
                    {
                        record.type == '-1' ? '消费' : '充值'
                    }
                </div>
            }
        },
        // {
        //     title: '之前余额',
        //     dataIndex: 'beforeMoney',
        //     render: (_, record) => {
        //         return <div style={{ color: 'green' }}>
        //             {record.beforeMoney}
        //         </div>
        //     }
        // },
        // {
        //     title: '消费金额',
        //     dataIndex: 'money',
        //     render: (_, record) => {
        //         return <div style={{ color: 'red' }}>
        //             {record.money}
        //         </div>
        //     }
        // },
        // {
        //     title: '之后余额',
        //     dataIndex: 'afterMoney',
        //     render: (_, record) => {
        //         return <div style={{ color: 'blue' }}>
        //             {record.afterMoney}
        //         </div>
        //     }
        // }
    ];

    useEffect(() => {
        if (consCurrent === 1) return;
        if (currentOption.functionName === 'onFetchAccountConsRecord') {
            onFetchAccountConsRecord(currentOption.record, currentOption.type);
        } else if (currentOption.functionName === 'onFetchCardConsRecord') {
            onFetchCardConsRecord(currentOption.record, currentOption.type);
        }
    }, [consCurrent])

    return (
        <PageContainer>
            <div className={styles.member_card_container}>
                <ProTable
                    title={() => <div className={styles.expend_total_count}>消费次数{expendTotalCount}，消费人数{personTotalcCount}</div>}
                    columns={columns}
                    actionRef={actionRef}
                    expandable={{
                        expandedRowRender: record => expandedRowRender(record)
                    }}
                    request={
                        async (values) => {
                            if (values.memberCardNum) {
                                values.cardNum = values.memberCardNum;
                            }
                            if (values.dateRange) {
                                setDateRange(values.dateRange);
                                const response = await cardAPI.GetMemberAccountRecordTotal({
                                    startTime: values.dateRange[0],
                                    endTime: values.dateRange[1]
                                });
                                if (response.statusCode === 200) {
                                    setExpendTotalCount(response.data.expendTotalCount);
                                    setPersonTotalcCount(response.data.personTotalcCount);
                                }
                            } else {
                                setDateRange(null);
                                setExpendTotalCount(0);
                                setPersonTotalcCount(0);
                            }
                            delete values.dateRange;
                            delete values.memberCardNum;
                            const response = await cardAPI.GetMemberAccountPageList(values);
                            setTotal(response.data.data);
                            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="储值卡账户管理"
                />
                <Modal width={800} title='消费记录' visible={isModalOpen} footer={false} onCancel={() => { setIsModalOpen(false); setConsCurrent(1) }}>
                    <Table columns={consColumns} dataSource={consList} pagination={{
                        current: consCurrent,
                        pageSize: consPageSize,
                        total: consTotal,
                        onChange: (page, pageSize) => {
                            setConsCurrent(page);
                            setConsPageSize(pageSize);
                        }
                    }} />
                </Modal>
            </div>
        </PageContainer>
    )
}

export default memberAccount;