/* 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,
} from 'antd';
import PageContainer from '@/components/BasePageContainer';
import { connect } from 'react-redux';
import {
  setTableSQLDirName,
  deleteConnNew,
  initDBv4new,
  getInitDBLogNew,
  getConnRecordNew,
  getDataBaseConfigNew,
  saveConnectionNew,
  getDataBaseList,
  updateConnDescNew,
  deleteInitDBLogNew,
  connectionTest,
  GetProductList, // 获取产品列表
  GetDbProduct, // 获取产品方案配置
  InitAddDataBase, // 数据库初始化
  InitEditDataBase, // 二次初始化
  CheckConnection,
  SetAdminMenuToRole,
  CheckDatabaseIsExist,
  NewInitAddDataBase,
} from '@/services/database/api';
import {
  CloseCircleOutlined,
  CheckCircleOutlined,
  ZoomInOutlined,
  ExclamationCircleOutlined,
  BarcodeOutlined,
  UserOutlined,
  CalendarOutlined,
} from '@ant-design/icons';
import styles from './DatabaseInitialization.less';
import styles1 from '../InitDataBase/InitDataBase.less';

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 [dbExists, setDbExists] = useState(false); // 数据库是否存在
  const [keepDb, setKeepDb] = useState([]);
  const [keepProduct, setKeepProduct] = useState([]);
  const scroll = useRef(null);

  const [data, setData] = useState([]);
  const [title, setTitle] = useState([]);
  const [keepCode, setKeepCode] = useState([]);
  const [keepData, setKeepData] = useState([]);
  const [checkboxFlag, setCheckboxFlag] = useState(0);
  const [keepValue, setKeepValue] = useState([]);
  const [value, setValue] = useState([]);
  const [product, setProduct] = useState([]);
  const [msg, setMsg] = useState('');
  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 [keepinitVisible, setKeepInitVisible] = useState(false);
  const [password, setPassword] = useState(false);
  const [isAuthorize, setIsAuthorize] = useState(false);
  const [licen, setLicen] = useState('');
  const [showDetali, setShowDetali] = useState(false);

  // 获取数据库配置信息
  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) {
        console.log(res.data);
        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);
        console.log(arr);
        console.log(aa);
        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 => {
        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);
            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 => {
    GetDbProduct().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) {
          setkeepNumber(res.data.Project[0].license);
          setkeepMsg(res.data.Project[0].projectName);
          setkeepNa(res.data.Project[0].applicantName);
          setkeepCo(res.data.Project[0].jobNumber);
        } else {
          setkeepNumber('');
          setkeepMsg('');
          setkeepNa('');
          setkeepCo('');
        }
        if (!res.data.IsAuthorize) {
          form.setFieldsValue(res.data.DbInfo);
        }
        // 有License的情况下首次进入展示数据
        // if (res.data.IsAuthorize) {
        if (res.data.Product) {
          let aa = [];
          res.data.Product.map(i => {
            aa.push(i.name);
          });
          if (res.data.IsAuthorize) {
            setCheckboxFlag(1);
          } else {
            setCheckboxFlag(0);
          }
          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);
          }
          let newArr = Array.from(new Set(aa));
          setKeepProduct(newArr);
          setKeepCode(newArr);
          setValue(newArr);
        }
        setDbExists(res.data.DBExists);
        setKeepDb(res.data);
        setIsAuthorize(res.data.IsAuthorize);
        if (res.data.IsAuthorize) {
          setMsg('');
        } else {
          if (res.data.Project && res.data.Project[0]) {
            setbeforeColor('red');
            setResult('检测到License已被使用');
            setMsg('检测到License已被使用');
          } else {
            setbeforeColor('red');
            setResult('未检测到License');
            setMsg('未检测到License');
          }
        }
        // if (res.data.DBExists) {
        //   setCheckboxFlag(1);
        //   setMsg('当前数据库已存在不可初始化');
        //   notification.error({
        //     message: '提示',
        //     duration: 3,
        //     description: '当前数据库已存在不可初始化',
        //   });
        // } else if (!res.data.DBExists && !res.data.Project[0]) {
        //   setCheckboxFlag(0);
        //   setMsg('');
        //   notification.warning({
        //     message: '提示',
        //     duration: 3,
        //     description: '未检测到License，自主选择产品进行数据库初始化',
        //   });
        // } else if (!res.data.DBExists && res.data.Project[0]) {
        //   setCheckboxFlag(1);
        //   notification.success({
        //     message: '提示',
        //     duration: 3,
        //     description: '已检测到License，需初始化数据库',
        //   });
        //   setMsg('');
        // }
      } else {
        notification.error({
          message: '提示',
          duration: 3,
          description: res.msg,
        });
      }
    });
  };

  const GetDbChange = e => {
    let obj = form.getFieldsValue();
    setCardLoading(true);
    GetDbProduct({ ...obj }).then(res => {
      setCardLoading(false);
      if (res.code === 0) {
        if (res.data.IsAuthorize) {
          // setMsg('');
          if (e) {
            findCheck();
          } else {
            onCheckLaster();
          }
        } else {
          if (res.data.Project && res.data.Project[0]) {
            setbeforeColor('red');
            setResult('检测到License已被使用');
            setMsg('检测到License已被使用');
          } else {
            setbeforeColor('red');
            setResult('未检测到License');
            setMsg('未检测到License');
          }
        }
        if (res.data.Project && res.data.Project.length > 0) {
          setkeepNumber(res.data.Project[0].license);
          setkeepMsg(res.data.Project[0].projectName);
          setkeepNa(res.data.Project[0].applicantName);
          setkeepCo(res.data.Project[0].jobNumber);
        } else {
          setkeepNumber('');
          setkeepMsg('');
          setkeepNa('');
          setkeepCo('');
        }
        if (res.data.Product) {
          let aa = [];
          res.data.Product.map(i => {
            aa.push(i.name);
          });
          console.log(aa);
          // if (res.data.IsAuthorize || res.data.DBExists) {
          //   setCheckboxFlag(1);
          // } else {
          //   setCheckboxFlag(0);
          // }
          // console.log(aa);
          if (aa.length > 0) {
            let dd = [];
            aa.map(i => {
              keepData.map(j => {
                if (j.name === i) {
                  dd.push(j);
                }
              });
            });
            console.log(dd);
            let Arr = Array.from(new Set(dd));
            console.log(Arr);
            let arr = formateArrDataA(Arr, 'productName');
            console.log(arr);
            let a = Object.keys(arr);
            console.log(a);
            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));
          console.log(aa);
          // 当前数据库已存在和上一个已存在数据库值重新赋值
          if (newArr.length > 0 || dbExists) {
            setKeepProduct(newArr);
            setKeepCode(newArr);
            setValue(newArr);
          }
          if (res.data.Product.length == 0) {
            setKeepValue([]);
          }
        }
        setDbExists(res.data.DBExists);
        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();
    // if (dbExists) {
    //   InitEditDataBase({ ...obj, productSetting, license: j }).then(res => {
    //     setInitLoading(false);
    //     if (res.code === 0) {
    //       setfirstColor('green');
    //       setsecordColor('green');
    //       SetAdminMenuToRole().then(resdata => {
    //         if (resdata.code === 0) {
    //           setLastColor('green');
    //         }
    //       });

    //       notification.success({
    //         message: '提示',
    //         duration: 5,
    //         description: '数据库初始化成功',
    //       });
    //     } else {
    //       setfirstColor('red');
    //       setsecordColor('gray');
    //       setLastColor('gray');
    //       notification.error({
    //         message: '提示',
    //         duration: 5,
    //         description: res.msg,
    //       });
    //     }
    //   });
    //   return;
    // }
    NewInitAddDataBase({ ...obj, productSetting }).then(res => {
      if (res.code === 0) {
        if (value.length > 0) {
          setKeepProduct(value);
        }
        // setMsg('当前数据库已存在不可初始化');
        setbeforeColor('red');
        setResult('检测到License已被使用');
        setMsg('检测到License已被使用');
        setCheckboxFlag(1);
        setfirstColor('green');

        SetAdminMenuToRole().then(resdata => {
          if (resdata.code === 0) {
            setLastColor('green');
          }
        });
        setDataResult('成功');
        notification.success({
          message: '提示',
          duration: 3,
          description: '数据库初始化成功',
        });
        setDbExists(true);
        if (keepNumber != '') {
          setkeepNumber('已使用');
        }
        // setkeepNa('');
        // setkeepMsg('');
        // setkeepCo('');
        if (res.data.productPackageCount == 0) {
          console.log(1212);
          setProductResult('产品授权不包含已初始化的产品');
          setsecordColor('#eda625');
        } else {
          setsecordColor('green');
        }
        setTotalProduct(res.data.productPackageSumCount);
        setSimpleProduct(res.data.productPackageCount);
      } 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('');
    // console.log(keepNumber);
    // if (keepNumber == '') {
    //   setKeepValue([]);
    // }

    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);
      // 已经被初始化的产品不允许取消勾选
      // if (arr && bb != -1) {
      //   console.log(arr);
      // } else {
      let aa = keepValue;
      aa[item] = e;
      let a = Object.keys(aa);
      let list = [];
      a.map(i => {
        aa[i].map(j => {
          list.push(j);
        });
      });
      console.log(aa);
      setKeepValue(aa);
      console.log(list);
      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);
        });
      });
      console.log(aa);
      console.log(list);
      setKeepValue(aa);
      setValue(list);
    }
  };

  const onCheck = () => {
    let obj = form.getFieldsValue();
    if (obj.ip && obj.userName && obj.password && obj.dbName) {
      // setKeepValue([]);
      setProduct([]);
      GetDbChange();
      deleteInitDBLogNew();
    } else {
      setbeforeColor('red');
      setResult('请输入完整数据库信息');
      setMsg('请输入完整数据库信息');
      setCheckboxFlag(1);
    }
  };
  const onCheckLaster = () => {
    let obj = form.getFieldsValue();

    CheckDatabaseIsExist({ ...obj }).then(res => {
      setCardLoading(false);
      if (res.code == 0) {
        // 数据库不存在
        if (res.data === false) {
          setbeforeColor('green');
          setResult('通过');
          // 有授权码
          console.log(keepNumber);
          if (keepNumber && keepNumber != '已使用') {
            setCheckboxFlag(1);
            // setDbExists(false);
            setMsg('');
          } else {
            setCheckboxFlag(0);
            // setDbExists(false);
            setMsg('');
          }
          // setValue([]);
          // setKeepProduct([]);
          console.log(value);
        } else {
          setbeforeColor('red');
          setResult('当前数据库已存在');
          setCheckboxFlag(1);
          setMsg('当前数据库已存在');
        }
      } else {
        setbeforeColor('red');
        setResult(`${res.msg}`);
        setMsg(res.msg);
        setCheckboxFlag(1);
      }
    });
  };

  const Submit = () => {
    let obj = form.getFieldsValue();
    if (obj.ip && obj.userName && obj.password && obj.dbName) {
      GetDbChange(1);
      setCardLoading(true);
    } else {
      setbeforeColor('red');
      setResult('请输入完整数据库信息');
      setMsg('请输入完整数据库信息');
      setCheckboxFlag(1);
    }
  };

  const findCheck = () => {
    let obj = form.getFieldsValue();
    CheckDatabaseIsExist({ ...obj }).then(res => {
      setCardLoading(false);
      if (res.code === 0) {
        if (res.data === true) {
          setbeforeColor('red');
          setPassword(false);
          setResult('当前数据库已存在 ');
          setMsg('当前数据库已存在');

          deleteInitDBLogNew();
          setCheckboxFlag(1);
        } else {
          setPassword(true);
          setbeforeColor('green');
          setResult('通过');
          // setDbExists(false);
          setMsg('');
          if (checkboxFlag == 0 && value.length == 0) {
            notification.warning({
              message: '提示',
              duration: 3,
              description: '请勾选产品',
            });
          } else if (checkboxFlag == 1 && keepProduct.length == 0) {
            notification.warning({
              message: '提示',
              duration: 3,
              description: '请勾选产品',
            });
          } else {
            let arr = [];
            if (checkboxFlag == 0) {
              keepData.map(i => {
                if (value.indexOf(i.name) != -1) {
                  arr.push(i);
                }
              });
            } else {
              keepData.map(i => {
                if (keepCode.indexOf(i.name) != -1) {
                  arr.push(i);
                }
              });
            }
            onOK(arr);
          }
        }
      } else {
        setbeforeColor('red');
        setResult(`${res.msg}`);
        setMsg(res.msg);
        setCheckboxFlag(1);
      }
    });
  };

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

  useEffect(() => {
    if (!initVisible) {
      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;
  };

  return (
    <>
      <PageContainer className={styles.InitDataBaseContainer}>
        <div style={{ display: 'flex', alignItems: 'center', width: '100%' }}>
          <div style={{ width: '30%' }}>
            <Card>
              <div style={{ height: 'calc(100vh - 108px)', 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) => {
                          console.log(form.getFieldValue().password);
                          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) => {
                          console.log(form.getFieldValue().dbName);
                          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
                    style={{ marginRight: '20px', visibility: ifInline }}
                    onClick={wirthValue}
                  >
                    当前数据库
                  </Button> */}
                  <Button onClick={save}>环境检查</Button>
                </div>
                <div style={{ marginTop: '100px', transform: 'scal(1.5)' }}>
                  <Timeline>
                    {/* <Timeline.Item color={oldColor}>
                      License检测
                      {(() => {
                        switch (oldColor) {
                          case 'gray':
                            return <></>;
                          case 'green':
                            return (
                              <>
                                <CheckCircleOutlined
                                  style={{ color: 'green', marginLeft: '10px' }}
                                />
                              </>
                            );
                          case '#eda625':
                            return (
                              <>
                                <ExclamationCircleOutlined
                                  style={{ color: '#eda625', marginLeft: '10px' }}
                                />
                                <span style={{ color: 'rgb(24 144 255)', marginLeft: '10px' }}>
                                  {license}
                                </span>
                              </>
                            );
                          default:
                            return (
                              <>
                                <CloseCircleOutlined style={{ color: 'red', marginLeft: '10px' }} />
                                <span style={{ color: 'rgb(24 144 255)', marginLeft: '5px' }}>
                                  {license}
                                </span>
                              </>
                            );
                        }
                      })()}
                    </Timeline.Item> */}
                    <Timeline.Item color={beforeColor}>
                      环境检查
                      {(() => {
                        switch (result) {
                          case '':
                            return <></>;
                          case '通过':
                            return (
                              <CheckCircleOutlined style={{ color: 'green', marginLeft: '10px' }} />
                            );
                          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>

                      {lastColor == 'green' ? (
                        <>
                          <CheckCircleOutlined style={{ color: 'green', marginLeft: '10px' }} />
                          <br />
                          <spsn>登录名：panda</spsn>
                          <br />
                          {password ? <span>初始密码：panda666</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' }}>
                  <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' }}>
                  {checkboxFlag == 0 ? (
                    <div style={{ float: 'right' }}>
                      （已选<span style={{ color: 'rgb(24 144 255)' }}>{value.length}</span>/
                      <span style={{ color: 'rgb(24 144 255)' }}>{allLength}</span>个产品）
                    </div>
                  ) : (
                    <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>
                        {/* {checkboxFlag == 0 ? (
                          <CheckboxGroup
                            options={data[item]}
                            value={value}
                            onChange={e => onChange1(e, item)}
                          />
                        ) : (
                          <> */}
                        {data[item] &&
                          data[item].map((i, j) => {
                            if (keepProduct.indexOf(i) != -1) {
                              return <Checkbox checked={true}>{i}</Checkbox>;
                            } else {
                              return (
                                <Checkbox checked={false} disabled>
                                  {i}
                                </Checkbox>
                              );
                            }
                          })}
                        {/* </>
                        )} */}
                      </div>
                    ))}
                </div>
              </Spin>
              <div>
                <Space size="large" className={styles.btnBox}>
                  <Popconfirm
                    placement="topLeft"
                    disabled={msg == '' ? false : true}
                    title={<span style={{ color: 'rgb(24 144 255)' }}>是否确认初始化！</span>}
                    okText="确认"
                    cancelText="取消"
                    onConfirm={() => {
                      Submit();
                      deleteInitDBLogNew();
                    }}
                  >
                    <Button type="primary" disabled={msg == '' ? false : true}>
                      初始化
                    </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',
            }}
          >
            <span>{initContent}</span>
            <div style={{ height: '40px' }}>
              <div style={{ position: 'relative' }}>
                <Spin
                  spinning={initLoading}
                  tip="loading..."
                  style={{ width: '100%', marginTop: '40px' }}
                />
              </div>
            </div>
            {/* <br />
            {showDetali ? <span>{initContentdetail}</span> : <></>} */}
          </div>
        </Modal>
        <Modal
          title="日志信息"
          visible={keepinitVisible}
          onCancel={() => {
            setKeepInitVisible(false);
            // setKeepInitContent('');
          }}
          width={800}
          maskClosable={false}
          bodyStyle={{
            height: '500px',
          }}
          footer={[
            <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={initVisibledetail}
          onCancel={() => {
            setinitVisibledetail(false);
            setInitContentdetail('');
          }}
          width={900}
          maskClosable={false}
          bodyStyle={{
            height: '600px',
            // overflowY: 'auto',
          }}
          footer={[
            <Button
              onClick={() => {
                handleClickdetail();
              }}
              key="back"
            >
              关闭窗口
            </Button>,
          ]}
        >
          <div
            ref={scroll}
            style={{
              maxHeight: '560px',
              overflowY: 'auto',
              marginRight: ' -24px',
            }}
          >
            {initContentdetail || (
              <Spin tip="loading..." style={{ width: '100%', marginTop: '40px' }} />
            )}
          </div>
        </Modal>
      </PageContainer>
    </>
  );
};

export default connect()(DatabaseInitialization);
