/* eslint-disable react/jsx-no-undef */
import React, { useEffect, useState } from 'react';
import {
  Card,
  Form,
  Input,
  Button,
  Select,
  message,
  Divider,
  Row,
  Col,
  Spin,
  Switch,
  Progress,
  Tooltip,
  Modal,
  Space,
} from 'antd';
import { CloseCircleFilled, InfoCircleFilled, QuestionCircleOutlined } from '@ant-design/icons';
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 Things from '../../../../assets/images/icons/物联网.svg';
import {
  GetIOTPlatformVersion,
  GetTCPConfigInfo,
  PingIOTPlatform,
  SaveTcpAddress,
  GetDataBaseConfig,
  GetBasicInfo,
  HealthCheck, // 健康检查接口
  CheckIsServiceAdd, // 判断数据库服务是否已添加
  GetServiceInfo, // 查询当前数据库服务状态信息
  AddDB, // 添加数据库
  DepositServiceDisable, // 停止数据库服务
  DepositServiceEnable, // 启动数据库服务
  GetGateWay,
  IsIotUpgrade, // 判断是否需要升级物联网统一接入平台
  IotUpgrade, // 升级物联网统一接入平台
  GetIotVersion, // 检查版本BS还是CS
} from '@/services/hostmanager/hostmanager';
import {
  GetDbProduct, // 获取产品方案配置
} from '@/services/database/api';
const layout = {
  labelCol: { span: 4 },
  wrapperCol: { span: 20 },
};
const tailLayout = {
  wrapperCol: { offset: 9, span: 15 },
};
let time = null;
const IotConfig = props => {
  const { setActiveKey } = props;
  const [loading, setLoading] = useState(false); // 加载
  const [show1, setShow1] = useState('none');
  const [show2, setShow2] = useState('none');
  const [show3, setShow3] = useState('none');
  const [show4, setShow4] = useState('none');
  const [currentIotVersion, setCurrentIotVersion] = useState({ data: '' });
  const [currentIotConfig, setCurrentIotConfig] = useState({
    TcpAddress: '',
    SSLSafe: '',
    IotAddress: '',
  });

  const [currentDataBase, setCurrentDataBase] = useState({
    userName: '',
    password: '',
    dbName: '',
    ip: '',
  });
  const [currentSiteInfo, setcurrentSiteInfo] = useState('');
  const [currentConfig, setCurrentConfig] = useState();

  const [form] = Form.useForm();
  const [flag, setFlag] = useState('');
  const [processLength, setProcessLength] = useState(0);
  const [switchStatus, setSwitchStatus] = useState(true);
  const [dbStatus, setDbStatus] = useState(''); // 数据库状态
  const [buStatus, setBuStatus] = useState(''); // 按钮状态
  const [keep, setKeep] = useState('');
  const [getWayVisible, setGetWayVisible] = useState(false);
  const [upgrade, setUpgrade] = useState(false);

  useEffect(() => {
    IsIotUpgrade().then(res => {
      if (res.code === 0) {
        setUpgrade(res.data);
        console.log(res);
      }
    });

    GetCurentIotVerison();
    GetIotConfig();
    return () => {
      if (time) {
        clearTimeout(time);
        time = null;
      }
      form.resetFields();
    };
  }, []);

  // 获取数据库连接
  const getCurrentConfig = () => {
    GetDataBaseConfig().then(res => {
      if (res.code === 0) {
        GetDbProduct({ ...res.data }).then(ress => {
          if (ress.data.Project.length > 0) {
            setKeep(ress.data.Project[ress.data.Project.length - 1].projectName);
          }
        });
        setCurrentDataBase(res.data);
        // 数据库是否已添加
        setLoading(true);
        CheckIsServiceAdd()
          .then(resdata1 => {
            setLoading(false);
            if (resdata1.code === 0) {
              if (resdata1.data === true) {
                setShow3('inline-block');
                setShow4('none');
                getStatus(res.data.ip, res.data.dbName);
              } else {
                setDbStatus(resdata1.msg);
                setBuStatus('添加');
                setSwitchStatus(true);
                setShow3('none');
                setShow4('inline-block');
              }
            }
          })
          .catch(err => {
            message.error('网络异常');
            setLoading(false);
          });
      }
    });
  };

  const getStatus = (x, y) => {
    // 查询是否禁用
    GetServiceInfo()
      .then(resdata => {
        if (resdata.code === 0) {
          setDbStatus(resdata.data.statusText);
          setProcessLength(resdata.data.loadingProgress * 100);
          if (resdata.data.statusText != '正常' && resdata.data.statusText != '已禁用') {
            setBuStatus('启动中');
            setSwitchStatus(true);
            time = setTimeout(() => {
              getStatus(x, y);
            }, 1000);
          } else {
            if (resdata.data.statusText == '正常') {
              setBuStatus('停止');
            }
            if (resdata.data.statusText == '已禁用') {
              setBuStatus('启动');
            }
            if (time) {
              clearTimeout(time);
              time = null;
            }
            setSwitchStatus(false);
          }

          if (resdata.data.statusText == '正常') {
            setCurrentConfig(true);
          } else {
            setCurrentConfig(false);
          }
        } else {
          message.error(resdata.msg);
        }
      })
      .catch(err => {
        if (time) {
          clearTimeout(time);
          time = null;
        }
        // message.error('访问异常请稍后再试');
      });
  };

  // 获取站点编号
  const getSiteCode = () => {
    GetBasicInfo().then(res => {
      if (res.code === 0) {
        setcurrentSiteInfo(res.data);
      }
    });
  };

  const GetCurentIotVerison = () => {
    GetIOTPlatformVersion().then(res => {
      if (res.data) {
        setCurrentIotVersion(res);
      }
    });
  };

  // 获取物联平台，EMQ服务地址
  const GetIotConfig = () => {
    GetTCPConfigInfo().then(res => {
      if (res.data) {
        let obj = {};
        Object.keys(currentIotConfig).forEach(k => {
          obj[k] = res.data[k];
        });
        GetIotVersion({
          ip: obj.IotAddress,
        }).then(resdata => {
          if (resdata.code === 0) {
            if (resdata.data === 'BS') {
              GetGateWay().then(resda => {
                if (resda.code === 0) {
                  if (resda.data === false) {
                    setFlag(0);
                    setGetWayVisible(true);
                  } else {
                    setFlag(1);
                    getCurrentConfig();
                    getSiteCode();
                    // HealthCheck()
                    //   .then(ress => {
                    //     if (ress.success) {
                    //       setFlag(1);
                    //       getCurrentConfig();
                    //       getSiteCode();
                    //     } else {
                    //       setFlag(0);
                    //     }
                    //   })
                    //   .catch(err => {
                    //     console.log(err);
                    //   });
                  }
                }
              });
            } else {
              setFlag(0);
            }
          } else {
            message.error(resdata.msg);
          }
        });
        form.setFieldsValue(obj);
        // if (!obj.IotAddress || obj.IotAddress == null) {
        //   form.setFieldsValue({ IotAddress: '127.0.0.1' });
        // }
        // if (!obj.TcpAddress || obj.TcpAddress == null) {
        //   form.setFieldsValue({ TcpAddress: '127.0.0.1:8083' });
        // }
        if (!obj.SSLSafe || obj.SSLSafe == null) {
          form.setFieldsValue({ SSLSafe: '否' });
        }
        setCurrentIotConfig(val => ({ ...val, ...obj }));
      }
    });
  };

  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 });
    } else {
      if (values.SSLSafe === '是') {
        values.SSLSafe = 1;
      }
      if (values.SSLSafe === '否') {
        values.SSLSafe = 0;
      }
      SaveIotConfig({
        tcpAddress: values.TcpAddress,
        iotAddress: values.IotAddress || currentIotConfig.IotAddress,
        sslSafe: values.SSLSafe,
      });
    }
  };

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

  // 物联网升级
  const PingIotUpdata = () => {
    setLoading(true);
    IotUpgrade().then(res => {
      setLoading(false);
      if (res.code === 0) {
        setUpgrade(false);
        message.success('升级成功!');
      } else {
        message.error(res.msg);
      }
    });
  };

  const PingIot = ({ ip, values }) => {
    SaveIotConfig({
      tcpAddress: values.TcpAddress,
      iotAddress: values.IotAddress,
      sslSafe: values.SSLSafe,
    });
  };
  const PingIot1 = () => {
    setLoading(true);
    let aa = form.getFieldsValue().IotAddress;
    console.log(aa);
    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 PingIot2 = () => {
    if (show3 === 'inline-block') {
      // 数据库已添加
      if (buStatus === '停止') {
        OperateNginx(false);
      } else if (buStatus === '启动') {
        OperateNginx(true);
      }
    } else {
      // 数据库未添加
      setLoading(true);
      AddDB().then(res => {
        setLoading(false);
        if (res.code === 0) {
          setShow3('inline-block');
          setShow4('none');
          message.success('添加成功!');
          getStatus(currentDataBase.ip, currentDataBase.dbName);
        } else {
          setShow3('none');
          setShow4('inline-block');
          message.error(res.msg);
        }
      });
    }
    // if (show3 == 'inline-block') {
    //   message.warning('该数据库已添加！');
    // } else if (!currentDataBase.ip) {
    //   message.error('未获取数据库信息');
    // } else if (!currentSiteInfo) {
    //   message.error('未获取站点编号');
    // } else {
    //   setLoading(true);
    //   AddDB({
    //     host: currentDataBase.ip,
    //     user: currentDataBase.userName,
    //     pwd: currentDataBase.password,
    //     dataBaseName: currentDataBase.dbName,
    //     siteCode: currentSiteInfo,
    //   }).then(res => {
    //     setLoading(false);
    //     if (res.success) {
    //       setShow3('inline-block');
    //       setShow4('none');
    //       message.success('添加成功!');
    //       getStatus(currentDataBase.ip, currentDataBase.dbName);
    //     } else {
    //       setShow3('none');
    //       setShow4('inline-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);
      }
    });
  };

  const OperateNginx = checked => {
    if (checked) {
      setSwitchStatus(true);
      setLoading(true);
      DepositServiceEnable().then(res => {
        setLoading(false);
        getStatus(currentDataBase.ip, currentDataBase.dbName);
        if (res.code === 0) {
          // setCurrentConfig(checked);
          message.success(res.msg);
        } else {
          message.error(res.msg);
        }
      });
    } else {
      setLoading(true);
      DepositServiceDisable().then(res => {
        setLoading(false);
        if (res.code === 0) {
          setDbStatus('已禁用');
          setBuStatus('启动');
          setProcessLength(0);
          setCurrentConfig(checked);
          message.success(res.msg);
        } else {
          message.error(res.msg);
        }
      });
    }
  };

  const submit = () => {
    window.location.href = `/civmanage/platform/host`;
  };
  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
            form={form}
            name="basic"
            initialValues={{ remember: true }}
            onFinish={onFinish}
            onFinishFailed={onFinishFailed}
          >
            <div
              style={{
                marginTop: '10px',
                display: 'flex',
                alignItems: 'center',
              }}
            >
              <img src={Internet} style={{ height: '16px' }} alt="" />
              <span style={{ marginLeft: '10px', fontWeight: 'bold' }}>物联网统一接入平台</span>
              {/* <div>
                {getWay === false ? (
                  <>
                    <InfoCircleFilled
                      style={{
                        color: '#faad14',
                        fontSize: '18px',
                        marginLeft: '10px',
                      }}
                    />
                    <span style={{ marginLeft: '5px' }}>请开启网关！</span>
                  </>
                ) : (
                  <></>
                )}
              </div> */}
            </div>
            <Divider />
            <Form.Item style={{ marginLeft: '20px', marginBottom: '0px' }}>
              <div style={{ display: 'flex', justifyContent: 'flex-start' }}>
                <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: '300px', marginLeft: '15px' }}
                    // placeholder="请输入服务地址"
                  />
                </Form.Item>
                <Button onClick={() => PingIot1()} style={{ marginLeft: '-88px' }}>
                  测试连接
                </Button>
                {upgrade && (
                  <>
                    <Button
                      type="primary"
                      onClick={() => PingIotUpdata()}
                      style={{ marginLeft: '25px' }}
                    >
                      平台升级
                    </Button>
                    <Tooltip title="添加物联统一接入平台的子网站，并导入网页菜单数据">
                      <QuestionCircleOutlined
                        style={{ fontSize: '18px', marginLeft: '10px', marginTop: '12px' }}
                      />
                    </Tooltip>
                  </>
                )}
                <span style={{ display: show1 }}>
                  <img
                    src={Yes}
                    style={{
                      height: '24px',
                      marginTop: '5px',
                      marginLeft: '26px',
                    }}
                    alt=""
                  />
                </span>
                <span style={{ display: show2 }}>
                  <CloseCircleFilled
                    style={{
                      fontSize: '24px',
                      marginTop: '5px',
                      marginLeft: '26px',
                    }}
                  />
                </span>
              </div>
            </Form.Item>

            <div style={{ marginTop: '20px' }}>
              {flag === 1 ? (
                <>
                  <Form.Item label="当前数据库" style={{ marginLeft: '50px' }}>
                    <span style={{ marginLeft: '14px' }}>{`${currentDataBase.ip}/${
                      currentDataBase.dbName
                    }`}</span>
                    {show3 === 'none' ? <></> : <span>({dbStatus})</span>}
                  </Form.Item>
                  <Form.Item label="加载进度" style={{ marginLeft: '65px' }}>
                    <div style={{ width: 200, marginBottom: '30px' }}>
                      <Progress
                        style={{ marginTop: '4px', marginLeft: '14px' }}
                        strokeColor={{
                          from: '#108ee9',
                          to: '#87d068',
                        }}
                        percent={processLength}
                        status={processLength == '100' ? 'success' : 'active'}
                      />
                    </div>
                    <div>
                      <Button
                        type="primary"
                        onClick={() => PingIot2()}
                        style={{ marginLeft: '15px' }}
                        disabled={buStatus === '启动中'}
                      >
                        {buStatus}
                      </Button>
                      {/* <Switch
                      checkedChildren="开启"
                      unCheckedChildren="关闭"
                      checked={currentConfig}
                      onChange={OperateNginx}
                      style={{ marginLeft: '15px' }}
                      disabled={switchStatus}
                    /> */}
                    </div>
                  </Form.Item>
                </>
              ) : (
                <></>
              )}
            </div>

            <div
              style={{
                marginTop: '40px',
                display: 'flex',
                alignItems: 'center',
              }}
            >
              <img src={EMQ} style={{ height: '16px' }} alt="" />
              <span style={{ marginLeft: '10px', fontWeight: 'bold' }}>EMQ</span>
            </div>
            <Divider />
            <Form.Item
              style={{ marginLeft: '20px' }}
              label="服务地址(EMQ)"
              name="TcpAddress"
              rules={[
                {
                  required: true,
                  pattern: new RegExp(/^.*:.*$/),
                  message: '请输入正确的IP:端口',
                },
              ]}
            >
              <Input style={{ width: '300px', marginLeft: '13px' }} />
            </Form.Item>
            <Form.Item
              style={{ marginLeft: '20px' }}
              name="SSLSafe"
              label="SSL(EMQ)"
              rules={[{ required: true, message: '请选择是否!' }]}
            >
              <Select placeholder="请选择是否!" style={{ width: '300px', marginLeft: '48px' }}>
                <Option value="1">是</Option>
                <Option value="0">否</Option>
              </Select>
            </Form.Item>
            <Form.Item>
              <Button type="primary" htmlType="submit" style={{ marginLeft: '152px' }}>
                保存
              </Button>
            </Form.Item>
          </Form>
        </Spin>
      </Card>
      <Modal
        visible={getWayVisible}
        title="提示"
        width="350px"
        closable
        maskClosable={false}
        onCancel={() => setGetWayVisible(false)}
        all
        footer={
          <Space>
            <Button
              onClick={() => {
                setGetWayVisible(false);
                setActiveKey('6');
              }}
              type="primary"
            >
              好的，去开启
            </Button>
          </Space>
        }
      >
        <InfoCircleFilled
          style={{
            color: '#faad14',
            fontSize: '18px',
            marginRight: '10px',
          }}
        />
        <span>当前网关暂未打开，请前往开启！</span>
      </Modal>
    </div>
  );
};
export default IotConfig;
