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';
const { post, api, xPost } = apiObj;
const { Option } = Select;
const { TextArea } = Input;
function AddRules(props) {
    const [form] = Form.useForm();
    const { back } = 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-container">
                <ContentForm back={goback} form={form} cancel={back}></ContentForm>
            </div>
            <Modal
                title="提示"
                okText='确定'
                cancelText='取消'
                width={400}
                visible={visible}
                onOk={handleOk}
                onCancel={handleCancel}
            >
                <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 [isChange, seIsChange] = useState(true);
    const { type, detail } = useContext(FiledContext);
    const { back, form, cancel } = props;
    const initialValues = detail
    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).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 = data[i].getColumnNameDTOList
                                setColList([...colList])
                            }
                        });

                    });
                }
            }
        })
    }
    //表选择
    function tablechange(value, options) {
        let colList = list[options.key].getColumnNameDTOList
        seIsChange(false)
        setColList([...colList])
    }
    function colchange(value, options) {
        const formData = form.getFieldsValue();
        let columnList = formData.columnList;
        columnList[options.index].id = options.key
        form.setFieldsValue({
            columnList: columnList
        });
    }
    //表字段添加
    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
        });
    }
    //标准值维护
    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)
            }
        });
        console.log(arr);
        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)
            seIsChange(false)
            list.forEach((item, i) => {
                detail.columnList.forEach(it => {
                    if (item.getTableNameDTO.tableCname == it.tableCname) {
                        let colList = list[i].getColumnNameDTOList
                        console.log(colList);
                        setColList([...colList])
                    }
                });

            });
        }
    }, []);

    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 onChange={tablechange} style={{ width: 160 }} placeholder="请选择">
                                                    {tableList.map((item) => {
                                                        return (
                                                            <Option value={item.tableCname} key={item.index}>{item.tableCname}</Option>
                                                        )
                                                    })}
                                                </Select>
                                            </Form.Item>
                                            <Form.Item label="表名称（英文）" rules={[{ required: true }]} name={['columnList', i, 'tableEname']} labelAlign="right">
                                                <Select allowClear onChange={tablechange} style={{ width: 160 }} placeholder="请选择" >
                                                    {tableList.map((item) => {
                                                        return (
                                                            <Option value={item.tableEname} 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 onChange={colchange} style={{ width: 160 }} placeholder="请选择" disabled={isChange}>
                                                    {colList.map((item) => {
                                                        return (
                                                            <Option value={item.columnCname} 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 onChange={colchange} style={{ width: 160 }} placeholder="请选择" disabled={isChange}>
                                                    {colList.map((item) => {
                                                        return (
                                                            <Option value={item.columnEname} 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} />
                                </div>

                            )
                        })
                    }

                </Form.Item>
                <Form.Item label="是否必填数据" name="isRequired">
                    <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 }}>
                                        <Input autoComplete='off' />
                                    </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">
                    <TextArea
                        autoSize={{ minRows: 3, maxRows: 5 }}
                    />
                </Form.Item>
            </Form>
            <div className="button-box">
                <Button onClick={back}>取消</Button>
                <Button onClick={handleSave} type='primary'>保存</Button>
            </div>
        </>
    )
}


export default AddRules;