import React, { useEffect, useState } from 'react';
import { Card, Form, Input, Button, Switch, message, Divider, Row, Col, Spin } from 'antd';
import styles from './ProxyConfig.less';
import {
  GetNginxConfigInfo,
  InsertNginxConfig,
  StartNginx,
  StopNginx,
  ReloadNginx,
  NginxCache,
  NginxLog,
} from '@/services/hostmanager/hostmanager';
import { ReloadOutlined } from '@ant-design/icons';
import configuration from '../../../../assets/images/icons/消息.svg';

const layout = {
  labelCol: { span: 2 },
  wrapperCol: { span: 22 },
};
const tailLayout = {
  wrapperCol: { offset: 11, span: 13 },
};

const ProxyConfig = () => {
  const [loading, setLoading] = useState(false); // 加载
  const [form] = Form.useForm();

  const [flag, setFlag] = useState(1);
  const [currentConfig, setCurrentConfig] = useState({
    NginxPort: '',
    IISIPProt: '',
    EMQIPPort: '',
    IsStartNginx: false,
    IsStartNginxCache: false,
    IsStartNginxLog: false,
  });
  const onFinish = values => {
    setLoading(true);
    InsertNginxConfig({
      port: values.NginxPort,
      iisLocation: values.IISIPProt,
      emqLocation: values.EMQIPPort,
    }).then(res => {
      setLoading(false);
      if (res.code === 0) {
        message.success('保存成功');
      } else {
        message.error('保存失败');
      }
    });
  };

  const onFinishFailed = errorInfo => {};

  const OperateNginx = checked => {
    if (checked) {
      OperateStartNginx();
    } else {
      OperateStopNginx();
    }
  };
  // 开启Nginx
  const OperateStartNginx = () => {
    StartNginx().then(res => {
      if (res.code === 0) {
        message.success('开启成功');
        setFlag(flag + 1);
      } else {
        message.error('开启失败');
      }
    });
  };
  // 停止Nginx
  const OperateStopNginx = () => {
    StopNginx().then(res => {
      if (res.code === 0) {
        message.success('关闭成功');
        setFlag(flag + 1);
      } else {
        message.error('关闭失败');
      }
    });
  };
  // 开启/关闭缓存
  const OperateNginxCache = isOpen => {
    NginxCache({
      isOpen: isOpen ? 1 : 0,
    }).then(res => {
      if (res.code === 0) {
        setFlag(flag + 1);
        message.success(isOpen ? '开启成功' : '关闭成功');
      } else {
        message.error(res.msg);
      }
    });
  };
  // 开启/关闭日志
  const OperateNginxLog = isOpen => {
    NginxLog({
      isOpen: isOpen ? 1 : 0,
    }).then(res => {
      if (res.code === 0) {
        setFlag(flag + 1);
        message.success(isOpen ? '开启成功' : '关闭成功');
      } else {
        message.error(res.msg);
      }
    });
  };

  const OperateReloadNginx = () => {
    ReloadNginx().then(res => {
      if (res.code === 0) {
        message.success('重载成功');
      } else {
        message.error('重载失败');
      }
    });
  };

  useEffect(() => {
    GetNginxConfigInfo().then(res => {
      if (res.code === 0) {
        setCurrentConfig({
          NginxPort: res.data.NginxPort,
          IISIPPort: res.data.IISIPPort,
          EMQIPPort: res.data.EMQIPPort,
          IsStartNginx: res.data.IsStartNginx,
          IsStartNginxCache: res.data.IsStartNginxCache,
          IsStartNginxLog: res.data.IsStartNginxLog,
        });
        let obj = {};
        Object.keys(currentConfig).forEach(k => {
          obj[k] = res.data[k];
        });
        form.setFieldsValue(obj);
      } else {
        message.errorInfo(res.msg);
      }
    });
  }, [flag]);
  //     GetNginxConfigInfoOLD().then(
  //         res => {
  //             if (res.say.statusCode === "0000") {
  //                 setCurrentConfig({
  //                     NginxPort: res.getMe[0].NginxPort,
  //                     IISIPProt: res.getMe[0].IISIPProt,
  //                     EMQIPPort: res.getMe[0].EMQIPPort,
  //                     IsStartNginx: res.getMe[0].IsStartNginx,
  //                     IsStartNginxCache: res.getMe[0].IsStartNginxCache,
  //                     IsStartNginxLog: res.getMe[0].IsStartNginxLog,
  //                 })
  //                 let obj = {};
  //                 Object.keys(currentConfig).forEach(k => {
  //                     obj[k] = res.getMe[0][k];
  //                 });
  //                 console.log(obj)
  //                 form.setFieldsValue(obj);
  //             } else {
  //                 message.errorInfo(res.msg)
  //             }
  //         }
  //     )
  // }, [])

  return (
    <div className={styles.proxy_container}>
      <Card style={{ width: '100%', height: 'calc(100vh - 130px)' }}>
        <Spin spinning={loading} tip="loading">
          <Form
            form={form}
            name="basic"
            initialValues={{ remember: true }}
            onFinish={onFinish}
            onFinishFailed={onFinishFailed}
          >
            <div style={{ display: 'flex', alignItems: 'center', marginTop: '10px' }}>
              <img src={configuration} style={{ height: '16px' }} />
              <span style={{ marginLeft: '10px', fontWeight: 'bold' }}>配置文件管理</span>
            </div>
            <Divider />
            <Form.Item
              style={{ marginLeft: '12px' }}
              label="Nginx端口"
              labelAlign="right"
              name="NginxPort"
              rules={[
                {
                  required: true,
                  pattern: new RegExp(/^[1-9]\d*$/, 'g'),
                  message: '请输入Nginx端口,例如:8091',
                },
              ]}
            >
              <Input style={{ width: '300px' }} placeholder="请输入Nginx端口" />
            </Form.Item>
            <Form.Item
              style={{ marginLeft: '34px' }}
              label="IIS地址"
              labelAlign="right"
              name="IISIPProt"
              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])(:\d*)$/,
                    'g',
                  ),
                  message: '请输入正确的IP例如:192.168.12.231:8231',
                },
              ]}
            >
              <Input style={{ width: '300px' }} placeholder="请输入IIS地址" />
            </Form.Item>
            <Form.Item
              style={{ marginLeft: '20px' }}
              label="EMQ地址"
              labelAlign="right"
              name="EMQIPPort"
              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])(:\d*)$/,
                    'g',
                  ),
                  message: '请输入正确的IP例如:192.168.12.231:8231',
                },
              ]}
            >
              <Input style={{ width: '300px' }} placeholder="请输入EMQ地址" />
            </Form.Item>
            <Form.Item>
              <Button type="primary" htmlType="submit" style={{ marginLeft: '103px' }}>
                保存
              </Button>
            </Form.Item>
          </Form>

          <div style={{ display: 'flex', alignItems: 'center', marginTop: '40px' }}>
            <img src={configuration} style={{ height: '16px' }} />
            <span style={{ marginLeft: '10px', fontWeight: 'bold' }}>服务管理</span>
          </div>
          <Divider />
          <div className={styles.operate_container}>
            <div style={{ marginLeft: '35px' }}>
              服务运行
              <Switch
                checkedChildren="开启"
                unCheckedChildren="关闭"
                checked={currentConfig.IsStartNginx}
                onChange={OperateNginx}
                style={{ marginLeft: '35px' }}
              />
            </div>
            <div style={{ marginLeft: '35px', marginTop: '20px' }}>
              服务日志
              <Switch
                checkedChildren="开启"
                unCheckedChildren="关闭"
                checked={currentConfig.IsStartNginxLog}
                onChange={OperateNginxLog}
                disabled={currentConfig.IsStartNginx > 0 ? 0 : 1}
                style={{ marginLeft: '35px' }}
              />
            </div>
            <div style={{ marginLeft: '35px', marginTop: '20px' }}>
              服务缓存
              <Switch
                checkedChildren="开启"
                unCheckedChildren="关闭"
                checked={currentConfig.IsStartNginxCache}
                onChange={OperateNginxCache}
                disabled={currentConfig.IsStartNginx > 0 ? 0 : 1}
                style={{ marginLeft: '35px' }}
              />
            </div>
            <div style={{ marginLeft: '35px', marginTop: '20px' }}>
              服务重载
              <Button
                type="primary"
                onClick={OperateReloadNginx}
                disabled={currentConfig.IsStartNginx > 0 ? 0 : 1}
                style={{ marginLeft: '35px' }}
              >
                重载
              </Button>
            </div>
          </div>
        </Spin>
      </Card>
    </div>
  );
};
export default ProxyConfig;
