import { useEffect, useState } from 'react';
import { useSelector, useDispatch } from 'react-redux'
import { Table, Modal, message, Menu, Breadcrumb, Dropdown, Space, Form, Input, Button, Row, Col, Select } from 'antd';
import { DownOutlined, PlusOutlined } from '@ant-design/icons';
import './index.less';
import apiObj from '@api/index';
import { setUnReadNum } from '@reducers/userInfo.js';
const { post, api, xPost } = apiObj;
const { Option } = Select;
function MyMessage() {
    const dispatch = useDispatch();
    useEffect(() => {
        //刷新列表
        getTableData();

    }, []);

    const [size, setSize] = useState(15);       //每页显示条数
    const [current, setCurrent] = useState(1);//当前页
    const [params, setParams] = useState({
        pages: 1,
        current: 1,
        size: 15
    });
    const [total, setTotal] = useState(0);       //每页显示条数
    const [dataSource, setDataSource] = useState([]);   //列表数据
    const [visible, setVisible] = useState(false);   //弹窗查看
    const [confirmLoading, setConfirmLoading] = useState(false);
    const [msgDetail, setMsgDetail] = useState({});
    //从state中取出状态、类型列表
    const staticInfo = useSelector(state => {
        return state.staticInfo;
    });
    const toUnRead = useSelector(state => {     //是否筛选未读
        //console.log(43,state)
        return state.tabPanes.toUnRead;
    });

    const { msgTypeList, msgStatusList } = staticInfo;

    //获取表格数据
    function getTableData(param = {}) {
        post(api.listPage, param).then((res) => {
            if (res.data.code === 200) {
                let data = res.data.data;
                setTotal(data.total);
                setDataSource(data.records);
            }

        })
    }
    //弹窗取消
    function handleCancel() {
        setVisible(false);
    }
    //获取未读消息数量
    function getNotNoticeCount() {
        xPost(api.getNotNoticeCount).then((res) => {
            if (res.data.code === 200) {
                let count = res.data.data.count;
                count = count > 99 ? '99+' : count;
                dispatch(setUnReadNum(count));
            } else {
                //message.warning(res.data.msg || '请求失败');
            }
        })
    }
    //查看消息弹窗
    function showMessage(id) {
        getMsgDetail(id);
        setVisible(true);
    }
    //获取消息详情
    function getMsgDetail(id) {     //type:1我的通知，0通知管理
        xPost(api.getNoticeInfoById, { id: id, type: 1 }).then((res) => {
            const { data, code } = res.data;
            if (code === 200) {
                setMsgDetail(data);
                //更新未读消息数量
                getNotNoticeCount();
                getTableData(params);//刷新列表
            } else {
                message.warning(res.data.message || '获取详情失败')
            }
        });
    }
    //每页显示条数切换
    function onSizeChange(current, pageSize) {
        params.current = current
        params.size = pageSize
        setSize(pageSize)
        setCurrent(current)
        setParams(params)
        getTableData(params)
    }
    //翻页
    function onPageChange(page, pageSize) {
        params.current = page
        params.size = pageSize
        setCurrent(page)
        setParams(params)
        getTableData(params)
    }
    //表格渲染
    function RenderTable() {
        const columns = [
            { title: '标题', dataIndex: 'title', key: 'title' },
            {
                title: '类型', width: 150, dataIndex: 'typeName', key: 'typeName'
            },
            { title: '发送者', dataIndex: 'sender', key: 'sender' },
            { title: '发送时间', width: 240, dataIndex: 'gmtCreate', key: 'gmtCreate' },
            {
                title: '阅读状态', key: 'statusName', dataIndex: 'statusName'
            },
            {
                title: '操作', key: 'operation', render: (row) => {
                    return (<Space size="middle">
                        <a onClick={() => showMessage(row.id)}>查看</a>
                    </Space>)
                }
            },
        ];
        return (
            <Table
                rowKey={record => record.id}
                scroll={{ y: 'calc(100vh - 360px)' }}
                columns={columns}
                dataSource={dataSource}
                pagination={{
                    showSizeChanger: true,
                    pageSizeOptions: [15, 30, 60, 120],
                    defaultPageSize: size,
                    pageNo: 1,
                    current: current,
                    size: 'small',
                    total: total,
                    showTotal: (total, range) => `第${range[0]}-${range[1]} 条/共 ${total} 条数据`,
                    onShowSizeChange: (current, pageSize) => onSizeChange(current, pageSize), // 改变每页数量时更新显示
                    onChange: (page, pageSize) => onPageChange(page, pageSize),//点击页码事件
                }}
            />
        )

    }
    //筛选项渲染
    const [form] = Form.useForm();
    const initialValues = { status: toUnRead ? '0' : '' };
    const onFinish = (values) => {
        getTableData(values);
        console.log('筛选项:', values);
    };
    const onReset = () => {
        form.resetFields();
        getTableData();
    };
    return (
        <div className='wrapper'>
            <div className="filter-box">
                <Form form={form} name="control-hooks" initialValues={initialValues} onFinish={onFinish}>
                    <Row gutter={24}>
                        <Col span={5} key={1}>
                            <Form.Item name="type" label="通知类型">
                                <Select
                                    allowClear
                                >
                                    {msgTypeList.map((item) => {
                                        return (
                                            <Option value={item.name} key={item.name}>{item.val}</Option>
                                        )
                                    })}
                                </Select>
                            </Form.Item>
                        </Col>
                        <Col span={5} key={2}>
                            <Form.Item name="status" label="阅读状态">
                                <Select
                                    allowClear
                                >
                                    {msgStatusList.map((item) => {
                                        return (
                                            <Option value={item.name} key={item.name}>{item.val}</Option>
                                        )
                                    })}
                                </Select>
                            </Form.Item>
                        </Col>
                        <Col span={9} key={3}>
                            <Form.Item>
                                <Button type="primary" htmlType="submit">
                                    查询
                                </Button>
                                <Button htmlType="button" onClick={onReset}>
                                    重置
                                </Button>
                            </Form.Item>
                        </Col>
                    </Row>
                </Form>
            </div>
            <div className="table">
                <div className="table-header">
                    <h2 className="table-title">我的通知</h2>
                </div>
                <RenderTable />
            </div>
            <Modal
                title="查看通知"
                footer={null}
                width={724}
                visible={visible}
                confirmLoading={confirmLoading}
                onCancel={() => setVisible(false)}
            >
                <div className="message-box">
                    <p className='msg-title'>{msgDetail.title}</p>
                    <div className="msg-content" dangerouslySetInnerHTML={{ __html: msgDetail.content }}></div>
                    <div className="msg-footer">
                        <span className="msg-type">类型：{msgDetail.typeName}</span>
                        <span className="msg-sender">发送者：{msgDetail.creatorName}</span>
                        <span className="msg-time">发送时间：{msgDetail.gmtCreate}</span>
                    </div>
                </div>
                <p className='message-oper'><Button type='primary' onClick={handleCancel}>返回</Button></p>
            </Modal>
        </div>
    )
}

export default MyMessage;