import React, { useEffect, useState } from 'react'
import { Card, Form, Input, Button, Select, message, Divider, Row, Col, Spin } from 'antd'
import styles from './IotConfig.less'
import Internet from '../../../../assets/images/icons/物联.svg';
import EMQ from '../../../../assets/images/icons/EMQ.svg';
import Yes from '../../../../assets/images/icons/正确.svg';
import { GetIOTPlatformVersion, GetTCPConfigInfo, PingIOTPlatform, SaveTcpAddress } from '@/services/platform/hostmanager'
import { CloseCircleFilled } from '@ant-design/icons';
const layout = {
    labelCol: { span: 4 },
    wrapperCol: { span: 20 },

};
const tailLayout = {
    wrapperCol: { offset: 9, span: 15 },

};

const IotConfig = () => {
    const [loading, setLoading] = useState(false); // 加载
    const [show1, setShow1] = useState('none')
    const [show2, setShow2] = useState('none')
    const [currentIotVersion, setCurrentIotVersion] = useState({ data: "" });
    const [currentIotConfig, setCurrentIotConfig] = useState({
        TcpAddress: "",
        SSLSafe: "",
        IotAddress: ""
    });

    const [form] = Form.useForm();
    const onFinish = (values) => {
        if (values.IotAddress != null && values.IotAddress.length > 0) {
            if(values.SSLSafe=='是'){
                values.SSLSafe=1
            }
            if(values.SSLSafe=='否'){
                values.SSLSafe=0
            }
            PingIot({ ip: values.IotAddress, values: values })
        } else {
            if(values.SSLSafe=='是'){
                values.SSLSafe=1
            }
            if(values.SSLSafe=='否'){
                values.SSLSafe=0
            }
            SaveIotConfig({
                tcpAddress: values.TcpAddress,
                iotAddress: values.IotAddress,
                sslSafe: values.SSLSafe
            })
        }
    };

    const onFinishFailed = (errorInfo) => {
        console.log('Failed:', errorInfo);
    };

    useEffect(() => {
        GetCurentIotVerison()
        GetIotConfig()

    }, [])

    const GetCurentIotVerison = () => {
        GetIOTPlatformVersion().then(
            res => {
                if (res.data) {
                    setCurrentIotVersion(res)
                }
            }
        )
    }
    const GetIotConfig = () => {
        GetTCPConfigInfo().then(
            res => {
                if (res.data) {
                    let obj = {};
                    Object.keys(currentIotConfig).forEach(k => {
                        obj[k] = res.data[k];
                    });
                    console.log(obj)
                    form.setFieldsValue(obj);
                    setCurrentIotConfig(val => ({ ...val, ...obj }));
                    setLoading(true)
                    PingIOTPlatform({
                        ip: obj.IotAddress
                    }).then(res => {
                        setLoading(false)
                        if (res.code === 0) {
                            setShow1('block')
                            setShow2('none')
                        } else {
                            setShow1('none')
                            setShow2('block')
                        }
                    }
                    )
                }
            }
        )
    }
    const PingIot = ({ ip, values }) => {
        SaveIotConfig({
            tcpAddress: values.TcpAddress,
            iotAddress: values.IotAddress,
            sslSafe: values.SSLSafe
        })
    }
    const PingIot1 = () => {
        setLoading(true)
        let aa = form.getFieldsValue().IotAddress
        PingIOTPlatform({
            ip: aa
        }).then(res => {
            setLoading(false)
            if (res.code === 0) {
                setShow1('block')
                setShow2('none')
                message.success("连接成功!");
            } else {
                setShow1('none')
                setShow2('block')
                message.error(res.msg);
            }
        }
        )
    }
    const SaveIotConfig = (config) => {
        setLoading(true)
        SaveTcpAddress(config).then(res => {
            setLoading(false)
            if (res.code === 0) {
                message.info('配置保存成功');
            } else {
                message.error(res.msg);
            }
        }
        )
    }


    return (
        <div className={styles.iot_container}>
            <Card title={`物联平台${currentIotVersion.data ? `[${currentIotVersion.data}]` : ""}`} style={{ width: "100%", height: 'calc(100vh - 130px)' }}>
                <Spin spinning={loading} tip="loading">
                    <Form
                        {...layout}
                        form={form}
                        name="basic"
                        initialValues={{ remember: true }}
                        onFinish={onFinish}
                        onFinishFailed={onFinishFailed}
                    >
                        <div style={{ marginTop: '10px', display: 'flex', alignItems: 'center', marginLeft: '15px' }}>
                            <img src={Internet} style={{ height: '16px' }} alt="" /><span style={{ marginLeft: '10px', fontWeight: 'bold' }}>物联平台</span>
                        </div>
                        <Divider />
                        <Row>
                            <Col span={18}>
                                <Form.Item
                                    label="服务地址(平台)"
                                    name="IotAddress"
                                    rules={[{ required: true, pattern: new RegExp(/^(([1-9]?\d|1\d{2}|2[0-4]\d|25[0-5])\.){3}([1-9]?\d|1\d{2}|2[0-4]\d|25[0-5])$/, "g"), message: '请输入正确的IP例如:192.168.12.231' }]}
                                >
                                    <Input style={{ width: '95%' }} />
                                </Form.Item>
                            </Col>
                            <Col span={3}>
                                <Button type="primary" onClick={() => PingIot1()}>连接</Button>
                            </Col>
                            <Col span={3}>
                                <span style={{ display: show1 }}><img src={Yes} style={{ height: '32px', marginRight: '20px', marginTop:'5px' }} alt="" /><span style={{verticalAlign: 'text-bottom'}}>已连接</span></span>
                                <span style={{ display: show2 }}><CloseCircleFilled style={{ fontSize: '32px', marginRight: '20px', marginTop:'5px' }} /><span style={{verticalAlign: 'text-bottom'}}>未连接</span></span>
                            </Col>

                            <div style={{ marginTop: '40px', display: 'flex', alignItems: 'center', marginLeft: '15px' }}>
                                <img src={EMQ} style={{ height: '16px' }} alt="" /><span style={{ marginLeft: '10px', fontWeight: 'bold' }}>EMQ</span>
                            </div>
                            <Divider />
                            <Col span={18}>
                                <Form.Item
                                    label="服务地址(EMQ)"
                                    name="TcpAddress"
                                    rules={[{ required: true, pattern: new RegExp(/^.*:.*$/), message: '请输入正确的IP:端口' }]}
                                >
                                    <Input style={{ width: '95%' }} />
                                </Form.Item>
                            </Col>
                            <Col span={6}>
                            </Col>
                            <Col span={18}>
                                <Form.Item
                                    name="SSLSafe"
                                    label="SSL(EMQ)"
                                    rules={[{ required: true, message: '请选择是否!' }]}

                                >
                                    <Select placeholder="请选择是否!" style={{ width: '95%' }}>
                                        <Option value="0">是</Option>
                                        <Option value="1">否</Option>
                                    </Select>
                                </Form.Item>
                            </Col>
                            <Col span={6}>
                            </Col>
                            <Col span={24}>
                                <Form.Item {...tailLayout}>
                                    <Button type="primary" htmlType="submit" disabled={currentIotConfig.TcpAddress.length > 0 ? 0 : 1}>
                                        保存
                                    </Button>
                                </Form.Item>
                            </Col>
                        </Row>
                    </Form>
                </Spin>
            </Card>
        </div>
    )
}
export default IotConfig