import { useEffect, useState } from 'react';
import { useSelector } from 'react-redux'
import { Table, Modal, message, Space, Form, Button, Row, Col, Select } from 'antd';
import { PlusOutlined } from '@ant-design/icons';
import AddNewMsg from './AddNewMsg.js';
import './index.less';
import apiObj from '@api/index';

const { post, api, xPost } = apiObj;
const { Option } = Select;
function MsgManage() {
    useEffect(() => {
        //刷新列表
        getTableData();

    }, []);
    const [isAdd,setIsAdd] = useState(false);   //是否是新增页面
    const [current, setCurrent] = useState(1);       //当前页
    const [size, setSize] = useState(15);       //每页显示条数
    const [total, setTotal] = useState(0);       //消息总数
    const [dataSource, setDataSource] = useState([]);   //列表数据
    const [visible, setVisible] = useState(false);   //弹窗查看
    const [delVisible, setDelVisible] = useState(false);   //弹窗删除
    const [delId,setDelId] = useState('');      //要删除的通知id
    const [confirmLoading, setConfirmLoading] = useState(false);
    const [msgDetail, setMsgDetail] = useState({});
    //从state中取出状态、类型列表
    const staticInfo = useSelector(state => {
        return state.staticInfo;
    });
    const { msgTypeList, msgStatusList } = staticInfo;

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

        })
    }
    //弹窗取消
    function handleCancel() {
        setVisible(false);
    }
    //新增子组织弹窗
    function showMessage(id) {
        getMsgDetail(id);
        setVisible(true);
    }
    //删除消息
    function delMessage(id){
        setDelVisible(true);
        setDelId(id);
    }
    //删除通知
    function postDelMsg() {
        xPost(api.deleteNoticeInfo, { id: delId}).then((res) => {
            const { code } = res.data;
            if (code === 200) {
                getTableData();     //刷新列表
                setDelVisible(false);
                message.success(res.data.msg || '删除成功')
            } else {
                message.warning(res.data.msg || '删除失败，请重试')
            }
        });
    }
    //获取通知详情
    function getMsgDetail(id) {     //type:1我的通知，0通知管理
        xPost(api.getNoticeInfoById, { id: id, type: 0 }).then((res) => {
            const { data, code } = res.data;
            if (code === 200) {
                setMsgDetail(data);
            } else {
                message.warning(res.data.msg || '获取详情失败')
            }
        });
    }
    //每页显示条数切换
    function onSizeChange(current,size){
        const values = form.getFieldsValue();
        const params = {...values,current,size};
        setSize(size);
        getTableData(params);
    }
    //翻页
    function onPageChange(current){
        const values = form.getFieldsValue();
        const params = {...values,current,size};
        setCurrent(current);
        getTableData(params);
    }
    //新增通知
    function showAddMsg(flag){
        setIsAdd(flag);
    }
    //表格渲染
    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: 'operation', render: (row) => {
                    return (<Space size="middle">
                        <a onClick={() => showMessage(row.id)}>查看</a>
                        <a className='delete' onClick={() => delMessage(row.id)}>删除</a>
                    </Space>)
                }
            },
        ];
        return (
            <Table
                rowKey={record => record.id}
                scroll={{ y: 'calc(100vh - 360px)' }}
                columns={columns}
                dataSource={dataSource}
                pagination={{
                   showSizeChanger:true,
                    onShowSizeChange:onSizeChange,
                    pageSizeOptions:[15,30,60,120],
                    defaultPageSize:size,
                    current: current,
                    pageSize:size,
                    size:'small',
                    total: total,
                    showTotal: (total, range) => `第${range[0]}-${range[1]} 条/共 ${total} 条数据`,
                    onChange:onPageChange,
                }}
            />
        )

    }
    //筛选项渲染
    const [form] = Form.useForm();
    const onFinish = (values: any) => {
        getTableData(values);
        console.log('筛选项:', values);
    };
    const onReset = () => {
        form.resetFields();
        getTableData();
    };
    if(isAdd){
        return (<AddNewMsg  goBack={() => showAddMsg(false)}></AddNewMsg>);
    }
    return (
        <div className='wrapper'>
            <div className="filter-box">
                <Form form={form} name="control-hooks" 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={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>
                    <Button type="primary" icon={<PlusOutlined />} onClick={() => showAddMsg(true)}>新增通知</Button>
                </div>
                <RenderTable />
            </div>
            <Modal
                title="查看通知"
                footer={null}
                width={724}
                visible={visible}
                onCancel={()=>setVisible(false)}
                confirmLoading={confirmLoading}
            >
                <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>
            <Modal
                title="删除通知"
                width={400}
                visible={delVisible}
                okText='确定'
                cancelText='取消'
                onOk={postDelMsg}
                onCancel={()=>setDelVisible(false)}
                confirmLoading={confirmLoading}
            >
                <p>确定要删除这条通知吗？</p>
            </Modal>
        </div>
    )
}

export default MsgManage;