/* eslint-disable guard-for-in */
/* eslint-disable no-restricted-syntax */
/* eslint-disable no-lonely-if */
/* eslint-disable prefer-promise-reject-errors */
/* eslint-disable no-else-return */
/* eslint-disable spaced-comment */
/* eslint-disable eqeqeq */
import React, { useEffect, useRef, useState } from 'react';
import {
  Card,
  Form,
  Input,
  Button,
  Space,
  notification,
  Modal,
  Spin,
  Divider,
  Checkbox,
  Popconfirm,
  Timeline,
  Tooltip,
  Table,
  message,
} from 'antd';
import PageContainer from '@/components/BasePageContainer';
import { connect } from 'react-redux';
import {
  getInitDBLogNew,
  deleteInitDBLogNew,
  GetProductList, // 获取产品列表
  GetDbProduct, // 获取产品方案配置
  SetAdminMenuToRole,
  CheckDatabaseIsExist,
  NewInitAddDataBase,
  InitEditDataBase,
  getDataBaseConfigNew,
} from '@/services/database/api';
import {
  CloseCircleOutlined,
  CheckCircleOutlined,
  ZoomInOutlined,
  ExclamationCircleOutlined,
  BarcodeOutlined,
  UserOutlined,
  CalendarOutlined,
  CheckOutlined,
  MinusSquareOutlined,
  PlusOutlined,
  EyeOutlined,
} from '@ant-design/icons';
import CryptoJS from 'crypto-js';
import styles from './DatabaseInitialization.less';
import styles1 from '../InitDataBase/InitDataBase.less';
import AppendModal from './AppendModal';

