import { useEffect, useState, useContext } from 'react';
import { Form, Input, Radio, Button, Select, message, Breadcrumb, Modal } from 'antd';
import './index.less';
import apiObj from '@api/index';
import backIcon from "@images/back.png";
import FiledContext from './filed-context';
import add from '@images/add-icon.png';
import del from '@images/del-icon.png';
import { getValueFromEvent } from '@utils/index'
const { post, api, xPost } = apiObj;
const { Option } = Select;
const { TextArea } = Input;
function AddRules(props) {
    const [form] = Form.useForm();
    const { back, userChange } = props;
    const [visible, setVisible] = useState(false);
    const { type } = useContext(FiledContext);
    function handleOk() {
        back()
    }
    function handleCancel() {
        setVisible(false)
    }
    const goback = () => {
        if (form.isFieldsTouched()) {
            setVisible(true)
        } else {
            back()
        }
    };
    return (
        <>
            <Breadcrumb separator="">
                <Breadcrumb.Item><img className='back-icon' src={backIcon} onClick={goback} alt="返回上一页" /></Breadcrumb.Item>
                <Breadcrumb.Item>字段校验规则维护</Breadcrumb.Item>
                <Breadcrumb.Separator />
                <Breadcrumb.Item>{type == 1 ? "新增字段校验" : "修改字段校验"}</Breadcrumb.Item>
            </Breadcrumb>
            <div className="add-rules">
                <ContentForm back={goback} form={form} cancel={userChange}></ContentForm>
            </div>
            <Modal
                title="提示"
                okText='确定'
                cancelText='取消'
                width={400}
                visible={visible}
                onOk={handleOk}
                onCancel={handleCancel}
                maskClosable={false}
            >
                <p>您还有内容未保存，确定要退出？</p>
            </Modal>
        </>
    )
}
function ContentForm(props) {
    const [columnList, setColumnList] = useState([]);
    const [standardValueList, setStandardValueList] = useState([]);
    const [regularList, setRegularList] = useState([]);//正则式数据
    const [tableList, setTableList] = useState([]);//表名称
    const [colList, setColList] = useState([[]]);//字段名称
    const [list, setList] = useState([]);
    const [tableCname, setTableCname] = useState();
    const [tableEname, setTableEname] = useState();
    const [columnCname, setcolumnCname] = useState();
    const [columnEname, setcolumnEname] = useState();
    const [disable, seDisable] = useState([true]);
    const { type, detail } = useContext(FiledContext);
    const { back, form, cancel } = props;
    const initialValues = detail
    console.log(type);
    const vilidateRules = {
        required: '${label}不能为空!',
    };
    //获取正则式名称
    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 getAddUpColumnName() {
        post(api.getAddUpColumnName, {
            tableCname: tableCname,
            tableEname: tableEname,
            columnId: type == 2 ? detail.columnId : null,
            columnCname: columnCname,
            columnEname: columnEname,
        }).then((res) => {
            if (res.data.code === 200) {
                const data = res.data.data;
                let columnList = []
                data.forEach((item, i) => {
                    item.getTableNameDTO.index = i
                    columnList.push(item.getTableNameDTO)
                });
                setTableList(columnList);
                setList(data)
                if (type == 2) {
                    data.forEach((item, i) => {
                        detail.columnList.forEach(it => {
                            if (item.getTableNameDTO.tableCname == it.tableCname) {
                                let colList = [[]]
                                colList[0] = data[i].getColumnNameDTOList
                                setColList([...colList])
                            }
                        });

                    });
                }
            }
        })
    }
    //表选择
    function tablechange(i, value, options, ins) {
        const formData = form.getFieldsValue();
        if (value) {
            colList[i] = list[options.key].getColumnNameDTOList
            disable[i] = false
            seDisable([...disable])
            setColList([...colList])
        } else {
            colList[i] = []
            disable[i] = true
            seDisable([...disable])
            setColList([...colList])
            getAddUpColumnName()
        }
        let columnList = formData.columnList;
        if (ins == 1) {
            if (value) {
                columnList[i].tableEname = options.val
            } else {
                columnList[i].tableEname = undefined
            }
        } else {
            if (value) {
                columnList[i].tableCname = options.val
            } else {
                columnList[i].tableCname = undefined
            }
        }
        columnList[i].columnCname = undefined
        columnList[i].columnEname = undefined
        form.setFieldsValue({
            columnList: columnList
        });
    }
    function colchange(i, value, options, ins) {
        const formData = form.getFieldsValue();
        let columnList = formData.columnList;
        if (value) {
            columnList[i].id = options.key
        } else {
            columnList[i].id = undefined
        }

        if (ins == 1) {
            if (value) {
                columnList[i].columnEname = options.val
            } else {
                columnList[i].columnEname = undefined
            }
        } else {
            if (value) {
                columnList[i].columnCname = options.val
            } else {
                columnList[i].columnCname = undefined
            }
        }
        form.setFieldsValue({
            columnList: columnList
        });
    }
    //表名称搜索(中文)
    function cnameSearch(val) {
        setTableCname(val)
        getAddUpColumnName()
    }
    //表名称搜索(英文)
    function enameSearch(val) {
        setTableEname(val)
        getAddUpColumnName()
    }
    //字段名称搜索(中文)
    function colmeSearch(val) {
        setcolumnCname(val)
        getAddUpColumnName()
    }
    //字段名称搜索(英文)
    function coleneSearch(val) {
        setcolumnEname(val)
        getAddUpColumnName()
    }
    //表字段添加
    function modifyData(i) {
        const formData = form.getFieldsValue();
        let columnList = formData.columnList;
        if (i == 0) {
            columnList.push({
                columnCname: undefined,
                columnEname: undefined,
                ableCname: undefined,
                tableEname: undefined
            })
        } else {
            columnList.splice(i, 1)
        }
        setColumnList([...columnList])
        form.setFieldsValue({
            columnList: columnList
        });
        const index = columnList.length - 1
        colList.push(...[[]])
        setColList([...colList])
        disable[index] = true
        seDisable([...disable])

    }
    //标准值维护
    function modifyStand(i) {
        const formData = form.getFieldsValue();
        let standardValueList = formData.standardValueList;
        if (i == 0) {
            standardValueList.push({
                tit: null
            })
        } else {
            standardValueList.splice(i, 1)
        }
        setStandardValueList([...standardValueList])
        form.setFieldsValue({
            standardValueList: standardValueList
        });
    }
    //正则式名称搜索
    function onSearch(val) {
        getRegular(val)
    }
    //正则式选择获取id
    function onChange(value, options) {
        form.setFieldsValue({
            regularId: options ? options.key : ''
        });
    }
    function handleSave() {
        form.validateFields().then((values) => {
            addColumnVerify()
        }).catch((error) => {
            console.log('验证失败', error)
        })
    }
    function addColumnVerify() {
        const formData = form.getFieldsValue();
        let arr = []
        let url
        formData.standardValueList.forEach(it => {
            if (it.tit) {
                arr.push(it.tit)
            }
        });
        formData.standardValueList = arr
        if (type == 1) {
            url = api.addColumnVerify
        } else {
            url = api.updateColumnVerify
            // formData.id = detail.columnId
        }
        post(url, formData).then((res) => {
            if (res.data.code === 200) {
                message.success(res.data.message);
                cancel()
            } else {
                message.error(res.data.message);
            }
        })
    }
    useEffect(() => {
        getRegular()
        getAddUpColumnName()
        if (detail) {
            const columnList = detail.columnList
            const standardValueList = detail.standardValueList
            setColumnList(columnList)
            setStandardValueList(standardValueList)
            list.forEach((item, i) => {
                detail.columnList.forEach(it => {
                    if (item.getTableNameDTO.tableCname == it.tableCname) {
                        let colList = [[]]
                        colList[0] = list[i].getColumnNameDTOList
                        setColList([...colList])
                    }
                });

            });
        }
        if (type == 2) {
            seDisable([false])
        }
    }, []);

    return (
        <>
            <Form
                labelCol={{ span: 4 }}
                wrapperCol={{ span: 16 }}
                layout="horizontal"
                validateMessages={vilidateRules}
                initialValues={initialValues}
                form={form}
            >
                <Form.Item>
                    {
                        columnList.map((it, i) => {
                            return (
                                <div className='box' key={i}>
                                    <div className='item'>
                                        <div className='item-box'>
                                            <Form.Item label="表名称（中文）" rules={[{ required: true }]} style={{ width: '50%' }} name={['columnList', i, 'tableCname']} labelAlign="right" >
                                                <Select allowClear showSearch onChange={(value, option) => tablechange(i, value, option, 1)} onSearch={cnameSearch} style={{ width: 160 }} placeholder="请选择" disabled={type ==2}>
                                                    {tableList.map((item) => {
                                                        return (
                                                            <Option value={item.tableCname} val={item.tableEname} key={item.index}>{item.tableCname}</Option>
                                                        )
                                                    })}
                                                </Select>
                                            </Form.Item>
                                            <Form.Item label="表名称（英文）" rules={[{ required: true }]} name={['columnList', i, 'tableEname']} labelAlign="right">
                                                <Select allowClear showSearch onChange={(value, option) => tablechange(i, value, option, 2)} onSearch={enameSearch} style={{ width: 160 }} placeholder="请选择" disabled={type ==2}>
                                                    {tableList.map((item) => {
                                                        return (
                                                            <Option value={item.tableEname} val={item.tableCname} key={item.index}>{item.tableEname}</Option>
                                                        )
                                                    })}
                                                </Select>
                                            </Form.Item>
                                        </div>
                                        <div className='item-box'>
                                            <Form.Item label="字段名称（中文）" rules={[{ required: true }]} style={{ width: '50%' }} name={['columnList', i, 'columnCname']} labelAlign="right">
                                                <Select allowClear showSearch onChange={(value, option) => colchange(i, value, option, 1)} onSearch={colmeSearch} style={{ width: 160 }} placeholder="请选择" disabled={disable[i] || type == 2}>
                                                    {colList[i].map((item) => {
                                                        return (
                                                            <Option value={item.columnCname} val={item.columnEname} key={item.id} index={i}>{item.columnCname}</Option>
                                                        )
                                                    })}
                                                </Select>
                                            </Form.Item>
                                            <Form.Item label="字段名称（英文）" rules={[{ required: true }]} name={['columnList', i, 'columnEname']} labelAlign="right">
                                                <Select allowClear showSearch onChange={(value, option) => colchange(i, value, option, 2)} onSearch={coleneSearch} style={{ width: 160 }} placeholder="请选择" disabled={disable[i] || type == 2}>
                                                    {colList[i].map((item) => {
                                                        return (
                                                            <Option value={item.columnEname} val={item.columnCname} key={item.id} index={i}>{item.columnEname}</Option>
                                                        )
                                                    })}
                                                </Select>
                                            </Form.Item>
                                            <Form.Item hidden={true} name={['columnList', i, 'id']} noStyle>
                                                <Input />
                                            </Form.Item>
                                        </div>
                                    </div>
                                    <img onClick={() => modifyData(i)} src={i == 0 ? add : del} hidden={type == 2} />
                                </div>

                            )
                        })
                    }

                </Form.Item>
                <Form.Item label="是否必填数据" name="isRequired" rules={[{ required: true, message: '请选择是否必填' }]}>
                    <Radio.Group>
                        <Radio value={'1'}>是</Radio>
                        <Radio value={'0'}>否</Radio>
                    </Radio.Group>
                </Form.Item>
                <Form.Item label="标准值维护"  >
                    {
                        standardValueList.map((it, i) => {
                            return (
                                <div className='box-2' key={i} >
                                    <Form.Item name={['standardValueList', i, 'tit']} style={{ width: 159 }} getValueFromEvent={getValueFromEvent} rules={[{ max: 30, message: '标准值不能超过30个字符' }]}>
                                        <Input autoComplete='off' placeholder="请输入" />
                                    </Form.Item>
                                    <img onClick={() => modifyStand(i)} src={i == 0 ? add : del} />
                                </div>

                            )
                        })
                    }

                </Form.Item>
                <Form.Item label="正则式名称" name="regularName">
                    <Select showSearch allowClear onSearch={onSearch} onChange={onChange} style={{ width: 160 }} placeholder="请选择">
                        {regularList.map((item) => {
                            return (
                                <Option value={item.name} key={item.id}>{item.name}</Option>
                            )
                        })}
                    </Select>
                </Form.Item>
                <Form.Item hidden={true} name="regularId" noStyle>
                    <Input />
                </Form.Item>
                <Form.Item label="说明" name="description" rules={[{ max: 200, message: '说明不能超过200个字符' }]} getValueFromEvent={getValueFromEvent}>
                    <TextArea
                        autoSize={{ minRows: 3, maxRows: 5 }}
                        placeholder="请输入"

                    />
                </Form.Item>
            </Form>
            <div className="button-box">
                <Button onClick={back}>关闭</Button>
                <Button onClick={handleSave} type='primary'>保存</Button>
            </div>
        </>
    )
}


export default AddRules;