/* eslint-disable no-shadow */
/* eslint-disable arrow-body-style */
/* eslint-disable array-callback-return */
/* eslint-disable indent */
import React, { useState, useEffect, useCallback, useRef } from 'react';
import { Form, Modal, Space, Divider, Radio, Checkbox } from 'antd';

import styles from './standingBook.less';
import Sortable from 'sortablejs';
import DragTable from '@/components/DragTable/DragTable';
const CheckboxGroup = Checkbox.Group;

const AddModal = props => {
  // 自定义获取改变后的值hooks
  const usePrevious = value => {
    const ref = useRef();
    useEffect(() => {
      ref.current = value;
    });
    return ref.current;
  };
  const { callBackSubmit, pickItem, visible, filed, newCheckedList } = 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 [isFirst, setIsFirst] = useState(true);
  const prevAmount = usePrevious({ checkedList });

  const onChangeList = (list, index, title) => {
    const checkedListArr = [...checkedList];
    checkedListArr[index] = list;
    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);
  };

  const onCheckAllChange = e => {
    const indeterminateArr = [...indeterminate];
    const checkAllArr = [...checkAll];
    const checkedListArr = [...checkedList];
    checkAllArr[e.target.index] = e.target.checked;
    indeterminateArr[e.target.index] = false;
    // eslint-disable-next-line no-unused-expressions
    e.target.checked
      ? (checkedListArr[e.target.index] = e.target.checkvalue)
      : (checkedListArr[e.target.index] = []);
    setCheckedList(checkedListArr);
    setIndeterminate(indeterminateArr);
    setCheckAll(checkAllArr);
  };
  // 监听用户选择的字段名
  useEffect(() => {
    if (prevAmount) {
      selectAll();
    }
  }, [checkedList]);

  const selectAll = () => {
    if (!visible) {
      return;
    }
    // 是否第一次保存数据
    if (isFirst) {
      setIsFirst(false);
      return;
    }
    // 新的选择后的数据(已选字段列表数据)
    let newSelect = JSON.parse(JSON.stringify(selectData));
    // 当前选中的
    let currentArr;
    // 上一次选中的
    let preArr;
    // 获取扁平化后的数组
    currentArr = new Set(checkedList.flat());
    preArr = new Set(prevAmount.checkedList.flat());

    // 找出相同的部分
    let someArr = [...new Set([...currentArr].filter(x => preArr.has(x)))];
    // 复选框事选中还是取消选中 add or del
    let checkType;
    if ([...currentArr].length > [...preArr].length) {
      checkType = 'add';
    } else if ([...currentArr].length < [...preArr].length) {
      checkType = 'del';
    }
    if (checkType === 'add') {
      // 添加新选中的元素
      currentArr.forEach(item => {
        if (someArr.indexOf(item) === -1) {
          newSelect.push({ name: item });
        }
      });
    } else if (checkType === 'del') {
      // 删除取消勾选的元素
      preArr.forEach(item => {
        if (someArr.indexOf(item) === -1) {
          newSelect.splice(newSelect.findIndex(ele => ele.name === item), 1);
        }
      });
    }
    console.log(newSelect);
    setSelectData(newSelect);
  };

  const onSubmit = () => {
    let newArr = selectData.map(item => item.name);
    callBackSubmit({ checkedList, str: newArr.join(','), pickItem });
  };
  const columns = [
    {
      title: '字段名',
      dataIndex: 'name',
      width: 150,
      key: 'name',
      ellipsis: true,
    },
  ];
  useEffect(() => {
    if (visible) {
      let arr = Object.keys(filed);
      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);
      // eslint-disable-next-line arrow-body-style
      let newArr = newCheckedList.map(item => {
        return { name: item };
      });
      if (newArr.length === 1 && newArr[0].name === '') {
        newArr = [];
      }
      console.log(newArr);
      setSelectData(newArr);
    } else {
      // 弹窗关闭时清空数据
      setSelectData([]);
      setCheckedList([]);
      setCheckAll([]);
      setIndeterminate([]);
      setIsFirst(true);
    }
  }, [visible]);

  const dragCallBack = arr => {
    console.log(arr);
    if (arr && !isFirst) {
      setSelectData(arr);
    }
  };
  return (
    <Modal
      title="字段集选择"
      bodyStyle={{ width: '100%', minHeight: '100px' }}
      style={{ top: '10px' }}
      width="750px"
      centered
      maskClosable={false}
      cancelText="取消"
      okText="确认"
      {...props}
      onOk={() => onSubmit()}
      confirmLoading={loading}
      forceRender
      getContainer={false}
      destroyOnClose
    >
      {visible && (
        <div className={styles.listCard}>
          <div className={styles.cardItem} style={{ borderRight: '1px solid #99bbe8' }}>
            <Divider
              orientation="left"
              style={{ margin: '0 0 10px 0', backgroundColor: '#dfe8f6' }}
            >
              待选字段列表
            </Divider>
            <div className={styles.cardContent}>
              {title.map((item, index) => {
                return (
                  <div className={styles.cardItemData} key={index}>
                    <Divider
                      orientation="left"
                      style={{
                        margin: '0 0 10px 0',
                        color: '#15428b',
                        borderTopColor: '#99bbe8',
                      }}
                    >
                      {item}{' '}
                      <Checkbox
                        indeterminate={indeterminate[index]}
                        onChange={onCheckAllChange}
                        index={index}
                        checkvalue={filed[item]}
                        checked={checkAll[index]}
                      >
                        {' '}
                      </Checkbox>
                    </Divider>
                    <CheckboxGroup
                      options={filed[item]}
                      value={checkedList[index]}
                      onChange={e => onChangeList(e, index, item)}
                    />
                  </div>
                );
              })}
            </div>
          </div>
          <div className={styles.cardItem}>
            <Divider
              orientation="left"
              style={{ margin: '0 0 10px 0', backgroundColor: '#dfe8f6' }}
            >
              已选字段列表
            </Divider>
            <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 AddModal;