const CheckboxGroup = Checkbox.Group;
const formLables = {
  ip: '服务器地址',
  userName: '用户名称',
  password: '用户密码',
  dbName: '数据库名称',
};
let time = null;
const DatabaseInitialization = props => {
  const [form] = Form.useForm();
  const [modalVisible, setModalVisible] = useState({
    describeVisible: false, // 描述弹窗
    versionVisible: false, // 检查版本弹窗
    initVisible: false, // 初始化选择产品弹窗
  }); // 修改弹窗
  const [initVisible, setInitVisible] = useState(false); // 数据库初始化弹窗
  const [initVisibledetail, setinitVisibledetail] = useState(false); // 数据库初始化详细信息弹窗
  const [initContent, setInitContent] = useState(''); // 数据库初始化内容
  const [initContentdetail, setInitContentdetail] = useState(''); // 数据库初始化详细内容
  const [cardLoading, setCardLoading] = useState(false); // 初始化card Loading
  const [finish, setFinish] = useState(false);
  const [initLoading, setInitLoading] = useState(false);
  const [keepDb, setKeepDb] = useState([]);
  const [keepProduct, setKeepProduct] = useState([]);
  const [keepStatus, setKeepStatus] = useState([]);
  const scroll = useRef(null);

  const [data, setData] = useState([]);
  const [title, setTitle] = useState([]);
  const [keepCode, setKeepCode] = useState([]);
  const [keepData, setKeepData] = useState([]);
  const [keepValue, setKeepValue] = useState([]);
  const [value, setValue] = useState([]);
  const [product, setProduct] = useState([]);
  const [msg, setMsg] = useState('null');
  const [keepNumber, setkeepNumber] = useState('');
  const [keepNa, setkeepNa] = useState('');
  const [keepCo, setkeepCo] = useState('');
  const [keepMsg, setkeepMsg] = useState('');
  const [allLength, setAllLength] = useState('');
  const [oldColor, setOldColor] = useState('gray');
  const [beforeColor, setbeforeColor] = useState('gray');
  const [firstColor, setfirstColor] = useState('gray');
  const [secordColor, setsecordColor] = useState('gray');
  const [lastColor, setLastColor] = useState('gray');
  const [totalProduct, setTotalProduct] = useState('');
  const [simpleProduct, setSimpleProduct] = useState('');
  const [show, setShow] = useState('hidden');
  const [keepInline, setKeepInline] = useState([]);
  const [ifInline, setIfInline] = useState('hidden');
  const [result, setResult] = useState('');
  const [license, setLicense] = useState('');
  const [dataResult, setDataResult] = useState('');
  const [productResult, setProductResult] = useState('');
  const [keepInitContent, setKeepInitContent] = useState('');
  const [keepInitContentDetail, setKeepInitContentDetail] = useState('');
  const [keepinitVisible, setKeepInitVisible] = useState(false);
  const [password, setPassword] = useState(false);
  const [isAuthorize, setIsAuthorize] = useState(false);
  const [licen, setLicen] = useState('');
  const [showDetali, setShowDetali] = useState(false);
  const [keepLast, setKeepLast] = useState('');
  const [appendVisible, setAppendVisible] = useState(false);
  const [append, setAppend] = useState('不需要追加');
  const [dataValue, setDataValue] = useState();
  const [keepHistroy, setKeepHistroy] = useState([]);
  const [historyVisible, setHistoryVisible] = useState(false);
  const [keepInitDetailVisible, setKeepInitDetailVisible] = useState(false);

  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();
  };

  // 获取数据库配置信息
  useEffect(() => {
    setCardLoading(true);
    getProductList();
    // form.setFieldsValue({ ip: '127.0.0.1', password: 'sa', userName: 'sa' });
  }, []);

  const getProductList = () => {
    GetProductList().then(res => {
      setCardLoading(false);
      if (res.code === 0) {
        GetDb(res.data);
        setKeepData(res.data);
        let arr = formateArrDataA(res.data, 'productName');
        let aa = Object.keys(arr);
        aa.map(i => {
          let list = [];
          arr[i].map(j => {
            list.push(j.name);
          });
          arr[i] = list;
        });
        setAllLength(res.data.length);
        setTitle(aa);
        setData(arr);
      }
    });
  };

  const formateArrDataA = (initialArr, name) => {
    // 判定传参是否符合规则
    if (!(initialArr instanceof Array)) {
      return '请传入正确格式的数组';
    }
    if (!name) {
      return '请传入对象属性';
    }
    // 先获取一下这个数组中有多少个"name"
    let nameArr = [];
    for (let i in initialArr) {
      if (nameArr.indexOf(initialArr[i][`${name}`]) === -1) {
        nameArr.push(initialArr[i][`${name}`]);
      }
    }
    // 新建一个包含多个list的结果对象
    let tempObj = {};
    // 根据不同的"name"生成多个数组
    for (let k in nameArr) {
      for (let j in initialArr) {
        if (initialArr[j][`${name}`] == nameArr[k]) {
          // 每次外循环时新建一个对应"name"的数组, 内循环时当前数组不变
          tempObj[nameArr[k]] = tempObj[nameArr[k]] || [];
          tempObj[nameArr[k]].push(initialArr[j]);
        }
      }
    }
    for (let keys in tempObj) {
      let arr = [];
      tempObj[keys].map((item, index) => {
        tempObj[keys] = arr;
        item.key = index;
        arr.push(item);
      });
    }
    return tempObj;
  };
  // 弹出模态框
  const handleShowModal = (key, value) => {
    setModalVisible({ ...modalVisible, [key]: value });
  };

  // 获取日志
  const doInitLog = () => {
    setInitLoading(true);
    getInitDBLogNew()
      .then(res => {
        if (res.code === 0) {
          if (res.data.content) {
            let arr = [];
            arr.push(
              res.data.content.split(/(\r\n)|(\n)/).map((item, index) => (
                // eslint-disable-next-line react/no-danger
                <p key={index} dangerouslySetInnerHTML={{ __html: item }} />
              )),
            );
            console.log(arr);
            setInitContent(arr);
            setKeepInitContent(arr);
            scroll.current.scrollTop = scroll.current.scrollHeight;
          }

          if (!res.data.finish) {
            // if (!finish) {
            time = setTimeout(() => {
              doInitLog();
            }, 600);
            // } else {
            //   setInitLoading(false);
            //   setShow('visible');
            //   if (time) {
            //     clearTimeout(time);
            //     time = null;
            //   }
            // }
          } else {
            setInitLoading(false);
            setShow('visible');
            if (time) {
              clearTimeout(time);
              time = null;
            }
          }
        }
      })
      .catch(err => {
        if (time) {
          clearTimeout(time);
          time = null;
        }
        message.error(err);
        setFinish(true);
      });
  };

  // 获取详细日志
  const doInitLogdetali = () => {
    getInitDBLogNew({ isAllInitDBLog: true })
      .then(res => {
        if (res.code === 0) {
          if (res.data.content) {
            let arr = [];
            arr.push(
              res.data.content.split(/(\r\n)|(\n)/).map((item, index) => (
                // eslint-disable-next-line react/no-danger
                <p key={index} dangerouslySetInnerHTML={{ __html: item }} />
              )),
            );
            console.log(arr);
            setInitContentdetail(arr);
            setKeepInitContentDetail(arr);
            setShowDetali(true);
            scroll.current.scrollTop = scroll.current.scrollHeight;
          }
        }
      })
      .catch(err => {
        console.log(err);
      });
  };

  const onValuesChange = (value, b) => {
    form.setFieldsValue(value);
  };

  const handlelook = () => {
    setInitVisible(false);
    setinitVisibledetail(true);
    doInitLogdetali();
  };

  // 关闭弹窗
  const handleClickdetail = () => {
    setinitVisibledetail(false);
    setInitContent('');
    setInitContentdetail('');
    setFinish(false);
    // deleteInitDBLogNew();
    setShowDetali(false);
  };

  // 关闭弹窗
  const handleClick = () => {
    setInitVisible(false);
    // setInitContent('');
    // setInitContentdetail('');
    setFinish(false);
    // deleteInitDBLogNew();
    setShowDetali(false);
  };

  const GetDb = kk => {
    getDataBaseConfigNew().then(resdata => {
      GetDbProduct({
        ip: resdata.data.ip,
        dbName: resdata.data.dbName,
        userName: resdata.data.userName,
        password: resdata.data.password,
      }).then(res => {
        if (res.code === 0) {
          if (res.data.DbInfo.ip == '127.0.0.1' || !res.data.DbInfo.ip) {
            setIfInline('hidden');
          } else {
            setIfInline('visible');
          }
          setKeepInline(res.data.DbInfo);
          if (res.data.Project && res.data.Project.length > 0) {
            setKeepHistroy(res.data.Project);
            setkeepNumber(res.data.Project[res.data.Project.length - 1].license);
            setkeepMsg(res.data.Project[res.data.Project.length - 1].projectName);
            setkeepNa(res.data.Project[res.data.Project.length - 1].applicantName);
            setkeepCo(res.data.Project[res.data.Project.length - 1].jobNumber);
          } else {
            setKeepHistroy([]);
            // setKeepProductData('');
            setkeepNumber('');
            setkeepMsg('');
            setkeepNa('');
            setkeepCo('');
          }

          // form.setFieldsValue(res.data.DbInfo);
          form.setFieldsValue({
            ip: resdata.data.ip,
            dbName: resdata.data.dbName,
            userName: resdata.data.userName,
            password: Decrypt(resdata.data.password),
          });
          GetDbChangeFirst(kk);
          // 有License的情况下首次进入展示数据
          // if (res.data.IsAuthorize) {
          console.log(res.data.Product);
          if (res.data.Product.length > 0) {
            let aa = [];
            let gg = [];
            res.data.Product.map(i => {
              if (i.name !== null) {
                if (i.status == 1) {
                  gg.push(i.name);
                }
                aa.push(i.name);
              }
            });
            if (aa.length > 0) {
              let dd = [];
              aa.map(i => {
                kk.map(j => {
                  if (j.name === i) {
                    dd.push(j);
                  }
                });
              });
              let Arr = Array.from(new Set(dd));
              let arr = formateArrDataA(Arr, 'productName');
              let a = Object.keys(arr);
              a.map(i => {
                let list = [];
                arr[i].map(j => {
                  list.push(j.name);
                });
                arr[i] = list;
              });
              setProduct(arr);
              setKeepValue(arr);
            }
            console.log(aa);
            let newArr = Array.from(new Set(aa));
            setKeepStatus(gg);
            console.log(newArr);
            if (newArr.length > 0) {
              setKeepProduct(newArr);
              setKeepCode(newArr);
              setValue(newArr);
            } else {
              setKeepProduct([]);
              setKeepCode([]);
              setValue([]);
            }
          }
          setKeepDb(res.data);
          setIsAuthorize(res.data.IsAuthorize);
          if (res.data.IsAuthorize) {
            setMsg('');
          } else {
            if (
              res.data.Project &&
              res.data.Project[0] &&
              res.data.Project[res.data.Project.length - 1].license == '已使用'
            ) {
              setbeforeColor('red');
              setResult('未检测到可用License');
              setMsg('未检测到可用License');
            } else {
              setbeforeColor('red');
              setResult('未检测到License');
              setMsg('未检测到License');
            }
          }
        } else {
          notification.error({
            message: '提示',
            duration: 3,
            description: res.msg,
          });
        }
      });
    });
  };

  const GetDbChangeFirst = kk => {
    let obj = form.getFieldsValue();
    GetDbProduct({ ...obj, password: Encrypt(obj.password) }).then(res => {
      setCardLoading(false);
      if (res.code === 0) {
        if (res.data.IsAuthorize) {
          if (kk) {
            findCheck1(res.data.IsAppend);
          } else {
            onCheckLaster(res.data.IsAppend);
          }
        } else {
          if (
            res.data.Project &&
            res.data.Project[0] &&
            res.data.Project[res.data.Project.length - 1].license == '已使用'
          ) {
            setbeforeColor('red');
            setResult('未检测到可用License');
            setMsg('未检测到可用License');
          } else {
            setbeforeColor('red');
            setResult('未检测到License');
            setMsg('未检测到License');
          }
        }
        if (res.data.Project && res.data.Project.length > 0) {
          setKeepHistroy(res.data.Project);
          setkeepNumber(res.data.Project[res.data.Project.length - 1].license);
          setkeepMsg(res.data.Project[res.data.Project.length - 1].projectName);
          setkeepNa(res.data.Project[res.data.Project.length - 1].applicantName);
          setkeepCo(res.data.Project[res.data.Project.length - 1].jobNumber);
        } else {
          // setKeepProductData('');
          setKeepHistroy([]);
          setkeepNumber('');
          setkeepMsg('');
          setkeepNa('');
          setkeepCo('');
        }
      } else {
        notification.error({
          message: '提示',
          duration: 3,
          description: res.msg,
        });
      }
    });
  };

  const GetDbChange = e => {
    let obj = form.getFieldsValue();
    GetDbProduct({ ...obj, password: Encrypt(obj.password) }).then(res => {
      setCardLoading(false);
      if (res.code === 0) {
        if (res.data.IsAuthorize) {
          // setMsg('');
          if (e) {
            findCheck(res.data.IsAppend);
          } else {
            onCheckLaster(res.data.IsAppend);
          }
        } else {
          let obj1 = form.getFieldsValue();
          CheckDatabaseIsExist({ ...obj1, password: Encrypt(obj.password) }).then(res1 => {
            setCardLoading(false);
            if (res1.code === 0) {
              if (
                res1.data.Project &&
                res1.data.Project[0] &&
                res1.data.Project[res1.data.Project.length - 1].license == '已使用'
              ) {
                setbeforeColor('red');
                setResult('未检测到可用License');
                setMsg('未检测到可用License');
              } else {
                setbeforeColor('red');
                setResult('未检测到License');
                setMsg('未检测到License');
              }
            } else {
              setbeforeColor('red');
              setResult(`${res1.msg}`);
              setMsg(res1.msg);
            }
          });
        }
        if (res.data.Project && res.data.Project.length > 0) {
          setKeepHistroy(res.data.Project);
          setkeepNumber(res.data.Project[res.data.Project.length - 1].license);
          setkeepMsg(res.data.Project[res.data.Project.length - 1].projectName);
          setkeepNa(res.data.Project[res.data.Project.length - 1].applicantName);
          setkeepCo(res.data.Project[res.data.Project.length - 1].jobNumber);
        } else {
          // setKeepProductData('');
          setKeepHistroy([]);
          setkeepNumber('');
          setkeepMsg('');
          setkeepNa('');
          setkeepCo('');
        }
        if (res.data.Product.length > 0) {
          let aa = [];
          let gg = [];
          res.data.Product.map(i => {
            if (i.name !== null) {
              if (i.status == 1) {
                gg.push(i.name);
              }
              aa.push(i.name);
            }
          });
          if (aa.length > 0) {
            let dd = [];
            aa.map(i => {
              keepData.map(j => {
                if (j.name === i) {
                  dd.push(j);
                }
              });
            });
            let Arr = Array.from(new Set(dd));
            let arr = formateArrDataA(Arr, 'productName');
            let a = Object.keys(arr);
            a.map(i => {
              let list = [];
              arr[i].map(j => {
                list.push(j.name);
              });
              arr[i] = list;
            });
            setProduct(arr);
            console.log(arr);
            setKeepValue(arr);
          }
          let newArr = Array.from(new Set(aa));
          // 当前数据库已存在和上一个已存在数据库值重新赋值
          if (newArr.length > 0) {
            console.log(newArr);
            setKeepProduct(newArr);
            setKeepStatus(gg);
            setKeepCode(newArr);
            setValue(newArr);
          } else {
            setKeepProduct([]);
            setKeepStatus([]);
            setKeepCode([]);
            setValue([]);
          }
          if (res.data.Product.length == 0) {
            setKeepValue([]);
          }
        }
        setKeepDb(res.data);
        setIsAuthorize(res.data.IsAuthorize);
      } else {
        notification.error({
          message: '提示',
          duration: 3,
          description: res.msg,
        });
      }
    });
  };

  const GetDbChangeAppend = () => {
    let obj = form.getFieldsValue();
    GetDbProduct({ ...obj, password: Encrypt(obj.password) }).then(res => {
      setCardLoading(false);
      if (res.code === 0) {
        if (res.data.Product.length > 0) {
          let aa = [];
          let gg = [];
          res.data.Product.map(i => {
            if (i.name !== null) {
              if (i.status == 1) {
                gg.push(i.name);
              }
              aa.push(i.name);
            }
          });
          // 后端返回出局的分组名可能发生改变,前端处理数据展示新分组名
          if (aa.length > 0) {
            let dd = [];
            aa.map(i => {
              keepData.map(j => {
                if (j.name === i) {
                  dd.push(j);
                }
              });
            });
            let Arr = Array.from(new Set(dd));
            let arr = formateArrDataA(Arr, 'productName');
            let a = Object.keys(arr);
            a.map(i => {
              let list = [];
              arr[i].map(j => {
                list.push(j.name);
              });
              arr[i] = list;
            });
            setProduct(arr);
            setKeepValue(arr);
          }
          let newArr = Array.from(new Set(aa));
          // 当前数据库已存在和上一个已存在数据库值重新赋值
          if (newArr.length > 0) {
            console.log(newArr);
            setKeepProduct(newArr);
            setKeepStatus(gg);
            setKeepCode(newArr);
            setValue(newArr);
          } else {
            setKeepProduct([]);
            setKeepStatus([]);
            setKeepCode([]);
            setValue([]);
          }
          if (res.data.Product.length == 0) {
            setKeepValue([]);
          }
        }
        if (res.data.Project && res.data.Project.length > 0) {
          setKeepHistroy(res.data.Project);
        } else {
          setKeepHistroy([]);
        }
        setKeepDb(res.data);
        setIsAuthorize(res.data.IsAuthorize);
      } else {
        notification.error({
          message: '提示',
          duration: 3,
          description: res.msg,
        });
      }
    });
  };

  const onOK = arr => {
    initDatabasePro(arr);
  };

  // 数据库初始化
  const initDatabasePro = e => {
    let productSetting = e;
    let obj = form.getFieldsValue();
    // 数据库存在调用编辑接口否则调用新增接口
    handleShowModal('initVisible', false);
    setInitVisible(true);
    doInitLog();
    NewInitAddDataBase({ ...obj, productSetting, password: Encrypt(obj.password) }).then(res => {
      if (res.code === 0) {
        GetDbChangeAppend(); // 刷星已初始化的产品勾选
        setMsg('未检测到可用License');
        setfirstColor('green');

        setDataResult('成功');
        notification.success({
          message: '提示',
          duration: 3,
          description: '数据库初始化成功',
        });
        if (keepNumber != '') {
          setkeepNumber('已使用');
        }
        if (res.data.productPackageCount == 0) {
          setProductResult('产品授权不包含已初始化的产品');
          setsecordColor('#eda625');
        } else {
          setsecordColor('green');
        }
        setTotalProduct(res.data.productPackageSumCount);
        setSimpleProduct(res.data.productPackageCount);
        // 给平台管理员赋值所有菜单权限
        SetAdminMenuToRole().then(resdata => {
          if (resdata.code === 0) {
            setLastColor('green');
            setKeepLast('');
          } else {
            setLastColor('red');
            setKeepLast(res.data.msg);
          }
        });
      } else {
        setDataResult(res.msg);
        setFinish(true);
        setfirstColor('red');
        setsecordColor('gray');
        setLastColor('gray');
        notification.error({
          message: '提示',
          duration: 3,
          description: res.msg,
        });
      }
    });
  };

  // 数据库初始化追加
  const initDatabaseProAppend = () => {
    // 数据库存在调用编辑接口否则调用新增接口
    handleShowModal('initVisible', false);
    setInitVisible(true);
    doInitLog();
    let obj = form.getFieldsValue();
    InitEditDataBase({ ...obj, password: Encrypt(obj.password) }).then(res => {
      if (res.code === 0) {
        GetDbChangeAppend();
        setMsg('未检测到可用License');
        setfirstColor('green');
        setDataResult('成功');
        notification.success({
          message: '提示',
          duration: 3,
          description: '数据库初始化追加成功',
        });
        if (keepNumber != '') {
          setkeepNumber('已使用');
        }
        if (res.data.productPackageCount == 0) {
          setProductResult('产品授权不包含已初始化的产品');
          setsecordColor('#eda625');
        } else {
          setsecordColor('green');
        }
        setTotalProduct(res.data.productPackageSumCount);
        setSimpleProduct(res.data.productPackageCount);
        setLastColor('green');
        setKeepLast('');
      } else {
        setDataResult(res.msg);
        setFinish(true);
        setfirstColor('red');
        setsecordColor('gray');
        setLastColor('gray');
        notification.error({
          message: '提示',
          duration: 3,
          description: res.msg,
        });
      }
    });
  };

  const flagChange = () => {
    setbeforeColor('gray');
    setfirstColor('gray');
    setsecordColor('gray');
    setLastColor('gray');
    setSimpleProduct('');
    setTotalProduct('');
    onCheck();
  };

  const onChange1 = (e, item) => {
    if (product[item]) {
      // 过滤已初始化的产品但不存在于产品列表中的数据,避免组件出错
      product[item].map(i => {
        if (data[item].indexOf(i) == -1) {
          product[item].splice(product[item].findIndex(j => j === i), 1);
        }
      });

      let arr = product[item].find(i => e.indexOf(i) == -1);
      let bb = keepProduct.indexOf(arr);
      let aa = keepValue;
      aa[item] = e;
      let a = Object.keys(aa);
      let list = [];
      a.map(i => {
        aa[i].map(j => {
          list.push(j);
        });
      });
      setKeepValue(aa);
      setValue(list);
    } else {
      let aa = keepValue;
      aa[item] = e;
      let a = Object.keys(aa);
      let list = [];
      a.map(i => {
        aa[i].map(j => {
          list.push(j);
        });
      });
      setKeepValue(aa);
      setValue(list);
    }
  };

  const onCheck = () => {
    let obj = form.getFieldsValue();
    if (obj.ip && obj.userName && obj.password && obj.dbName) {
      // setKeepValue([]);
      setProduct([]);
      setCardLoading(true);
      GetProductList({ ...obj, password: Encrypt(obj.password) }).then(res => {
        if (res.code === 0) {
          console.log(res.data);
          GetDbChange();
          setKeepData(res.data);
          let arr = formateArrDataA(res.data, 'productName');
          let aa = Object.keys(arr);
          aa.map(i => {
            let list = [];
            arr[i].map(j => {
              list.push(j.name);
            });
            arr[i] = list;
          });
          setAllLength(res.data.length);
          setTitle(aa);
          setData(arr);
        } else {
          setCardLoading(false);
        }
      });

      // deleteInitDBLogNew();
    } else {
      setbeforeColor('red');
      setResult('请输入完整数据库信息');
      setMsg('请输入完整数据库信息');
    }
  };
  // 非授权模式下环境检查
  const checkUnLicense = () => {
    let obj = form.getFieldsValue();
    CheckDatabaseIsExist({ ...obj, password: Encrypt(obj.password) }).then(res => {
      setCardLoading(false);
      if (res.code !== 0) {
        setbeforeColor('red');
        setResult(`${res.msg}`);
        setMsg(res.msg);
      }
    });
  };

  const onCheckLaster = aa => {
    // 此时有授权码才能进入
    let obj = form.getFieldsValue();
    CheckDatabaseIsExist({ ...obj, password: Encrypt(obj.password) }).then(res => {
      setCardLoading(false);
      if (res.code == 0) {
        setDataValue(form.getFieldsValue());
        // 数据库不存在
        if (res.data === false) {
          setbeforeColor('green');
          setResult('通过');
          setAppend('无需追加');
          setMsg('');
          if (keepNumber && keepNumber != '已使用') {
            setMsg('');
          }
        } else {
          if (aa) {
            setbeforeColor('green');
            setResult('检测到License,当前环境需要追加产品');
            setMsg('检测到License,当前环境需要追加产品');
            setAppend('');
            setAppendVisible(true);
            console.log(form.getFieldsValue());
            setDataValue(form.getFieldsValue());
          } else {
            setbeforeColor('red');
            setResult('无法追加,该数据库为非授权初始化数据库,请直接升级数据库!');
            setMsg('无法追加,该数据库为非授权初始化数据库,请直接升级数据库!');
            setAppend('无需追加');
          }
        }
      } else {
        setbeforeColor('red');
        setResult(`${res.msg}`);
        setMsg(res.msg);
      }
    });
  };

  const Submit = () => {
    let obj = form.getFieldsValue();
    if (obj.ip && obj.userName && obj.password && obj.dbName) {
      GetProductList({ ...obj, password: Encrypt(obj.password) }).then(res => {
        setCardLoading(false);
        if (res.code === 0) {
          GetDbChange(1);
          setKeepData(res.data);
          let arr = formateArrDataA(res.data, 'productName');
          let aa = Object.keys(arr);
          aa.map(i => {
            let list = [];
            arr[i].map(j => {
              list.push(j.name);
            });
            arr[i] = list;
          });
          setAllLength(res.data.length);
          setTitle(aa);
          setData(arr);
        }
      });

      setCardLoading(true);
    } else {
      setbeforeColor('red');
      setResult('请输入完整数据库信息');
      setMsg('请输入完整数据库信息');
    }
  };

  const findCheck = aa => {
    let obj = form.getFieldsValue();
    CheckDatabaseIsExist({ ...obj, password: Encrypt(obj.password) }).then(res => {
      setCardLoading(false);
      if (res.code === 0) {
        setDataValue(form.getFieldsValue());
        if (res.data === true) {
          if (aa) {
            setbeforeColor('green');
            setResult('检测到License,当前环境需要追加产品');
            setMsg('检测到License,当前环境需要追加产品');
            setAppend('');
            setAppendVisible(true);
            setDataValue(form.getFieldsValue());
          } else {
            setbeforeColor('red');
            setPassword(false);
            setResult('无法追加,该数据库为非授权初始化数据库,请直接升级数据库! ');
            setMsg('无法追加,该数据库为非授权初始化数据库,请直接升级数据库!');
            setAppend('无需追加');
            // deleteInitDBLogNew();
          }
        } else {
          setPassword(true);
          setbeforeColor('green');
          setResult('通过');
          setMsg('');
          setAppend('无需追加');

          let arr = [];

          keepData.map(i => {
            if (keepCode.indexOf(i.name) != -1) {
              arr.push(i);
            }
          });

          onOK(arr);
        }
      } else {
        setbeforeColor('red');
        setResult(`${res.msg}`);
        setMsg(res.msg);
      }
    });
  };

  const findCheck1 = aa => {
    let obj = form.getFieldsValue();
    CheckDatabaseIsExist({ ...obj, password: Encrypt(obj.password) }).then(res => {
      setCardLoading(false);
      if (res.code === 0) {
        setDataValue(form.getFieldsValue());
        if (res.data === true) {
          if (aa) {
            setbeforeColor('green');
            setResult('检测到License,当前环境需要追加产品');
            setMsg('检测到License,当前环境需要追加产品');
            setAppend('');
            setAppendVisible(true);
            setDataValue(form.getFieldsValue());
          } else {
            setbeforeColor('red');
            setPassword(false);
            setResult('无法追加,该数据库为非授权初始化数据库,请直接升级数据库! ');
            setMsg('无法追加,该数据库为非授权初始化数据库,请直接升级数据库!');
            setAppend('无需追加');
            // deleteInitDBLogNew();
          }
        } else {
          setPassword(true);
          setbeforeColor('green');
          setResult('通过');
          setMsg('');
          setAppend('无需追加');

          let arr = [];

          keepData.map(i => {
            if (keepCode.indexOf(i.name) != -1) {
              arr.push(i);
            }
          });
        }
      } else {
        setbeforeColor('red');
        setResult(`${res.msg}`);
        setMsg(res.msg);
      }
    });
  };

  const save = () => {
    flagChange();
  };

  useEffect(() => {
    if (!initVisible && !initVisibledetail) {
      setShow('hidden');
    }
  }, [initVisible]);

  const wirthValue = () => {
    setResult('');
    setbeforeColor('gray');
    setfirstColor('gray');
    setsecordColor('gray');
    setLastColor('gray');
    setSimpleProduct('');
    setTotalProduct('');
    form.setFieldsValue(keepInline);
  };

  const simple = e => {
    let aa = 0;
    if (keepValue && keepValue[e]) {
      aa = keepValue[e].length;
    }
    return aa;
  };

  const total = e => {
    let aa = 0;
    if (data && data[e]) {
      aa = data[e].length;
    }
    return aa;
  };

  const onOk = () => {
    setAppendVisible(false);
    initDatabaseProAppend();
    // GetDbChangeAppend();
  };

  const onHistory = () => {
    setHistoryVisible(true);
  };

  const columns = [
    {
      title: '授权码',
      dataIndex: 'license',
      key: 'license',
    },
    {
      title: '项目名',
      dataIndex: 'projectName',
      key: 'projectName',
    },
    {
      title: '授权人',
      dataIndex: 'applicantName',
      key: 'applicantName',
    },
    {
      title: '使用时间',
      dataIndex: 'createTime',
      key: 'createTime',
    },
    {
      title: '部署产品',
      dataIndex: 'productSolutions',
      key: 'productSolutions',
      render: text => {
        let aa = [];
        if (text) {
          text.map(i => {
            aa.push(i.name);
          });
          return (
            <Tooltip title={aa.toString()} arrowPointAtCenter placement="rightTop">
              <span>{text.length}个</span>
            </Tooltip>
          );
        }
      },
    },
  ];

  useEffect(() => {
    if (!initVisibledetail && !initVisible) {
      deleteInitDBLogNew();
    }
  }, [initVisibledetail, initVisible]);

  return (
    <>
      <PageContainer className={styles.InitDataBaseContainer}>
        <div style={{ display: 'flex', alignItems: 'center', width: '100%' }}>
          <div style={{ width: '30%' }}>
            <Card>
              <div style={{ height: 'calc(100vh - 101px)', paddingTop: '13px' }}>
                <Form
                  className={styles.mgTop20}
                  layout="horizontal"
                  labelAlign="left"
                  labelCol={{ span: 6 }}
                  form={form}
                  onValuesChange={onValuesChange}
                >
                  <Form.Item
                    label={`${formLables.ip}:`}
                    name="ip"
                    rules={[
                      {
                        validator: (rule, value) => {
                          let regCn = /^((2[0-4]\d|25[0-5]|[01]?\d\d?)\.){3}(2[0-4]\d|25[0-5]|[01]?\d\d?)$/;
                          if (form.getFieldValue().ip == '') {
                            return Promise.reject('ip必填');
                          }
                          if (!regCn.test(form.getFieldValue().ip)) {
                            return Promise.reject('ip格式不正确');
                          }
                          setbeforeColor('gray');
                          setfirstColor('gray');
                          setsecordColor('gray');
                          setLastColor('gray');
                          setSimpleProduct('');
                          setTotalProduct('');
                          setResult('');
                          return Promise.resolve();
                        },
                      },
                    ]}
                  >
                    <Input placeholder="请输入服务器名或IP地址" />
                  </Form.Item>
                  <Form.Item
                    label={`${formLables.userName}:`}
                    name="userName"
                    rules={[
                      {
                        validator: (rule, value) => {
                          if (form.getFieldValue().userName == '') {
                            return Promise.reject('用户名称必填');
                          }
                          setbeforeColor('gray');
                          setfirstColor('gray');
                          setsecordColor('gray');
                          setLastColor('gray');
                          setSimpleProduct('');
                          setTotalProduct('');
                          setResult('');
                          return Promise.resolve();
                        },
                      },
                    ]}
                  >
                    <Input placeholder="请输入用户名称" />
                  </Form.Item>
                  <Form.Item
                    label={`${formLables.password}:`}
                    name="password"
                    rules={[
                      {
                        validator: (rule, value) => {
                          if (form.getFieldValue().password == '') {
                            return Promise.reject('用户密码必填');
                          }
                          setbeforeColor('gray');
                          setfirstColor('gray');
                          setsecordColor('gray');
                          setLastColor('gray');
                          setSimpleProduct('');
                          setTotalProduct('');
                          setResult('');
                          return Promise.resolve();
                        },
                      },
                    ]}
                  >
                    <Input placeholder="请输入用户密码" type="password" />
                  </Form.Item>
                  <Form.Item
                    label={`${formLables.dbName}:`}
                    name="dbName"
                    rules={[
                      {
                        validator: (rule, value) => {
                          if (
                            form.getFieldValue().dbName == '' ||
                            form.getFieldValue().dbName == undefined
                          ) {
                            return Promise.reject('数据库名称必填');
                          }
                          setbeforeColor('gray');
                          setfirstColor('gray');
                          setsecordColor('gray');
                          setLastColor('gray');
                          setSimpleProduct('');
                          setTotalProduct('');
                          setResult('');
                          return Promise.resolve();
                        },
                      },
                    ]}
                  >
                    <Input placeholder="请输入数据库名称" />
                  </Form.Item>
                </Form>
                <div style={{ float: 'right' }}>
                  <Button onClick={save}>环境检查</Button>
                </div>
                <div style={{ marginTop: '100px', transform: 'scal(1.5)' }}>
                  <Timeline>
                    <Timeline.Item color={beforeColor}>
                      环境检查
                      {(() => {
                        switch (result) {
                          case '':
                            return <></>;
                          case '通过':
                            return (
                              <CheckCircleOutlined style={{ color: 'green', marginLeft: '10px' }} />
                            );
                          case '检测到License,当前环境需要追加产品':
                            return (
                              <>
                                <CheckCircleOutlined
                                  style={{ color: 'green', marginLeft: '10px' }}
                                />
                                <span style={{ color: 'rgb(24 144 255)', marginLeft: '5px' }}>
                                  {result}
                                </span>
                              </>
                            );
                          default:
                            return (
                              <>
                                <CloseCircleOutlined style={{ color: 'red', marginLeft: '10px' }} />
                                <span style={{ color: 'rgb(24 144 255)', marginLeft: '5px' }}>
                                  {result}
                                </span>
                              </>
                            );
                        }
                      })()}
                    </Timeline.Item>
                    <Timeline.Item color={firstColor}>
                      <span>数据库初始化</span>
                      {(() => {
                        switch (firstColor) {
                          case 'gray':
                            return <></>;
                          case 'green':
                            return (
                              <>
                                <CheckCircleOutlined
                                  style={{ color: 'green', marginLeft: '10px' }}
                                />
                                <Tooltip title="查看初始化日志">
                                  <ZoomInOutlined
                                    style={{ color: 'rgb(24 144 255)', marginLeft: '10px' }}
                                    onClick={() => setKeepInitVisible(true)}
                                  />
                                </Tooltip>
                              </>
                            );
                          default:
                            return (
                              <>
                                <CloseCircleOutlined style={{ color: 'red', marginLeft: '10px' }} />
                                <span style={{ color: 'rgb(24 144 255)', marginLeft: '5px' }}>
                                  {dataResult}
                                </span>
                              </>
                            );
                        }
                      })()}
                    </Timeline.Item>
                    <Timeline.Item color={secordColor}>
                      <span>产品授权开启已初始化产品</span>
                      {(() => {
                        switch (secordColor) {
                          case 'gray':
                            return <></>;
                          case 'green':
                            return (
                              <>
                                <CheckCircleOutlined
                                  style={{ color: 'green', marginLeft: '10px' }}
                                />
                                <p>
                                  已开启
                                  <span style={{ color: 'rgb(24 144 255)' }}>{simpleProduct}</span>/
                                  <span style={{ color: 'rgb(24 144 255)' }}>{totalProduct}</span>
                                  个产品
                                </p>
                              </>
                            );
                          case '#eda625':
                            return (
                              <>
                                <ExclamationCircleOutlined
                                  style={{ color: '#eda625', marginLeft: '10px' }}
                                />
                                <span style={{ color: 'rgb(24 144 255)', marginLeft: '10px' }}>
                                  {productResult}
                                </span>
                                <p>
                                  已开启
                                  <span style={{ color: 'rgb(24 144 255)' }}>{simpleProduct}</span>/
                                  <span style={{ color: 'rgb(24 144 255)' }}>{totalProduct}</span>
                                  个产品
                                </p>
                              </>
                            );
                          default:
                            return <></>;
                        }
                      })()}
                    </Timeline.Item>
                    <Timeline.Item color={lastColor}>
                      <span>平台管理员赋权使用</span>
                      {(() => {
                        switch (lastColor) {
                          case 'gray':
                            return <></>;
                          case 'green':
                            return (
                              <>
                                <CheckCircleOutlined
                                  style={{ color: 'green', marginLeft: '10px' }}
                                />
                                <br />
                                <spsn>登录名:panda</spsn>
                                <br />
                                {password ? <span>初始密码:panda666</span> : <></>}
                              </>
                            );
                          default:
                            return (
                              <>
                                <CloseCircleOutlined style={{ color: 'red', marginLeft: '10px' }} />
                                <span style={{ color: 'rgb(24 144 255)', marginLeft: '5px' }}>
                                  {keepLast}
                                </span>
                              </>
                            );
                        }
                      })()}
                    </Timeline.Item>
                  </Timeline>
                </div>
              </div>
            </Card>
          </div>
          <div style={{ width: '70%' }}>
            <Card className={styles.mgTop20}>
              <div
                style={{
                  height: '50px',
                  display: 'flex',
                  justifyContent: 'space-between',
                  alignItems: 'center',
                  // color: 'rgb(137 67 67 / 85%)',
                }}
              >
                <div style={{ display: 'inline-block', backgroundColor: 'aliceblue' }}>
                  {keepHistroy.length > 0 ? (
                    <Tooltip title="查看数据库授权记录">
                      <EyeOutlined
                        style={{ color: 'rgb(24 144 255)', marginRight: '5px' }}
                        onClick={onHistory}
                      />
                    </Tooltip>
                  ) : (
                    <></>
                  )}
                  <BarcodeOutlined style={{ color: 'rgb(227 168 96)', marginRight: '5px' }} />
                  授权码:
                  {keepNumber ? (
                    <>{keepNumber}</>
                  ) : (
                    <span>
                      --
                      {/* <EditOutlined
                        style={{ color: 'rgb(24 144 255)', marginLeft: '20px', marginTop: '10px' }}
                        onClick={}
                      /> */}
                    </span>
                  )}
                </div>
                <div style={{ display: 'inline-block', backgroundColor: 'aliceblue' }}>
                  <CalendarOutlined style={{ color: '#8466cb', marginRight: '5px' }} />
                  项目名:{keepMsg ? <>{keepMsg}</> : '--'}
                </div>
                <div style={{ display: 'inline-block', backgroundColor: 'aliceblue' }}>
                  <UserOutlined style={{ color: 'green', marginRight: '5px' }} />
                  授权人:{keepNa ? <>{keepNa}</> : '-'}
                  {keepCo ? <>({keepCo})</> : '-'}
                </div>
                <div style={{ display: 'inline-block', backgroundColor: 'aliceblue' }}>
                  <div style={{ float: 'right' }}>
                    (已选
                    <span style={{ color: 'rgb(24 144 255)' }}>{keepProduct.length}</span>/
                    <span style={{ color: 'rgb(24 144 255)' }}>{allLength}</span>个产品)
                  </div>
                </div>
              </div>
              <Spin tip="loading..." spinning={cardLoading}>
                <div className={styles1.initItemData}>
                  {title &&
                    title.map((item, index) => (
                      <div key={index} style={{ marginBottom: '10px' }}>
                        <Divider
                          orientation="center"
                          style={{
                            margin: '0 0 20px 0',
                            color: '#15428b',
                            borderTopColor: '#99bbe8',
                          }}
                        >
                          {`${item}(${simple(item)}/${total(item)})`}
                        </Divider>
                        {data[item] &&
                          data[item].map((i, j) => {
                            if (keepProduct.indexOf(i) != -1) {
                              if (keepStatus.indexOf(i) != -1) {
                                return (
                                  <span
                                    style={{
                                      width: '250px',
                                      marginLeft: '24px',
                                      display: 'inline-block',
                                      marginBottom: '20px',
                                    }}
                                  >
                                    <CheckOutlined style={{ color: 'green', marginRight: '5px' }} />
                                    {i}
                                  </span>
                                );
                              } else {
                                return (
                                  <span
                                    style={{
                                      width: '250px',
                                      marginLeft: '24px',
                                      display: 'inline-block',
                                      marginBottom: '20px',
                                    }}
                                  >
                                    <PlusOutlined
                                      style={{ color: 'rgb(24, 144, 255)', marginRight: '5px' }}
                                    />
                                    {i}
                                  </span>
                                );
                              }
                            } else {
                              return (
                                <span
                                  style={{
                                    width: '250px',
                                    marginLeft: '24px',
                                    display: 'inline-block',
                                    marginBottom: '20px',
                                    color: '#c3c3c3',
                                  }}
                                >
                                  {/* <MinusSquareOutlined
                                    style={{ color: 'gray', marginTop: '-6px', marginRight: '5px' }}
                                  /> */}
                                  {i}
                                </span>
                              );
                            }
                          })}
                      </div>
                    ))}
                </div>
              </Spin>
              <div>
                <Space size="large" className={styles.btnBox}>
                  {/* {append == '' ? (
                    <Button onClick={() => setAppendVisible(true)}>追加</Button>
                  ) : (
                    <></>
                  )} */}
                  <Popconfirm
                    placement="topLeft"
                    disabled={msg != ''}
                    title={<span style={{ color: 'rgb(24 144 255)' }}>是否确认初始化!</span>}
                    okText="确认"
                    cancelText="取消"
                    onConfirm={() => {
                      Submit();
                      // deleteInitDBLogNew();
                    }}
                  >
                    <Button type="primary" disabled={msg != ''}>
                      初始化
                    </Button>
                    {/* <Button type="primary" disabled={isAuthorize && msg == '' ? false : true}>
                      初始化
                    </Button> */}
                  </Popconfirm>
                </Space>
              </div>
            </Card>
          </div>
        </div>
        <Modal
          title="初始化数据库"
          visible={initVisible}
          onCancel={() => {
            setInitVisible(false);
            setInitContent('');
            setInitContentdetail('');
            // deleteInitDBLogNew();
          }}
          width={800}
          maskClosable={false}
          bodyStyle={{
            height: '500px',
            // overflowY: 'scroll',
          }}
          footer={[
            <Button
              style={{ visibility: show }}
              onClick={() => {
                handlelook();
              }}
            >
              查看详细信息
            </Button>,
            <Button
              onClick={() => {
                handleClick();
              }}
              key="back"
              type="primary"
              loading={initLoading}
            >
              关闭窗口
            </Button>,
          ]}
        >
          <div
            ref={scroll}
            style={{
              height: '470px',
              overflowY: 'scroll',
              marginRight: ' -24px',
            }}
          >
            <Spin
              spinning={initLoading}
              tip="loading..."
              style={{ width: '100%', marginTop: '40px' }}
            >
              <span>{initContent}</span>
              <div style={{ height: '40px' }}>
                <div style={{ position: 'relative' }}>
                  {/* {initLoading ? <span>加载中...</span> : <></>} */}
                  {/* <Spin
                  spinning={initLoading}
                  tip="loading..."
                  style={{ width: '100%', marginTop: '40px' }}
                /> */}
                </div>
              </div>
              {/* <br />
            {showDetali ? <span>{initContentdetail}</span> : <></>} */}
            </Spin>
          </div>
        </Modal>
        <Modal
          title="日志信息"
          visible={keepinitVisible}
          onCancel={() => {
            setKeepInitVisible(false);
            // setKeepInitContent('');
          }}
          width={800}
          maskClosable={false}
          bodyStyle={{
            height: '500px',
          }}
          footer={[
            <Button
              onClick={() => {
                setKeepInitDetailVisible(true);
                setKeepInitVisible(false);
              }}
            >
              查看详细日志
            </Button>,
            <Button
              onClick={() => {
                setKeepInitVisible(false);
              }}
              key="back"
              type="primary"
            >
              关闭窗口
            </Button>,
          ]}
        >
          <div
            ref={scroll}
            style={{
              maxHeight: '470px',
              overflowY: 'auto',
              marginRight: ' -24px',
            }}
          >
            {keepInitContent}
          </div>
        </Modal>
        <Modal
          title="详细日志信息"
          visible={keepInitDetailVisible}
          onCancel={() => {
            setKeepInitDetailVisible(false);
          }}
          width={800}
          maskClosable={false}
          bodyStyle={{
            height: '500px',
          }}
          footer={[
            <Button
              onClick={() => {
                setKeepInitDetailVisible(false);
                setKeepInitVisible(true);
              }}
            >
              查看日志
            </Button>,
            <Button
              onClick={() => {
                setKeepInitDetailVisible(false);
              }}
              key="back"
              type="primary"
            >
              关闭窗口
            </Button>,
          ]}
        >
          <div
            ref={scroll}
            style={{
              maxHeight: '470px',
              overflowY: 'auto',
              marginRight: ' -24px',
            }}
          >
            {keepInitContentDetail}
          </div>
        </Modal>

        <AppendModal
          visible={appendVisible}
          onCancel={() => {
            setAppendVisible(false);
          }}
          value={dataValue}
          callBackSubmit={onOk}
          keepHistroy={keepHistroy}
        />
        <Modal
          title="数据库授权记录"
          visible={historyVisible}
          onCancel={() => {
            setHistoryVisible(false);
          }}
          width={1000}
          bodyStyle={{
            height: '500px',
            overflowY: 'scroll',
          }}
          footer={[
            <Button
              onClick={() => {
                setHistoryVisible(false);
              }}
              key="back"
            >
              关闭
            </Button>,
          ]}
        >
          <Table
            size="small"
            rowKey={record => record.userID}
            bordered
            columns={columns}
            dataSource={keepHistroy}
            pagination={false}
            scroll={{ x: 'max-content' }}
          />
        </Modal>
        <Modal
          title="初始化数据库详细日志"
          visible={initVisibledetail}
          onCancel={() => {
            setinitVisibledetail(false);
            setInitContentdetail('');
          }}
          width={800}
          maskClosable={false}
          bodyStyle={{
            height: '500px',
            // overflowY: 'auto',
          }}
          footer={[
            <Button
              onClick={() => {
                setInitVisible(true);
                setinitVisibledetail(false);
              }}
            >
              查看初始化日志
            </Button>,
            <Button
              onClick={() => {
                handleClickdetail();
              }}
              key="back"
              type="primary"
            >
              关闭窗口
            </Button>,
          ]}
        >
          <div
            ref={scroll}
            style={{
              maxHeight: '470px',
              overflowY: 'auto',
              marginRight: ' -24px',
            }}
          >
            {initContentdetail || (
              <Spin tip="loading..." style={{ width: '100%', marginTop: '40px' }} />
            )}
          </div>
        </Modal>
      </PageContainer>
    </>
  );
};

export default connect()(DatabaseInitialization);