/* eslint-disable no-else-return */
/* eslint-disable react/jsx-boolean-value */
/* eslint-disable no-lonely-if */
/* eslint-disable guard-for-in */
/* eslint-disable no-restricted-syntax */
/*
 * @Description:
 * @Author: leizhe
 * @Date: 2022-07-13 16:13:03
 * @LastEditTime: 2022-08-16 09:59:34
 * @LastEditors: leizhe
 */
import React, { useState, useEffect } from 'react';
import { Form, Modal, Divider, Checkbox, Button, Input, notification, Row, Col, Spin } from 'antd';
import {
  GetProductList,
  GetProductListByLicense,
  InitAddDataBase,
  InitEditDataBase,
  GetLicenseStatus,
} from '@/services/database/api';
import styles from './InitDataBase.less';

const CheckboxGroup = Checkbox.Group;

const InitModal = props => {
  const [form] = Form.useForm();
  const { callBackSubmit = () => {}, keepDb, visible, onCancel, keepProduct, keep } = props;
  const [data, setData] = useState([]);
  const [title, setTitle] = useState([]);
  const [listVisible, setListVisible] = useState(false);
  const [keepCode, setKeepCode] = useState([]);
  const [keepData, setKeepData] = useState([]);
  const [flag, setFlag] = useState(0);
  const [mag, setMag] = useState('');
  const [code, setCode] = useState('');
  const [checkboxFlag, setCheckboxFlag] = useState(0);
  const [keepValue, setKeepValue] = useState([]);
  const [value, setValue] = useState([]);
  const [product, setProduct] = useState([]);

  useEffect(() => {
    getProductList();
    console.log(keep);
    console.log(keepProduct);
    setFlag(0);
    setCheckboxFlag(0);
    setMag('');
    if (visible) {
      if (keep) {
        setCheckboxFlag(1);
      } else {
        setCheckboxFlag(0);
      }
      setValue(keepProduct);
      setKeepCode(keepProduct);
    } else {
      setCode('');
      setKeepCode([]);
      setValue([]);
      setKeepValue([]);
    }
  }, [visible]);

  useEffect(() => {
    form.resetFields();
  }, [listVisible]);

  const getProductList = () => {
    // GetProductList().then(res => {
    //   if (res.code === 0) {
    //     setKeepData(res.data);
    //     if (keepProduct.length > 0) {
    //       let dd = [];
    //       keepProduct.map(i => {
    //         res.data.map(j => {
    //           if (j.name === i) {
    //             dd.push(j);
    //           }
    //         });
    //       });
    //       let arr = formateArrDataA(dd, 'productName');
    //       let aa = Object.keys(arr);
    //       aa.map(i => {
    //         let list = [];
    //         arr[i].map(j => {
    //           list.push(j.name);
    //         });
    //         arr[i] = list;
    //       });
    //       console.log(arr);
    //       setProduct(arr);
    //       setKeepValue(arr);
    //     }
    //     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;
    //     });
    //     console.log(aa);
    //     console.log(arr);
    //     console.log(keepProduct);
    //     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 codeSubmit = () => {
    let obj = form.getFieldsValue();
    console.log(obj);
    let str = `${obj.License1}${obj.License2}${obj.License3}${obj.License4}${obj.License5}`;
    GetProductListByLicense({ License: str }).then(res => {
      if (res.code === 0) {
        if (res.data.length > 0) {
          let aa = [];
          res.data.map(i => {
            aa.push(i.name);
          });
          console.log(aa);
          let bb = keepProduct;
          let cc = aa.concat(bb);
          let dd = Array.from(new Set(cc));
          console.log(dd);
          GetLicenseStatus({ license: str }).then(res => {
            if (res.code === 0) {
              if (res.data == 1) {
                notification.error({
                  message: '提示',
                  duration: 5,
                  description: '激活码已被使用',
                });
              } else {
                setCheckboxFlag(checkboxFlag + 1);
                setKeepCode(dd);
                setCode(str);
                setListVisible(false);
                setFlag(flag + 1);
                setMag('');
              }
            } else {
              notification.error({
                message: '提示',
                duration: 5,
                description: res.msg,
              });
            }
          });
        } else {
          notification.error({
            message: '提示',
            duration: 5,
            description: '激活码未购买任何产品',
          });
          setMag('激活码未购买任何产品');
        }
      } else {
        notification.error({
          message: '提示',
          duration: 5,
          description: res.msg,
        });
        setMag(res.msg);
      }
    });
  };

  const onSubmit = () => {
    // console.log(mag);
    // if (mag != '' && keepProduct == keepCode && checkboxFlag != 0) {
    //   notification.error({
    //     message: '提示',
    //     duration: 5,
    //     description: '请先输入激活码激活产品',
    //   });
    // } else {
    //   if (flag !== 0 || checkboxFlag == 0) {
    //     setLoadings(true);
    //     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);
    //         }
    //       });
    //     }
    //     console.log(arr);
    //     callBackSubmit(arr, code);
    //     onCancel();
    //   } else {
    //     notification.warning({
    //       message: '提示',
    //       duration: 5,
    //       description: '请先输入激活码激活产品',
    //     });
    //   }
    // }
    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);
        }
      });
    }
    console.log(arr);
    callBackSubmit(arr, code);
    onCancel();
  };

  const onChange = (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);
          });
        });
        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);
        });
      });
      setKeepValue(aa);
      setValue(list);
    }
  };

  return (
    <Modal
      title="初始化"
      bodyStyle={{ width: '100%', minHeight: '100px', maxHeight: '600px', overflow: 'scroll' }}
      width="980px"
      destroyOnClose
      centered
      {...props}
      forceRender
      getContainer={false}
      footer={[
        // <Button onClick={() => setListVisible(true)}>产品激活</Button>,
        <Button type="primary" onClick={() => onSubmit()}>
          确认
        </Button>,
      ]}
    >
      <div>
        {visible && (
          <div className={styles.initItemData1}>
            {title &&
              title.map((item, index) => (
                <div key={index}>
                  <Divider
                    orientation="center"
                    style={{
                      margin: '0 0 20px 0',
                      color: '#15428b',
                      borderTopColor: '#99bbe8',
                    }}
                  >
                    {item}
                  </Divider>
                  {checkboxFlag == 0 ? (
                    <CheckboxGroup
                      options={data[item]}
                      value={value}
                      onChange={e => onChange(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>
        )}
      </div>
      <Modal
        title="产品激活"
        visible={listVisible}
        onCancel={() => setListVisible(false)}
        onOk={() => codeSubmit()}
        width="700px"
      >
        <Form form={form}>
          <Row span={24}>
            <Col span={6}>
              <Form.Item
                label="产品激活码"
                name="License1"
                // rules={[{ required: true, message: '请输入产品激活码' }]}
              >
                <Input
                  maxLength={5}
                  onPaste={e => {
                    let aa = e.clipboardData
                      .getData('Text')
                      .split('-')
                      .join('');
                    let a1 = aa.substring(0, 5);
                    let a2 = aa.substring(5, 10);
                    let a3 = aa.substring(10, 15);
                    let a4 = aa.substring(15, 20);
                    let a5 = aa.substring(20, 25);
                    form.resetFields();
                    form.setFieldsValue({
                      License1: a1,
                      License2: a2,
                      License3: a3,
                      License4: a4,
                      License5: a5,
                    });
                  }}
                />
              </Form.Item>
            </Col>
            <Col span={1}>
              <Form.Item>
                <span style={{ marginLeft: '10px' }}>-</span>
              </Form.Item>
            </Col>
            <Col span={3}>
              <Form.Item name="License2">
                <Input
                  maxLength={5}
                  onPaste={e => {
                    let aa = e.clipboardData
                      .getData('Text')
                      .split('-')
                      .join('');
                    let a1 = aa.substring(0, 5);
                    let a2 = aa.substring(5, 10);
                    let a3 = aa.substring(10, 15);
                    let a4 = aa.substring(15, 20);
                    let a5 = aa.substring(20, 25);
                    form.resetFields();
                    form.setFieldsValue({
                      License1: a1,
                      License2: a2,
                      License3: a3,
                      License4: a4,
                      License5: a5,
                    });
                  }}
                />
              </Form.Item>
            </Col>
            <Col span={1}>
              <Form.Item>
                <span style={{ marginLeft: '10px' }}>-</span>
              </Form.Item>
            </Col>
            <Col span={3}>
              <Form.Item name="License3">
                <Input
                  maxLength={5}
                  onPaste={e => {
                    let aa = e.clipboardData
                      .getData('Text')
                      .split('-')
                      .join('');
                    let a1 = aa.substring(0, 5);
                    let a2 = aa.substring(5, 10);
                    let a3 = aa.substring(10, 15);
                    let a4 = aa.substring(15, 20);
                    let a5 = aa.substring(20, 25);
                    form.resetFields();
                    form.setFieldsValue({
                      License1: a1,
                      License2: a2,
                      License3: a3,
                      License4: a4,
                      License5: a5,
                    });
                  }}
                />
              </Form.Item>
            </Col>
            <Col span={1}>
              <Form.Item>
                <span style={{ marginLeft: '10px' }}>-</span>
              </Form.Item>
            </Col>
            <Col span={3}>
              <Form.Item name="License4">
                <Input
                  maxLength={5}
                  onPaste={e => {
                    let aa = e.clipboardData
                      .getData('Text')
                      .split('-')
                      .join('');
                    let a1 = aa.substring(0, 5);
                    let a2 = aa.substring(5, 10);
                    let a3 = aa.substring(10, 15);
                    let a4 = aa.substring(15, 20);
                    let a5 = aa.substring(20, 25);
                    form.resetFields();
                    form.setFieldsValue({
                      License1: a1,
                      License2: a2,
                      License3: a3,
                      License4: a4,
                      License5: a5,
                    });
                  }}
                />
              </Form.Item>
            </Col>
            <Col span={1}>
              <Form.Item>
                <span style={{ marginLeft: '10px' }}>-</span>
              </Form.Item>
            </Col>
            <Col span={3}>
              <Form.Item name="License5">
                <Input
                  maxLength={5}
                  onPaste={e => {
                    let aa = e.clipboardData
                      .getData('Text')
                      .split('-')
                      .join('');
                    let a1 = aa.substring(0, 5);
                    let a2 = aa.substring(5, 10);
                    let a3 = aa.substring(10, 15);
                    let a4 = aa.substring(15, 20);
                    let a5 = aa.substring(20, 25);
                    form.resetFields();
                    form.setFieldsValue({
                      License1: a1,
                      License2: a2,
                      License3: a3,
                      License4: a4,
                      License5: a5,
                    });
                  }}
                />
              </Form.Item>
            </Col>
          </Row>
          <Form.Item
            name="name"
            label="部署人工号"
            rules={[
              // { required: true, message: '请输入部署人工号' },
              {
                validator: (rule, value) => {
                  let aa = /^[1-9]([0-9])*$/;
                  let bb = form.getFieldValue().name;
                  if (!aa.test(bb)) {
                    return Promise.reject('请正确填写工号');
                  }
                  return Promise.resolve();
                },
              },
            ]}
          >
            <Input placeholder="请输入部署人工号" allowClear style={{ width: '33%' }} />
          </Form.Item>
        </Form>
      </Modal>
    </Modal>
  );
};
export default InitModal;