import React, { useState, useEffect, useRef } from 'react';
import { useSelector } from 'react-redux';
import { Form, Input, Button, Table, Row, Col, Spin, Modal, Space } from 'antd';
import { PlusOutlined } from '@ant-design/icons';
import { getValueFromEvent } from '@utils/index'
import '@common/common.less';
import apiObj from '@api/index';
import AddRegular from './addRegular';
import RegularContext from './regular-context';
import { message } from "antd/lib/index";
const { post, api, xPost } = apiObj;
function RegularManage() {

    const [regularList, setRegularList] = useState([]);
    const [total, setTotal] = useState(0);
    const [title, setTitle] = useState();
    const [tip, setTip] = useState();
    const [flag, setFlag] = useState(0);
    const [loading, setLoading] = useState(false);
    const [type, setType] = useState(0);//1新增 2修改
    const [visible, setVisible] = useState(false);
    const [delvisible, setDelVisible] = useState(false);
    const [selectedRowKeys, setSelectedRowKeys] = useState([]);
    const [size, setSize] = useState(15);
    const [current, setCurrent] = useState(1);
    const [regularDetail, setRegularDetail] = useState(null);//详情数据
    const [params, setParams] = useState({
        pages: 1,
        current: 1,
        size: 15,
        desc: ['dri.gmt_create']
    });
    const [form] = Form.useForm();
    let data = {
        pages: 1,
        current: 1,
        size: 15,
        desc: ['dri.gmt_create']
    }
    const { regularNum } = useSelector((state) => {
        return state.userInfo;
    });
    useEffect(() => {
        setCurrent(1)
        setSize(15)
        setParams(data)
        form.resetFields();
        setSelectedRowKeys([])
        getRegularPage(data);
    }, [regularNum]);
    //表格数据
    function getRegularPage(param) {
        setLoading(true)
        const hide = message.loading('加载中...', 0);
        post(api.getRegularPage, param || params).then((res) => {
            hide()
            if (res.data.code === 200) {
                const data = res.data.data;
                setRegularList(data.records);
                setTotal(data.total)
            }
        }).catch((err) => {
            hide()
        })
    }
    //判断正则是否关联
    function isRelation(param) {
        post(api.isRelation, {
            id: param.id,
            name: param.name,
            val: param.val,
        }).then((res) => {
            if (res.data.code === 200) {
                const data = res.data.data;
                setFlag(data ? 1 : 0)
            }
        })
    }
    //删除弹窗确认
    function showDelModal(flag) {
        if (flag && !selectedRowKeys.length) {
            message.warning("请先选择要删除的记录~", 1);
            return;
        }
        setDelVisible(flag)
    }
    //删除记录
    function delRegularById() {
        let arr = []
        selectedRowKeys.forEach(it => {
            arr.push(it.split('-')[0])
        });
        post(api.delRegularById, { ids: arr }).then((res) => {
            if (res.data.code === 200) {
                //刷新列表
                const totalPage = Math.ceil((total - selectedRowKeys.length) / 15);
                //将当前页码与删除数据之后的总页数进行比较，避免当前页码不存在
                const pagenum =
                    params.current > totalPage ? totalPage : params.current;
                //避免pagenum变为0
                params.current = pagenum < 1 ? 1 : pagenum;
                setParams(params)
                console.log(params.current);
                getRegularPage()
                message.success(res.data.message);
            } else {
                message.warning(res.data.message || '操作失败，请重试~');
            }
        });
        showDelModal(false);
        setSelectedRowKeys([])
    }
    //新增修改跳转
    function showModal(title, type, record) {
        setVisible(true)
        setTitle(title)
        setType(type)
        setRegularDetail(record)
        setFlag(0)
        if (type == 2) {
            isRelation(record)
        }
    }
    function cancel() {
        setVisible(false)
        setRegularDetail(null)
    }
    function userChange() {
        setVisible(false)
        getRegularPage()
        setRegularDetail(null)
        setSelectedRowKeys([])
    }
    function onSizeChange(current, pageSize) {
        params.current = current
        params.size = pageSize
        setSize(pageSize)
        setCurrent(current)
        setParams(params)
    }
    function changePage(page, pageSize) {
        params.current = page
        params.size = pageSize
        setParams(params)
        setCurrent(page)
        getRegularPage()
        setSelectedRowKeys([])
    }
    const rowSelection = {
        selectedRowKeys,
        onChange: onSelectChange,
    };
    function onSelectChange(selectedRowKeys) {
        let arr = []
        selectedRowKeys.forEach(it => {
            arr.push(it.split('-')[1])
        });
        if (arr.indexOf('1') >= 0) {
            setTip('正则式关联字段校验规则，删除后将取消关联且无法恢复，确认删除这' + selectedRowKeys.length + '条正则式？')
        } else {
            setTip('正则式删除后将无法恢复，确认删除这' + selectedRowKeys.length + '条正则式？')
        }

        setSelectedRowKeys(selectedRowKeys);
    };
    const onFinish = (value) => {
        params.current = 1
        const param = {
            ...params,
            ...value,
        }
        setCurrent(1)
        setParams(param)
        getRegularPage(param);
        setSelectedRowKeys([])
    };
    const onReset = () => {
        setCurrent(1)
        setSize(15)
        setParams(data)
        form.resetFields();
        getRegularPage(data);
        setSelectedRowKeys([])
    };
    const columns = [
        { title: '序号', dataIndex: 'index', render: (text, record, index) => (current - 1) * params.size + index + 1 },
        { title: '正则式名称', dataIndex: 'name', key: 'name' },
        {
            title: '正则式值', dataIndex: 'val', key: 'val', render: (text, record) => {
                return record.val.length > 20 ? <span title={record.val}>{record.val.substring(0, 20) + '...'}</span> : record.val;
            }
        },
        {
            title: '说明', dataIndex: 'description', key: 'description', render: (text, record) => {
                return (record.description || "-").length > 20 ? <span title={record.description}>{record.description.substring(0, 20) + '...'}</span> : record.description;
            }
        },
        {
            title: '操作', dataIndex: 'key', render: (text, record) => (
                <Space size="middle">
                    <a onClick={() => showModal('修改正则式', 2, record)}>修改</a>
                </Space>
            )
        }
    ];

    return (
        <div className="wrapper">
            <div className="filter-box">
                <Form
                    form={form}
                    name="normal_login"
                    onFinish={onFinish}
                >
                    <Row gutter={24}>
                        <Col span={5} key={0}>
                            <Form.Item label="正则式名称" name="name" getValueFromEvent={getValueFromEvent}>
                                <Input placeholder="请输入" autoComplete='off' allowClear maxLength='30' />
                            </Form.Item>
                        </Col>

                        <Col span={6} key={7}>
                            <Form.Item>
                                <Button type="primary" htmlType="submit">
                                    查询
                                </Button>
                                <Button onClick={onReset}>
                                    重置
                                </Button>
                            </Form.Item>
                        </Col>
                    </Row>
                </Form>
            </div>

            <div className="table">
                <div className="table-header">
                    <h2 className="table-title">正则式维护</h2>
                    <Space size="middle">
                        <Button type="primary" icon={<PlusOutlined />} onClick={() => showModal('新增正则式', 1, {})}>新增</Button>
                        <Button type="primary" onClick={() => showDelModal(true)} danger>删除</Button>
                    </Space>

                </div>
                <Table
                    columns={columns}
                    rowSelection={rowSelection}
                    dataSource={regularList}
                    rowKey={record => record.id + '-' + record.relation}
                    pagination={{
                        pageSize: size,
                        size: 'small',
                        current: current,
                        showSizeChanger: true,
                        pageSizeOptions: ['15', '30', '60', '120'],
                        showTotal: (total, range) => `第${range[0]}-${range[1]} 条/共 ${total} 条数据`,
                        onShowSizeChange: (current, pageSize) => onSizeChange(current, pageSize), // 改变每页数量时更新显示
                        onChange: (page, pageSize) => changePage(page, pageSize),//点击页码事件
                        total: total,
                        showQuickJumper:true,
                    }} />
            </div>

            {visible && regularDetail ?
                <Modal
                    title={title}
                    okText='确定'
                    cancelText='关闭'
                    width="500px"
                    visible={visible}
                    onCancel={cancel}
                    footer={null}
                    forceRender={true}
                    maskClosable={false}
                >
                    <RegularContext.Provider value={{ regularDetail, type, flag }}>
                        <AddRegular userChange={userChange} cancel={cancel} />
                    </RegularContext.Provider>

                </Modal>
                : ''}

            <Modal
                title="删除正则式"
                okText='确定'
                cancelText='关闭'
                width={400}
                visible={delvisible}
                onOk={delRegularById}
                /*confirmLoading={confirmLoading}*/
                onCancel={() => showDelModal(false)}
                maskClosable={false}
            >
                <p>{tip}</p>
            </Modal>
        </div >
    )
}

export default RegularManage;