import React, { useEffect, useState, useRef, useMemo } from 'react';
import { Modal, Divider, Checkbox } from 'antd';
import styles from './optionEdit.less';
import DragTable from '@/components/DragTable/DragTable';
const CheckboxGroup = Checkbox.Group;

const Fieldselection = props => {
  // 自定义获取改变后的值hooks
  const usePrevious = value => {
    const ref = useRef();
    useEffect(() => {
      ref.current = value;
    });
    return ref.current;
  };
  const { onSubumit, handleCancel, visible, fieldList, fieldData, fieldName } = props;
  const [checkList, setCheckList] = useState([]);
  const [selectList, setSelectList] = useState([]); // 选中字段列表
  const [isFirst, setIsFirst] = useState(true);
  const prevAmount = usePrevious({ checkList });
  const columns = [
    {
      title: '字段名',
      dataIndex: 'name',
      width: 150,
      key: 'name',
    },
  ];

  useEffect(() => {
    if (visible) {
      setCheckList(fieldList);
      let newArr = fieldData.map(item => ({ name: item }));
      setSelectList(newArr);
    } else {
      setSelectList([]);
      setCheckList([]);
      setIsFirst(true);
    }
  }, [visible]);
  useEffect(() => {
    if (prevAmount) {
      selectAll();
    }
  }, [checkList]);
  const selectAll = () => {
    if (!visible) {
      return;
    }
    // 是否第一次保存数据
    if (isFirst) {
      setIsFirst(false);
      return;
    }
    // 新的选择后的数据（已选字段列表数据）
    let newSelect = JSON.parse(JSON.stringify(selectList));
    // 当前选中的
    let currentArr = [];
    // 上一次选中的
    let preArr = [];
    // 获取扁平化后的数组
    checkList.forEach(item => {
      currentArr = [...currentArr, ...item.defaultCheckedList];
    });
    prevAmount.checkList.forEach(item => {
      preArr = [...preArr, ...item.defaultCheckedList];
    });
    currentArr = new Set(currentArr);
    preArr = new Set(preArr);
    // 找出相同的部分
    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);
        }
      });
    }
    setSelectList(newSelect);
  };
  // 提交表单
  const onFinish = () => {
    let callArr = selectList.map(item => item.name);
    onSubumit(callArr);
  };
  // 复选框
  const onChange = (list, index) => {
    setCheckList(value => {
      const chooseList = JSON.parse(JSON.stringify(value));
      chooseList[index].defaultCheckedList = list;
      chooseList[index].indeterminate =
        !!list.length && list.length < chooseList[index].plainOptions.length;
      chooseList[index].checkAll = list.length === chooseList[index].plainOptions.length;
      return chooseList;
    });
  };
  // 全选
  const onCheckAllChange = (e, index) => {
    setCheckList(value => {
      const chooseList = JSON.parse(JSON.stringify(value));
      chooseList[index].defaultCheckedList = e.target.checked ? chooseList[index].plainOptions : [];
      chooseList[index].indeterminate = false;
      chooseList[index].checkAll = e.target.checked;
      return chooseList;
    });
  };
  // 拖拽回调
  const dragCallBack = arr => {
    if (arr) {
      setSelectList(arr);
    }
  };
  return (
    <Modal
      title={fieldName === 'CarField' ? '卡片字段配置' : '详情字段配置'}
      visible={visible}
      onOk={onFinish}
      width="750px"
      onCancel={handleCancel}
      maskClosable={false}
      destroyOnClose
      centered
    >
      <div className={styles.fieldContent}>
        {/* 待选字段列表 */}
        <div className={styles.willSelectBox}>
          <div className={styles.header}>
            <Divider orientation="left" className={styles.headDivider}>
              待选字段列表
            </Divider>
          </div>
          <div className={styles.cardContent}>
            {checkList.map((item, index) => (
              <div className={styles.cardBox} key={index}>
                <div className={styles.title}>
                  <Divider orientation="left" className={styles.cardDivider}>
                    <span className={styles.groupName}>{item.groupName}</span>
                    <Checkbox
                      indeterminate={item.indeterminate}
                      onChange={e => onCheckAllChange(e, index)}
                      checked={item.checkAll}
                    />
                  </Divider>
                </div>
                <div className={styles.filedList}>
                  <CheckboxGroup
                    key={index}
                    options={item.plainOptions}
                    value={item.defaultCheckedList}
                    onChange={list => onChange(list, index)}
                  />
                </div>
              </div>
            ))}
          </div>
        </div>
        {/* 已选字段列表 */}
        <div className={styles.hasSelectBox}>
          <div className={styles.header}>
            <Divider orientation="left" className={styles.headDivider}>
              已选字段列表
            </Divider>
          </div>
          <div className={styles.doctorTable}>
            <DragTable
              bordered
              rowKey={record => record.name}
              columns={columns}
              dataSource={selectList}
              pagination={false}
              size="small"
              dragCallBack={dragCallBack}
              ItemTypes="stadingOrder"
            />
          </div>
        </div>
      </div>
    </Modal>
  );
};
export default Fieldselection;
