/* eslint-disable jsx-a11y/alt-text */
import React, { useEffect, useState } from 'react';
import {
  Card,
  Form,
  Input,
  Button,
  Switch,
  message,
  Divider,
  Row,
  Col,
  Spin,
  notification,
} 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(res.msg);
      }
    });
  };

  const onFinishFailed = errorInfo => {};

  const OperateNginx = checked => {
    if (checked) {
      OperateStartNginx();
    } else {
      OperateStopNginx();
    }
  };
  // 开启Nginx
  const OperateStartNginx = () => {
    setLoading(true);
    StartNginx().then(res => {
      setLoading(false);
      if (res.code === 0) {
        message.success('开启成功');
        setFlag(flag + 1);
      } else {
        message.error(res.msg);
      }
    });
  };
  // 停止Nginx
  const OperateStopNginx = () => {
    setLoading(true);
    StopNginx().then(res => {
      setLoading(false);
      if (res.code === 0) {
        message.success('关闭成功');
        setFlag(flag + 1);
      } else {
        message.error(res.msg);
      }
    });
  };
  // // 开启/关闭缓存
  // 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(() => {
    // let aa = window.location.origin;
    // let pepole = aa.split('//');
    // console.log(pepole[1]);
    // form.setFieldsValue({
    //   NginxPort: '8002',
    //   IISIPProt: pepole[1],
    //   EMQIPPort: '127.0.0.1:8083',
    // });
    GetNginxConfigInfo().then(res => {
      if (res.code === 0) {
        form.setFieldsValue({
          NginxPort: res.data.NginxPort,
          IISIPProt: res.data.IISIPProt,
          EMQIPPort: res.data.EMQIPPort,
        });
        setCurrentConfig({
          NginxPort: res.data.NginxPort,
          IISIPProt: res.data.IISIPProt,
          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];
        });
        console.log(obj);
        // if (obj.NginxPort) {
        //   form.setFieldsValue({ NginxPort: obj.NginxPort });
        // }
        // if (obj.IISIPProt) {
        //   form.setFieldsValue({ IISIPProt: obj.IISIPProt });
        // }
        // if (obj.EMQIPPort) {
        //   form.setFieldsValue({ EMQIPPort: obj.EMQIPPort });
        // }
        // form.setFieldsValue(obj);
      } else {
        notification.error({
          message: '提示',
          duration: 3,
          description: 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' }}>Nginx配置文件管理</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端口,例如:8002',
                },
              ]}
            >
              <Input style={{ width: '300px' }} placeholder="请输入Nginx端口，示例：8002" />
            </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地址，示例：192.168.12.231:8231"
              />
            </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例如:127.0.0.1：8083',
                },
              ]}
            >
              <Input
                style={{ width: '300px' }}
                placeholder="请输入EMQ地址，示例：127.0.0.1：8083"
              />
            </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' }}>Nginx服务管理</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;
