import React, { useEffect, useState } from 'react';
import { Card, Form, Input, Button, Select, message, Divider, Spin, Row, Col } from 'antd';
import {
  GetMessageConfigInfo,
  SaveSystemInfo,
  ConnectMessPlatform,
  GetBasicInfo,
  GetDataBaseConfig,
} from '@/services/hostmanager/hostmanager';
import { GetMessageVersion } from '@/services/messagemanage/messagemanage';
import { CloseCircleFilled } from '@ant-design/icons';
import CryptoJS from 'crypto-js';
import message11 from '../../../../assets/images/icons/消息.svg';
import Yes from '../../../../assets/images/icons/正确.svg';
import styles from './messageConfig.less';

const layout = {
  labelCol: { span: 2 },
  wrapperCol: { span: 21 },
};
const tailLayout = {
  wrapperCol: { offset: 11, span: 13 },
};
const MessageConfig = () => {
  const [loading, setLoading] = useState(false); // 加载
  const [currentAddress, setCurrentAddress] = useState('');
  const [currentDataBase, setCurrentDataBase] = useState({});
  const [currentSiteInfo, setcurrentSiteInfo] = useState('');
  const [show1, setShow1] = useState('none');
  const [show2, setShow2] = useState('none');
  const [messageVersion, setMessageVersion] = useState('');
  const [flag, setFlag] = useState(0);

  const [form] = Form.useForm();

  const key = CryptoJS.enc.Utf8.parse('1p2a3n4d5a6o7m8s9a10n1e2t3c4o5re'); // 十六位十六进制数作为密钥
  const iv = CryptoJS.enc.Utf8.parse('1234567890000000');

  // 解密
  const Decrypt = word => {
    let encryptedHexStr = CryptoJS.enc.Hex.parse(word);
    let srcs = CryptoJS.enc.Base64.stringify(encryptedHexStr);
    let decrypt = CryptoJS.AES.decrypt(srcs, key, {
      iv,
      mode: CryptoJS.mode.CBC,
      padding: CryptoJS.pad.Pkcs7,
    });
    let decryptedStr = decrypt.toString(CryptoJS.enc.Utf8);
    return decryptedStr.toString();
  };

  // 加密
  const Encrypt = word => {
    let srcs = CryptoJS.enc.Utf8.parse(word);
    let encrypted = CryptoJS.AES.encrypt(srcs, key, {
      iv,
      mode: CryptoJS.mode.CBC,
      padding: CryptoJS.pad.Pkcs7,
    });
    return encrypted.ciphertext.toString().toUpperCase();
  };
  const onFinish = values => {
    // 先测试连接再保存
    // 1.测试链接
    setLoading(true);
    ConnectMessPlatform({
      messAddress: values.messageAddress,
      sqlServerIP: currentDataBase.ip,
      loginName: currentDataBase.userName,
      password: Encrypt(currentDataBase.password),
      sqlName: currentDataBase.dbName,
      siteCode: currentSiteInfo,
    }).then(res => {
      setLoading(false);
      if (res.code === 0) {
        setShow1('block');
        setShow2('none');
        // 2.保存连接
        SaveSystemInfo({
          configName: '消息平台连接地址',
          configValue: values.messageAddress,
        }).then(resdata => {
          if (resdata.code === 0) {
            message.info('配置保存成功');
          } else {
            message.error(resdata.msg);
          }
        });
      } else {
        setShow1('none');
        setShow2('block');
        message.error(res.msg);
      }
    });
  };

  const getMessageConfig = (CurrentAddress, CurrentDataBase, currentSiteInfo) => {
    setLoading(true);
    ConnectMessPlatform({
      messAddress: CurrentAddress,
      sqlServerIP: CurrentDataBase.ip,
      loginName: CurrentDataBase.userName,
      password: Encrypt(CurrentDataBase.password),
      sqlName: CurrentDataBase.dbName,
      siteCode: currentSiteInfo,
    }).then(res => {
      setLoading(false);
      if (res.code === 0) {
        setShow1('block');
        setShow2('none');
      } else {
        setShow1('none');
        setShow2('block');
        message.error(res.msg);
      }
    });
  };

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

  useEffect(() => {
    // form.setFieldsValue({ messageAddress: '127.0.0.1:8231' });
    GetMessageConfigInfo().then(res => {
      if (res.code == 0) {
        setCurrentAddress(res.data);
        // if (!res.data || res.data == null) {
        //   form.setFieldsValue({ messageAddress: '127.0.0.1:8231' });
        // } else {
        //   form.setFieldsValue({ messageAddress: res.data });
        // }
        form.setFieldsValue({ messageAddress: res.data });

        GetDataBaseConfig().then(resdata => {
          if (resdata.code === 0) {
            setCurrentDataBase({ ...resdata.data, password: Decrypt(resdata.data.password) });
            GetBasicInfo().then(reslist => {
              if (reslist.code === 0) {
                setcurrentSiteInfo(reslist.data);
                // getMessageConfig(CurrentAddress, CurrentDataBase, currentSiteInfo);
              }
            });
          }
        });
      } else {
        message.info('获取消息平台配置失败!');
      }
    });
    getMessageVersion();
    return () => {
      form.resetFields();
    };
  }, [flag]);

  const getMessageVersion = () => {
    GetMessageVersion().then(res => {
      console.log(res.data);
      setMessageVersion(res.data);
    });
  };

  const butn = () => {
    console.log(messageVersion);
    let data = '';
    if (messageVersion == '1.0') {
      data = '2.0';
    } else {
      data = '1.0';
    }
    SaveSystemInfo({
      configName: '消息解析规则版本',
      configValue: data,
    }).then(resdata => {
      if (resdata.code === 0) {
        message.info('配置保存成功');
        getMessageVersion();
      } else {
        message.error(resdata.msg);
      }
    });
  };

  return (
    <div className={styles.message_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={{
                marginTop: '10px',
                display: 'flex',
                alignItems: 'center',
              }}
            >
              <img src={message11} style={{ height: '16px' }} alt="" />
              <span style={{ marginLeft: '10px', fontWeight: 'bold' }}>消息平台</span>
            </div>
            <Divider />
            <Form.Item
              style={{ marginLeft: '20px', marginBottom: '0px' }}
              // label="服务地址(平台)"
              // name="messageAddress"
              // 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',
              //   },
              // ]}
            >
              <div style={{ display: 'flex', justifyContent: 'flex-start' }}>
                <Form.Item
                  label="服务地址(平台)"
                  name="messageAddress"
                  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', marginLeft: '15px' }}
                    // placeholder="请输入服务地址"
                  />
                </Form.Item>
                <span style={{ display: show1 }}>
                  <img
                    src={Yes}
                    style={{ height: '24px', marginLeft: '26px', marginTop: '10px' }}
                    alt=""
                  />
                </span>
                <span style={{ display: show2 }}>
                  <CloseCircleFilled
                    style={{ fontSize: '24px', marginLeft: '26px', marginTop: '10px' }}
                  />
                </span>
              </div>
            </Form.Item>

            <Form.Item>
              <Button type="primary" htmlType="submit" style={{ marginLeft: '152px' }}>
                保存连接
              </Button>
            </Form.Item>
            <Form.Item label="消息版本" style={{ marginLeft: '67px', marginBottom: '0px' }}>
              <span style={{ marginLeft: '15px', color: 'red', fontWeight: 'bold' }}>
                {messageVersion}
              </span>
            </Form.Item>
            <Form.Item>
              <Button
                type="primary"
                style={{ marginLeft: '152px', marginTop: '13px', width: '88px' }}
                onClick={butn}
              >
                {messageVersion == '1.0' ? '升级' : '回退'}
              </Button>
              <br />
              <br />
              <span style={{ color: 'red', fontWeight: 'bold', marginLeft: '152px' }}>
                提示：web4请使用1.0版本，web5请使用2.0版本，请根据项目的实际情况决定
              </span>
            </Form.Item>
          </Form>
        </Spin>
      </Card>
    </div>
  );
};
export default MessageConfig;
