import React, { useState, useEffect, useRef } from 'react';
import { useSelector, useDispatch } from 'react-redux';
import { Form, Input, Button, Table, Row, Col, Select, Modal, Spin, Space, message } from 'antd';
import { PlusOutlined } from '@ant-design/icons';
import '@common/common.less';
import apiObj from '@api/index';
import AddRules from './addRules';
import FiledContext from './filed-context';
import { getValueFromEvent } from '@utils/index'
const { post, api, xPost } = apiObj;
const { Option } = Select;

function FieldRules() {
    const [addVisible, setAddVisible] = useState(false);         //新增页面显示
    const [logList, setLogList] = useState([]);
    const [total, setTotal] = useState(0);
    const [type, setType] = useState(0);//1新增 2修改
    const [visible, setVisible] = useState(false);
    const [size, setSize] = useState(15);
    const [current, setCurrent] = useState(1);
    const [loading, setLoading] = useState(false);
    const [regularList, setRegularList] = useState([]);//正则式数据
    const [selectedRowKeys, setSelectedRowKeys] = useState([]);
    const [tableList, setTableList] = useState([]);//表名称
    const [colList, setColList] = useState([]);//字段名称
    const [tableCname, setTableCname] = useState(null);//字段名称
    const [tableEname, setTableEname] = useState(null);//字段名称
    const [disable, setDisable] = useState(true);//字段名称
    const [filedDetail, setFiledDetail] = useState(null);//详情数据
    const [params, setParams] = useState({
        pages: 1,
        current: 1,
        size: 15,
        desc: ['gmt_create']
    });
    const [form] = Form.useForm();
    let data = {
        pages: 1,
        current: 1,
        size: 15,
        desc: ['gmt_create']
    }
    const { rulerNum } = useSelector((state) => {
        return state.userInfo;
    });
    useEffect(() => {
        setCurrent(1)
        setSize(15)
        setParams(data)
        form.resetFields();
        getRegular()
        getTableName()
        getColumnName('', '', '', '')
        getColumnVerifyPage(data);
        setSelectedRowKeys([])
        setDisable(true)
    }, [rulerNum]);
    //表格数据
    function getColumnVerifyPage(param) {
        const hide = message.loading('加载中...', 0);
        post(api.getColumnVerifyPage, param || params).then((res) => {
            hide()
            if (res.data.code === 200) {
                const data = res.data.data;
                setLogList(data.records);
                setTotal(data.total)
            }
        }).catch((err) => {
            hide()
        })
    }
    //获取正则式名称
    function getRegular(name) {
        const param = {
            name: name || ''
        }
        post(api.getRegular, param).then((res) => {
            if (res.data.code === 200) {
                const data = res.data.data;
                setRegularList(data);
            }
        })
    }
    //获取字段名
    function getColumnName(columnCname, columnEname, tableCname, tableEname) {
        const param = {
            columnCname: columnCname,
            columnEname: columnEname,
            tableCname: tableCname,
            tableEname: tableEname
        }
        post(api.getColumnName, param).then((res) => {
            if (res.data.code === 200) {
                const data = res.data.data;
                setColList([...data]);
            }
        })
    }
    //获取表名称
    function getTableName(tableCname, tableEname) {
        const param = {
            tableCname: tableCname,
            tableEname: tableEname
        }
        post(api.getTableName, param).then((res) => {
            if (res.data.code === 200) {
                const data = res.data.data;
                setTableList([...data]);
            }
        })
    }
    //表名称搜索(中文)
    function cnameSearch(val) {
        getTableName(val, '')
    }
    //表名称搜索(英文)
    function enameSearch(val) {
        getTableName('', val)
    }
    //字段名称搜索(中文)
    function colmeSearch(val) {
        const formData = form.getFieldsValue();
        getColumnName(val, '', formData.tableCname, '')
    }
    //字段名称搜索(英文)
    function coleneSearch(val) {
        const formData = form.getFieldsValue();
        getColumnName('', val, '', formData.tableEname)
    }
    //正则式名称搜索
    function onSearch(val) {
        getRegular(val)
    }
    //删除记录
    function delColumnVerify() {
        post(api.delColumnVerify, { ids: selectedRowKeys }).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)
                getColumnVerifyPage()
                message.success(res.data.message);
            } else {
                message.warning(res.data.message || '操作失败，请重试~');
            }
        });
        showDelModal(false);
        setSelectedRowKeys([])
    }
    //删除弹窗确认
    function showDelModal(flag) {
        if (flag && !selectedRowKeys.length) {
            message.warning("请先选择要删除的记录~", 1);
            return;
        }
        setVisible(flag)
    }
    //新增修改跳转
    function showModal(type, id) {
        setAddVisible(true)
        setType(type)
        if (type == 1) {
            setFiledDetail({
                columnList: [{
                    columnCname: undefined,
                    columnEname: undefined,
                    ableCname: undefined,
                    tableEname: undefined,
                    id: undefined
                }],
                standardValueList: [{
                    tit: null
                }]
            })
        } else {
            getByIdColumnVerify(id)
        }

    }
    //详情
    function getByIdColumnVerify(id) {
        const param = {
            columnId: id,
        }
        post(api.getByIdColumnVerify, param).then((res) => {
            if (res.data.code === 200) {
                const data = res.data.data;
                let obj = []
                if (data.standardValueList) {
                    data.standardValueList.forEach(it => {
                        obj.push({
                            tit: it
                        })
                    });
                    console.log(obj);
                } else {
                    obj = [{ tit: null }]
                }
                delete data.standardValueList
                const arr = {
                    columnList: [{
                        columnCname: data.columnCname,
                        columnEname: data.columnEname,
                        tableCname: data.tableCname,
                        tableEname: data.tableEname,
                        disable: true,
                        id: data.columnId
                    }],
                    standardValueList: obj,
                    regularName: data.regular,
                    ...data
                }
                setFiledDetail(arr)
            }
        })
    }
    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)
        getColumnVerifyPage()
        setSelectedRowKeys([])
    }
    function onSelectChange(selectedRowKeys) {
        setSelectedRowKeys(selectedRowKeys);
    };
    function tableCnameChange(value, option) {
        setTableCname(value)
        getColumnName('', '', value, '')
        if (value) {
            form.setFieldsValue({
                tableEname: option.val,
                columnCname: undefined,
                columnEname: undefined,
            });
            setDisable(false)
        } else {
            form.setFieldsValue({
                tableEname: undefined,
                columnCname: undefined,
                columnEname: undefined,
            })
            setDisable(true)
            getTableName()
        }

    }
    function tableEnameChange(value, option) {
        setTableEname(value)
        getColumnName('', '', '', value)
        if (value) {
            form.setFieldsValue({
                tableCname: option.val,
                columnCname: undefined,
                columnEname: undefined,
            });
            setDisable(false)
        } else {
            form.setFieldsValue({
                tableCname: undefined,
                columnCname: undefined,
                columnEname: undefined,
            })
            setDisable(true)
            getTableName()
        }
    }
    function colchange(value, option, ins) {
        if (ins == 1) {
            if (value) {
                form.setFieldsValue({
                    columnEname: option.val
                });
            } else {
                form.setFieldsValue({
                    columnEname: undefined
                })
                getColumnName('', '', '', '')
            }
        } else {
            if (value) {
                form.setFieldsValue({
                    columnCname: option.val
                });
            } else {
                form.setFieldsValue({
                    columnCname: undefined
                })
                getColumnName('', '', '', '')
            }
        }
    }
    //返回
    function goBack() {
        setAddVisible(false);
        setFiledDetail(null)
    }
    function userChange() {
        setVisible(false)
        setFiledDetail(null)
        getColumnVerifyPage();
        setSelectedRowKeys([])
    }
    const onFinish = (value) => {
        params.current = 1
        const param = {
            ...params,
            ...value,
        }
        setCurrent(1)
        setParams(param)
        getColumnVerifyPage(param);
        setSelectedRowKeys([])
    };
    const onReset = () => {
        setCurrent(1)
        setSize(15)
        setParams(data)
        form.resetFields();
        getRegular()
        getTableName()
        getColumnName('', '', '', '')
        getColumnVerifyPage(data);
        setSelectedRowKeys([])
        setDisable(true)
    };
    const columns = [
        { title: '序号', dataIndex: 'index', render: (text, record, index) => (current - 1) * params.size + index + 1, width: 60 },
        { title: '表名称（中文）', dataIndex: 'tableCname', key: 'tableCname', width: 130, },
        { title: '表名称（英文）', dataIndex: 'tableEname', key: 'tableEname', width: 130, },
        { title: '字段名称（中文）', dataIndex: 'columnCname', key: 'columnCname', width: 145, },
        { title: '字段名称（英文）', dataIndex: 'columnEname', key: 'columnEname', width: 145, },
        {
            title: '是否必填', dataIndex: 'isRequired', key: 'isRequired', render: (text, record) => {
                return record.isRequired == 1 ? "是" : record.isRequired == 0 ? "否" : '';
            }
        },
        {
            title: '标准值维护', dataIndex: 'standardvalue', key: 'standardvalue', width: 110, render: (text, record) => {
                return record.standardvalue ? record.standardvalue.length > 10 ? <span title={record.standardvalue}>{record.standardvalue.substring(0, 10) + '...'}</span> : record.standardvalue : '-';
            }
        },
        {
            title: '正则式名称', dataIndex: 'regular', key: 'regular', width: 110, render: (text, record) => {
                return record.regular || '-';
            }
        },
        {
            title: '说明', dataIndex: 'description', key: 'description', render: (text, record) => {
                return record.description ? 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.columnId)}>修改</a>
                </Space>
            )
        }
    ];
    const rowSelection = {
        selectedRowKeys,
        onChange: onSelectChange,
    };
    if (addVisible && filedDetail) {
        return (
            <FiledContext.Provider value={{ type, detail: filedDetail }}>
                <AddRules userChange={userChange} back={goBack} className="aa" />
            </FiledContext.Provider>
        )
    }
    return (
        <div className="wrapper">
            <div className="filter-box">
                <Form
                    form={form}
                    name="normal_login"
                    onFinish={onFinish}
                    initialValues={{ lossType: '', lossWay: '', isRequired: '' }}
                >
                    <Row gutter={24}>
                        <Space size="middle">
                            <Form.Item label="表名称（中文）" name="tableCname">
                                <Select showSearch allowClear onChange={(value, option) => tableCnameChange(value, option)} onSearch={cnameSearch} style={{ width: '159px' }} placeholder="请选择">
                                    {tableList.map((item) => {
                                        return (
                                            <Option value={item.tableCname} val={item.tableEname} key={item.tableCname}>{item.tableCname}</Option>
                                        )
                                    })}
                                </Select>
                            </Form.Item>

                            <Form.Item label="表名称（英文）" name="tableEname">
                                <Select showSearch allowClear onChange={(value, option) => tableEnameChange(value, option)} onSearch={enameSearch} style={{ width: '159px' }} placeholder="请选择">
                                    {tableList.map((item) => {
                                        return (
                                            <Option value={item.tableEname} val={item.tableCname} key={item.tableEname}>{item.tableEname}</Option>
                                        )
                                    })}
                                </Select>
                            </Form.Item>
                            <Form.Item label="字段名称（中文）" name="columnCname">
                                <Select showSearch allowClear onChange={(value, option) => colchange(value, option, 1)} onSearch={colmeSearch} style={{ width: '159px' }} placeholder="请选择" disabled={disable}>
                                    {colList.map((item, i) => {
                                        return (
                                            <Option value={item.columnCname} val={item.columnEname} key={item.columnCname}>{item.columnCname}</Option>
                                        )
                                    })}
                                </Select>
                            </Form.Item>
                            <Form.Item label="字段名称（英文）" name="columnEname">
                                <Select showSearch allowClear onChange={(value, option) => colchange(value, option, 2)} onSearch={coleneSearch} placeholder="请选择" style={{ width: '159px' }} disabled={disable}>
                                    {colList.map((item, i) => {
                                        return (
                                            <Option value={item.columnEname} val={item.columnCname} key={item.columnEname}>{item.columnEname}</Option>
                                        )
                                    })}
                                </Select>
                            </Form.Item>
                        </Space>
                        <Col span={5} key={4}>
                            <Form.Item label="是否必填" name="isRequired">
                                <Select
                                    placeholder="请选择"
                                    allowClear
                                >
                                    <Option value="" key={2}>全部</Option>
                                    <Option value="1" key={1}>是</Option>
                                    <Option value="0" key={0}>否</Option>
                                </Select>
                            </Form.Item>
                        </Col>
                        <Col span={5} key={5}>
                            <Form.Item label="标准值" name="standardValue" getValueFromEvent={getValueFromEvent}>
                                <Input placeholder="请输入" autoComplete='off' allowClear maxLength='30' />
                            </Form.Item>
                        </Col>
                        <Form.Item label="正则名称" name="regularName">
                            <Select showSearch allowClear onSearch={onSearch} placeholder="请选择" style={{ width: '159px' }}>
                                {regularList.map((item) => {
                                    return (
                                        <Option value={item.name} key={item.id}>{item.name}</Option>
                                    )
                                })}
                            </Select>
                        </Form.Item>
                        <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={logList}
                    rowKey={record => record.columnId}
                    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>
            <Modal
                title="删除字段校验规则"
                okText='确定'
                cancelText='关闭'
                width={400}
                visible={visible}
                onOk={delColumnVerify}
                /*confirmLoading={confirmLoading}*/
                onCancel={() => showDelModal(false)}
                maskClosable={false}
            >
                <p>字段校验规则删除后将无法恢复，确认删除这{selectedRowKeys.length}条数据？</p>
            </Modal>
        </div >
    )
}
export default FieldRules;