import React, { useState, useEffect, useRef } from 'react';
import { Form, Input, Button, Table, Row, Col, Select, Modal, DatePicker, Space } from 'antd';
import { DeleteOutlined, PlusOutlined } from '@ant-design/icons';
import { getCookie } 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;
const { RangePicker } = DatePicker;
const { Option } = Select;
function RegularManage() {
    useEffect(() => {
        getRegularPage();
    }, []);
    const [regularList, setRegularList] = useState([]);
    const [total, setTotal] = useState(0);
    const [title, setTitle] = useState();
    const [tip, setTip] = useState();
    const [flag, setFlag] = useState(0);
    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
    });
    const [form] = Form.useForm();
    let data = {
        pages: 1,
        current: 1,
        size: size
    }
    //表格数据
    function getRegularPage(param) {
        post(api.getRegularPage, param || params).then((res) => {
            if (res.data.code === 200) {
                const data = res.data.data;
                setRegularList(data.records);
                setTotal(data.total)
            }
        })
    }
    //删除弹窗确认
    function showDelModal(flag) {
        if (flag && !selectedRowKeys.length) {
            message.warning("请先选择要删除的记录~", 1);
            return;
        }
        setDelVisible(flag)
    }
    //删除记录
    function delRegularById() {
        post(api.delRegularById, { ids: selectedRowKeys }).then((res) => {
            if (res.data.code === 200) {
                //刷新列表
                getRegularPage()
                message.success(res.data.message);
            } else {
                message.warning(res.data.message || '操作失败，请重试~');
            }
        });
        showDelModal(false);
    }
    //新增修改跳转
    function showModal(title, type, record) {
        setVisible(true)
        setTitle(title)
        setType(type)
        setRegularDetail(record)
    }
    function cancel() {
        setVisible(false)
    }
    function userChange() {
        setVisible(false)
        getRegularPage()
    }
    function onSizeChange(current, pageSize) {
        params.current = current
        params.size = pageSize
        setSize(pageSize)
        setCurrent(current)
        setParams(params)
        getRegularPage()
    }
    function changePage(page, pageSize) {
        params.current = page
        params.size = pageSize
        setParams(params)
        setCurrent(page)
        getRegularPage()
    }
    const rowSelection = {
        selectedRowKeys,
        onChange: onSelectChange,
    };
    function onSelectChange(selectedRowKeys) {
        let arr = []
        selectedRowKeys.forEach(it => {
            arr.push(it.split('-')[1])
        });
        if (arr.indexOf('1') > 0) {
            setFlag(1)
            setTip('正则式关联字段校验规则，删除后将取消关联且无法恢复，确认删除这' + selectedRowKeys.length + '条正则式？')
        } else {
            setFlag(0)
            setTip('正则式删除后将无法恢复，确认删除这' + selectedRowKeys.length + '条正则式？')
        }

        setSelectedRowKeys(selectedRowKeys);
    };
    const onFinish = (value) => {
        const param = {
            ...data,
            ...value,
        }
        setCurrent(1)
        setParams(param)
        getRegularPage(param);
    };
    const onReset = () => {
        setCurrent(1)
        setParams(data)
        form.resetFields();
        getRegularPage(data);
    };
    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' },
        { title: '说明', dataIndex: 'description', key: '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">
                                <Input placeholder="正则式名称" autoComplete='off' />
                            </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}
                    scroll={{ y: 'calc(100vh - 380px)' }}
                    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
                    }} />
            </div>

            {visible && regularDetail ?
                <Modal
                    title={title}
                    okText='确定'
                    cancelText='取消'
                    width="500px"
                    visible={visible}
                    onCancel={cancel}
                    footer={null}
                    forceRender={true}
                >
                    <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)}
            >
                <p>{tip}</p>
            </Modal>
        </div >
    )
}

export default RegularManage;