/* eslint-disable no-undef */
/* eslint-disable guard-for-in */
/* eslint-disable no-restricted-syntax */
/* eslint-disable camelcase */
/* eslint-disable react/jsx-no-undef */
/* eslint-disable valid-typeof */
/* eslint-disable no-unused-vars */
/* eslint-disable consistent-return */
/* eslint-disable no-shadow */
/* eslint-disable indent */
/* eslint-disable no-unused-expressions */
/* eslint-disable array-callback-return */
/* eslint-disable eqeqeq */
/* eslint-disable no-plusplus */
import React, { useState, useEffect, useCallback, useRef } from 'react';
import { Form, Modal, Divider, Checkbox, Tabs, Empty } from 'antd';
import DragTable from '@/components/DragTable/DragTable';
import classnames from 'classnames';
import styles from './incident.less';
const CheckboxGroup = Checkbox.Group;
const EditModal = props => {
  const { callBackSubmit = () => {}, pickItem, visible, filed, newCheckedList, flag } = props;
  const [loading, setLoading] = useState(false);
  const [value, setValue] = useState('');
  const [checkValue, setCheckValue] = useState([]);
  const [form] = Form.useForm();
  const [title, setTitle] = useState([]);
  const { Item } = Form;
  const [checkedList, setCheckedList] = useState([]); // 选中复选框内容
  const [indeterminate, setIndeterminate] = useState([]);
  const [checkAll, setCheckAll] = useState([]);
  const [selectData, setSelectData] = useState([]);
  const [arrValue, setArrValue] = useState([]);
  const [data, setData] = useState(0);
  const [flagg, setFlagg] = useState(0);
  const [type, setType] = useState(); // 是否全选
  let objArr = [];

  const onChangeList = (list, index, title) => {
    const checkedListArr = [...checkedList];
    checkedListArr[index] = list;
    // 将第一次打开回显数据先存成数组
    let oldArr = [];
    let addArr = [];
    let newArr = [];
    // if (flagg == 0) {
    arrValue.map((item, index) => {
      oldArr = oldArr.concat(item);
    });

    console.log(oldArr);
    // 将第一次打开回显数据存入已选择数组里
    oldArr.map(item => {
      newArr.push(item);
    });
    console.log(newArr);
    // 获取本次新增数据后的数组
    let objArr = [];
    checkedListArr.map(item => {
      objArr = objArr.concat(item);
    });
    console.log(checkedListArr);
    console.log(objArr); // 本次增加数据后数组
    console.log(arrValue); // 上次数组
    // 获取新增数据
    objArr.map((item1, index1) => {
      if (arrValue.indexOf(item1) == -1) {
        addArr.push(item1);
      }
    });
    // 将每次新增数据从尾部写入已选择数组里
    if (addArr.length != 0) {
      addArr.map(item => {
        newArr.push(item);
      });
    }
    // 保存此次所有数据顺序
    setArrValue(newArr);
    setCheckedList(checkedListArr);
    const indeterminateArr = [...indeterminate];
    const checkAllArr = [...checkAll];
    indeterminateArr[index] = !!list.length && list.length < filed[title].length;
    checkAllArr[index] = list.length === filed[title].length;
    setIndeterminate(indeterminateArr);
    setCheckAll(checkAllArr);
    setFlagg(0);
  };

  const onSubmit1 = () => {
    let aRR = [];
    selectData.map(item => {
      if (typeof item == 'string') {
        aRR = selectData;
      } else {
        aRR.push(item.name);
      }
    });
    let newArr = selectData.map(item => item.name);
    console.log(newArr);
    console.log(filed.外部字段);
    let valueArr = [];
    if (filed.外部字段) {
      newArr.forEach(item => {
        if (filed.外部字段.indexOf(item) != -1) {
          valueArr.push(item);
        }
      });
    }
    callBackSubmit({
      valueArr,
      checkedList,
      str: aRR.join(','),
      pickItem,
      stt: aRR,
      title,
    });
  };

  const onCheckAllChange1 = e => {
    setData(1);
    const indeterminateArr = [...indeterminate];
    const checkAllArr = [...checkAll];
    const checkedListArr = [...checkedList];
    checkAllArr[e.target.index] = e.target.checked;
    indeterminateArr[e.target.index] = false;
    e.target.checked
      ? (checkedListArr[e.target.index] = e.target.checkvalue)
      : (checkedListArr[e.target.index] = []);
    setType(e.target.checked);
    setCheckedList(checkedListArr);
    setIndeterminate(indeterminateArr);
    setCheckAll(checkAllArr);
  };

  useEffect(() => {
    selectAll();
    // console.log(flagg);
    // // 不是第一次
    // if (flagg == 0) {
    //   console.log(12121);
    //   selectAll();
    // }
    // // 是否是全选
    // if (data == 1) {
    //   selectAll();
    // }
    setData(0);
  }, [checkedList]);

  const selectAll = () => {
    objArr = [];
    let lastArr = [];
    // 处理未排序的勾选数据扁平化
    checkedList.map(item => {
      objArr = objArr.concat(item);
    });

    // 判断是否操作全部勾选的复选框
    if (data == 1) {
      // 处理上次选中改变顺序后的数据扁平化
      let newArr = [];
      arrValue.map(item => {
        if (item.name == undefined) {
          newArr = arrValue;
        } else {
          newArr = arrValue.map(item => item.name);
        }
      });
      // 判断是否为全选
      if (type == false) {
        // 判断上次有顺序的数据是否包含这次未排序已选列表数据
        newArr.map(item => {
          if (objArr.indexOf(item) != -1) {
            lastArr.push(item);
          }
        });
        let newArr1 = lastArr.map(item => ({ name: item }));
        if (newArr1.length === 1 && newArr1[0].name === '') {
          newArr1 = [];
        }
        setSelectData(newArr1);
        setArrValue(lastArr);
      } else {
        // 全选状态时
        let addArr = [];
        objArr.map(item => {
          if (newArr.indexOf(item) == -1) {
            addArr.push(item);
          }
        });
        addArr.map(item => {
          newArr.push(item);
        });
        let newArr1 = newArr.map(item => ({ name: item }));
        if (newArr1.length === 1 && newArr1[0].name === '') {
          newArr1 = [];
        }
        setSelectData(newArr1);
        setArrValue(newArr);
      }
    } else {
      // 判断扁平处理后的选中未排序列表数据是否存在于上次已选数组中
      arrValue.map(item => {
        if (objArr.indexOf(item) != -1) {
          lastArr.push(item);
        }
      });
      let newArr1 = lastArr.map(item => ({ name: item }));
      if (newArr1.length === 1 && newArr1[0].name === '') {
        newArr1 = [];
      }
      setSelectData(newArr1);
      setArrValue(lastArr);
    }
  };

  useEffect(() => {
    if (visible) {
      setFlagg(1);
      let arr = Object.keys(filed);
      console.log(arr, 'arr');
      setTitle(arr);
      let checkArr = [];
      let indeterminateArr = [];
      let checkAllArr = [];
      arr.map((item, index) => {
        checkArr[index] = [];
        newCheckedList.map(checkItem => {
          if (filed[item].includes(checkItem)) {
            checkArr[index].push(checkItem);
          }
        });
        indeterminateArr.push(
          !!checkArr[index].length && checkArr[index].length < filed[item].length,
        );
        checkAllArr.push(checkArr[index].length === filed[item].length);
      });
      setCheckedList(checkArr);
      setIndeterminate(indeterminateArr);
      setCheckAll(checkAllArr);
      let newArr1 = newCheckedList.map(item => ({ name: item }));
      if (newArr1.length === 1 && newArr1[0].name === '') {
        newArr1 = [];
      }
      setSelectData(newArr1);
      setArrValue(newArr1);
    }
  }, [visible]);

  const dragCallBack = arr => {
    if (arr) {
      setSelectData(arr);
      let newArr = [];
      arr.map(item => {
        newArr.push(item.name);
      });
      setArrValue(newArr);
    }
  };

  const columns = [
    {
      title: '已选列表',
      dataIndex: 'name',
      width: 150,
      key: 'name',
    },
  ];

  return (
    <Modal
      title="字段集选择"
      bodyStyle={{ width: '100%', minHeight: '100px' }}
      width="750px"
      destroyOnClose
      centered
      cancelText="取消"
      okText="确认"
      {...props}
      onOk={() => onSubmit1()}
      forceRender
      getContainer={false}
    >
      {visible && (
        <div className={styles.listCard}>
          <div className={styles.cardItem} style={{ borderRight: '1px solid #99bbe8' }}>
            {flag === 0 ? (
              <>
                <div className={styles.cardContent}>
                  <span
                    style={{
                      color: 'red',
                      fontSize: '1rem',
                      marginLeft: '25px',
                    }}
                  >
                    请先选择事件主表
                  </span>
                </div>
              </>
            ) : (
              <>
                {JSON.stringify(filed) == '{}' ? (
                  <>
                    <div className={styles.cardContent}>
                      <Empty
                        image={Empty.PRESENTED_IMAGE_SIMPLE}
                        description="表字段缺失请先配置表/字段"
                      />
                    </div>
                  </>
                ) : (
                  <>
                    <div className={styles.cardContent}>
                      {title.map((item, index) => (
                        <div
                          className={classnames({
                            [styles.cardItemData]: true,
                            [styles.cardItemData1]: item == '外部字段',
                          })}
                          key={index}
                        >
                          <Divider
                            orientation="left"
                            style={{
                              margin: '0 0 10px 0',
                              color: '#15428b',
                              borderTopColor: '#99bbe8',
                            }}
                          >
                            <Checkbox
                              indeterminate={indeterminate[index]}
                              onChange={onCheckAllChange1}
                              index={index}
                              checkvalue={filed[item]}
                              checked={checkAll[index]}
                              style={{ marginRight: '7px' }}
                            />
                            {item == '外部字段' && <span style={{ color: 'red' }}>{item}</span>}
                            {item == '内置字段' && <span>{`${item}(谨慎选择)`}</span>}
                            {item != '外部字段' && item != '内置字段' && <span>{item}</span>}
                          </Divider>
                          <CheckboxGroup
                            options={filed[item]}
                            value={checkedList[index]}
                            onChange={e => onChangeList(e, index, item)}
                          />
                        </div>
                      ))}
                    </div>
                  </>
                )}
              </>
            )}
          </div>
          <div className={styles.cardItem}>
            <div className={styles.cardContent}>
              <div className={styles.doctorTable}>
                <DragTable
                  bordered
                  style={{ marginBottom: '10px' }}
                  rowKey={record => record.name}
                  columns={columns}
                  dataSource={selectData}
                  pagination={false}
                  size="small"
                  dragCallBack={dragCallBack}
                  ItemTypes="stadingOrder"
                />
              </div>
            </div>
          </div>
        </div>
      )}
    </Modal>
  );
};
export default EditModal;