/* eslint-disable indent */
/* eslint-disable guard-for-in */
/* eslint-disable no-restricted-syntax */
import React, { useEffect, useState } from 'react';
import { Button, Space, notification, Modal, Popconfirm, Empty, Spin, Tooltip } from 'antd';
import {
  BarcodeOutlined,
  UserOutlined,
  CalendarOutlined,
  PlusOutlined,
  CheckOutlined,
} from '@ant-design/icons';
import CryptoJS from 'crypto-js';
import styles from './DatabaseInitialization.less';
import { GetLicenseDifference, InitEditDataBase, GetProductList } from '@/services/database/api';
import New from '../../../assets/images/icons/new.png';

const AppendModal = props => {
  const { callBackSubmit = () => {}, visible, onCancel, value, keepHistroy, appendType } = props;
  const [data, setData] = useState([]);
  const [allLength, setAllLength] = useState('');
  const [flag, setFlag] = useState();
  const [loading, setLoading] = useState(false);
  const [code, setCode] = useState('');
  const [project, setProject] = useState('');
  const [name, setName] = useState('');
  const [number, setNumber] = useState('');
  const [much, setMuch] = useState([]);
  const [code1, setCode1] = useState('');
  const [project1, setProject1] = useState('');
  const [name1, setName1] = useState('');
  const [number1, setNumber1] = useState('');
  const [allValue, setAllValue] = useState([]);
  const [keepData, setKeepData] = useState([]);

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

  useEffect(() => {
    if (visible) {
      getProduct();
      let aa = [];
      keepHistroy.map((i, j) => {
        if (i.license !== '已使用' && j !== keepHistroy.length - 1) {
          aa.push(i);
        }
      });
      if (aa.length > 0) {
        let a = [];
        let b = [];
        let c = [];
        aa.map(k => {
          a.push(k.license);
          b.push(k.projectName);
          c.push(`${k.applicantName}（${k.jobNumber}）`);
        });
        setCode1(a.toString());
        setProject1(b.toString());
        setName1(c.toString());
      }
      setMuch(aa);
      setCode(keepHistroy[keepHistroy.length - 1].license);
      setProject(keepHistroy[keepHistroy.length - 1].projectName);
      setName(keepHistroy[keepHistroy.length - 1].applicantName);
      setNumber(keepHistroy[keepHistroy.length - 1].jobNumber);
    } else {
      setData([]);
      setFlag();
      setAllLength('');
    }
  }, [visible]);

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

  // 加密
  const Encrypt = word => {
    let srcs = CryptoJS.enc.Utf8.parse(word);
    let encrypted = CryptoJS.AES.encrypt(srcs, key, {
      iv,
      mode: CryptoJS.mode.CBC,
      padding: CryptoJS.pad.Pkcs7,
    });
    return encrypted.ciphertext.toString().toUpperCase();
  };

  const getProduct = () => {
    setLoading(true);
    let pwd =
      Decrypt(value.password) === '' || Decrypt(value.password).indexOf('\u0004') !== -1
        ? Encrypt(value.password)
        : value.password;
    GetLicenseDifference({ ...value, password: pwd }).then(res => {
      setLoading(false);
      if (res.code === 0) {
        setKeepData(res.data);
        let aab = [];
        res.data.map(k => {
          if (k.status == 0) {
            aab.push(k.name);
          }
        });
        setAllValue(aab);
        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;
        });
        setData(arr);
        if (res.data.length == 0) {
          setFlag(1);
        } else {
          setFlag(0);
        }
        setAllLength(res.data.length);
      } else {
        notification.error({
          message: '提示',
          duration: 3,
          description: res.msg,
        });
      }
    });
  };

  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 Submit = () => {
    if (allValue.length > 0) {
      callBackSubmit();
    }
  };

  const title = e => {
    let aa = [];
    data[e].map(i => {
      if (allValue.indexOf(i) != -1) {
        aa.push(i);
      }
    });
    return aa.length;
  };

  const title1 = () => {
    if (allValue.length == 0) {
      return <span style={{ color: 'red' }}>license下产品已全被初始化，无需再次追加！！！</span>;
    }
    return (
      <span style={{ color: 'rgb(24 144 255)' }}>
        {appendType === 'yes' ? (
          <div style={{ width: '150px' }}>
            当前数据库为非授权初始化数据库，是否使用授权码升级到授权码模式？
          </div>
        ) : (
          '是否确认追加！'
        )}
      </span>
    );
  };

  return (
    <Modal
      title="产品追加"
      width="1000px"
      visible={visible}
      onCancel={onCancel}
      destroyOnClose
      maskClosable={false}
      bodyStyle={{
        height: '500px',
        overflowY: 'scroll',
      }}
      footer={
        <Space>
          <Button onClick={onCancel}>取消</Button>
          <Popconfirm
            placement="topLeft"
            title={title1}
            okText="确认"
            cancelText="取消"
            onConfirm={() => {
              Submit();
            }}
          >
            <Button type="primary">追加</Button>
          </Popconfirm>
        </Space>
      }
    >
      <Spin spinning={loading}>
        {flag === 1 ? (
          <Empty
            image={Empty.PRESENTED_IMAGE_SIMPLE}
            description={<span>当前授权码下产品已全部初始化，无需再次追加</span>}
          />
        ) : (
          <>
            {allLength > 0 && (
              <div
                style={{
                  height: '50px',
                  display: 'flex',
                  justifyContent: 'space-between',
                  alignItems: 'center',
                  marginBottom: '15px',
                }}
              >
                {much.length > 0 ? (
                  <Tooltip title={code1}>
                    <div style={{ display: 'inline-block', backgroundColor: 'aliceblue' }}>
                      <BarcodeOutlined style={{ color: 'rgb(227 168 96)', marginRight: '5px' }} />
                      授权码：
                      {code ? <>{code}</> : <span>--</span>}
                      <span>...</span>
                    </div>
                  </Tooltip>
                ) : (
                  <div style={{ display: 'inline-block', backgroundColor: 'aliceblue' }}>
                    <BarcodeOutlined style={{ color: 'rgb(227 168 96)', marginRight: '5px' }} />
                    授权码：
                    {code ? <>{code}</> : <span>--</span>}
                  </div>
                )}
                {much.length > 0 ? (
                  <Tooltip title={project1}>
                    <div style={{ display: 'inline-block', backgroundColor: 'aliceblue' }}>
                      <CalendarOutlined style={{ color: '#8466cb', marginRight: '5px' }} />
                      项目名：{project ? <>{project}</> : '--'}
                      <span>...</span>
                    </div>
                  </Tooltip>
                ) : (
                  <div style={{ display: 'inline-block', backgroundColor: 'aliceblue' }}>
                    <CalendarOutlined style={{ color: '#8466cb', marginRight: '5px' }} />
                    项目名：{project ? <>{project}</> : '--'}
                  </div>
                )}
                {much.length > 0 ? (
                  <Tooltip title={name1}>
                    <div style={{ display: 'inline-block', backgroundColor: 'aliceblue' }}>
                      <UserOutlined style={{ color: 'green', marginRight: '5px' }} />
                      授权人：{name ? <>{name}</> : '-'}
                      {number ? <>（{number}）</> : '-'}
                      {much.length > 0 ? <span>...</span> : <></>}
                    </div>
                  </Tooltip>
                ) : (
                  <div style={{ display: 'inline-block', backgroundColor: 'aliceblue' }}>
                    <UserOutlined style={{ color: 'green', marginRight: '5px' }} />
                    授权人：{name ? <>{name}</> : '-'}
                    {number ? <>（{number}）</> : '-'}
                  </div>
                )}
                <div style={{ display: 'inline-block', backgroundColor: 'aliceblue' }}>
                  <div style={{ float: 'right' }}>
                    <strong>
                      追加产品列表（共
                      <span style={{ color: 'rgb(24 144 255)' }}>
                        {allValue && allValue.length > 0 ? allValue.length : 0}
                      </span>
                      <span>/</span>
                      <span style={{ color: 'rgb(24 144 255)' }}>{allLength}</span>
                      个）
                    </strong>
                  </div>
                </div>
              </div>
            )}
            {data &&
              Object.keys(data).map((i, j) => (
                <div
                  style={{
                    border: '2px solid #c2cdfd',
                    borderRadius: '5px',
                    marginBottom: '20px',
                    position: 'relative',
                    paddingTop: '30px',
                  }}
                >
                  <div
                    style={{
                      position: 'absolute',
                      left: '13px',
                      top: '-12px',
                      backgroundColor: 'white',
                      paddingLeft: '10px',
                      paddingRight: '10px',
                    }}
                  >
                    <>
                      <span>{i}</span>
                      <span>
                        (共
                        <span style={{ color: 'rgb(24, 144, 255)' }}>{title(i)}</span>
                        <span>/</span>
                        <span style={{ color: 'rgb(24, 144, 255)' }}>{data[i].length}</span>个)
                      </span>
                    </>
                  </div>
                  {data[i].map(j => (
                    <span
                      style={{
                        width: '150px',
                        marginLeft: '24px',
                        display: 'inline-block',
                        marginBottom: '20px',
                      }}
                    >
                      {allValue.indexOf(j) !== -1 ? (
                        <span>
                          {keepData.length > 0 &&
                            keepData.find(item => item.name === j).version !== 2022 && (
                              <img
                                src={New}
                                style={{
                                  height: '24px',
                                  marginTop: '-12px',
                                  marginRight: '3px',
                                }}
                                alt=""
                              />
                            )}
                          <PlusOutlined
                            style={{ color: 'rgb(24, 144, 255)', marginRight: '5px' }}
                          />
                          {j}
                        </span>
                      ) : (
                        <span>
                          {keepData.length > 0 &&
                            keepData.find(item => item.name === j).version !== 2022 && (
                              <img
                                src={New}
                                style={{
                                  height: '24px',
                                  marginTop: '-12px',
                                  marginRight: '3px',
                                }}
                                alt=""
                              />
                            )}
                          <CheckOutlined style={{ color: 'green', marginRight: '5px' }} />
                          {j}
                        </span>
                      )}
                    </span>
                  ))}
                </div>
              ))}
          </>
        )}
      </Spin>
    </Modal>
  );
};
export default AppendModal;
