/* eslint-disable no-plusplus */
/* eslint-disable array-callback-return */
/* eslint-disable no-unused-expressions */
/* eslint-disable no-shadow */
import React, { useState, useEffect, useCallback, useRef } from 'react';
import {
  Form,
  Modal,
  Space,
  Divider,
  Radio,
  Checkbox,
  Button,
  Tabs,
  Pagination,
  Input,
} from 'antd';

import DragTable from '@/components/DragTable/DragTable';
import styles from './incident.less';
const CheckboxGroup = Checkbox.Group;
const { TabPane } = Tabs;
const ChangeAddFlows = props => {
  const {
    callBackSubmit = () => {},
    pickItem,
    visible,
    filed1,
    characterValue,
    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 [arrValue, setArrValue] = useState([]);
  const [data, setData] = useState([]);
  const [flagg, setFlagg] = useState(0);
  const [type, setType] = useState(); // 是否全选
  const [searchWord, setSearchWord] = useState(''); // 关键字
  const { Search } = Input;
  const [total, setTotal] = useState();
  const [pageSize, setPageSize] = useState(10);
  const [currentPage, setCurrentPage] = useState(1);
  let objArr = [];

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

  const onSubmit = () => {
    console.log(selectData);
    let aRR = [];
    selectData.map(item => {
      console.log(typeof item);
      if (typeof item == 'string') {
        aRR = selectData;
      } else {
        console.log(112212);
        console.log(item.name);
        aRR.push(item.name);
        console.log(63467246);
        console.log(aRR);
      }
    });

    console.log(aRR);
    callBackSubmit({
      checkedList,
      str: aRR.join(','),
      pickItem,
      stt: aRR,
      title,
      filed22: filed1,
    });
  };
  const onCheckAllChange = 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] = []);
    setCheckedList(checkedListArr);
    setType(e.target.checked);
    setIndeterminate(indeterminateArr);
    setCheckAll(checkAllArr);
  };
  useEffect(() => {
    if (flagg == 0) {
      selectAll();
    }
    if (data == 1) {
      selectAll();
    }
    setData(0);
  }, [checkedList]);

  const selectAll = () => {
    console.log(data);
    console.log(checkedList);
    objArr = [];
    let lastArr = [];
    checkedList.map(item => {
      objArr = objArr.concat(item);
    });
    console.log(arrValue);
    console.log(objArr);
    if (data == 1) {
      let newArr = [];
      arrValue.map(item => {
        if (item.name == undefined) {
          newArr = arrValue;
        } else {
          newArr = arrValue.map(item => item.name);
        }
      });
      console.log(newArr);
      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 = [];
        }
        console.log(newArr1);
        setSelectData(newArr1);
        setArrValue(lastArr);
      } else {
        let addArr = [];
        objArr.map(item => {
          if (newArr.indexOf(item) == -1) {
            addArr.push(item);
          }
        });
        console.log(addArr);
        addArr.map(item => {
          newArr.push(item);
        });
        console.log(newArr);
        let newArr1 = newArr.map(item => ({ name: item }));
        if (newArr1.length === 1 && newArr1[0].name === '') {
          newArr1 = [];
        }
        console.log(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 = [];
      }
      console.log(lastArr);
      console.log(newArr1);
      setSelectData(newArr1);
      setArrValue(lastArr);
    }
  };

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

    if (arr) {
      console.log(111);
      setSelectData(arr);
      let newArr = arr.map(item => item.name);
      console.log(newArr);
      setArrValue(newArr);
    }
  };

  const submitSearchUser = () => {};

  // 获取搜索框的值
  const handleSearch = e => {
    setSearchWord(e.target.value);
  };

  // 监听分页
  const paginationChange = (page, pageSizes) => {
    // 分页时清空复选框
    setCurrentPage(page);
    setPageSize(pageSizes);
    // let username = form.getFieldValue('username');
    // getData(username, page, pageSizes);
  };

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

  return (
    <Modal
      title="权限选择"
      bodyStyle={{ width: '100%', height: '650px', overflowY: 'scorll' }}
      width="1000px"
      style={{ top: '10px' }}
      destroyOnClose
      centered
      cancelText="取消"
      okText="确认"
      {...props}
      onOk={() => onSubmit()}
      forceRender
      getContainer={false}
    >
      <Search
        style={{
          width: 260,
          marginRight: '20px',
          marginBottom: '10px',
        }}
        placeholder="搜索"
        onSearch={submitSearchUser}
        onChange={e => handleSearch(e)}
        enterButton
        value={searchWord}
      />
      <Button
        type="primary"
        htmlType="submit"
        //   onClick={() => {
        //     setCurrentPage(1);
        //     getData('', 1, pageSize);
        //     form.setFieldsValue({ username: '' });
        //   }}
      >
        重置
      </Button>
      {visible && (
        <div className={styles.listCard1}>
          <div className={styles.cardItem1}>
            <div className={styles.cardContent1}>
              <Tabs defaultActiveKey="0" className={styles.tab}>
                {title.map((item, index) => (
                  <TabPane tab={item} key={index}>
                    <div className={styles.cardItemData1} key={index}>
                      <Divider
                        orientation="left"
                        style={{
                          margin: '0 0 10px 0',
                          color: '#15428b',
                          borderTopColor: '#99bbe8',
                        }}
                      >
                        <Checkbox
                          indeterminate={indeterminate[index]}
                          onChange={onCheckAllChange}
                          index={index}
                          checkvalue={filed1[item]}
                          checked={checkAll[index]}
                          style={{ marginRight: '7px' }}
                        />
                        {item}
                      </Divider>
                      <CheckboxGroup
                        options={filed1[item]}
                        value={checkedList[index]}
                        onChange={e => onChangeList1(e, index, item)}
                      />
                    </div>
                  </TabPane>
                ))}
              </Tabs>
            </div>
          </div>
          <div className={styles.cardItem11}>
            <DragTable
              bordered
              style={{ marginBottom: '10px' }}
              rowKey={record => record.name}
              columns={columns}
              dataSource={selectData}
              pagination={false}
              size="small"
              dragCallBack={dragCallBack}
              ItemTypes="stadingOrder"
            />
          </div>
        </div>
      )}
      <Pagination
        total={total}
        showTotal={item => `共 ${item} 条`}
        defaultPageSize={pageSize}
        defaultCurrent={1}
        current={currentPage}
        onChange={paginationChange}
        style={{ marginBottom: '10px' }}
        size="small"
        showQuickJumper
      />
    </Modal>
  );
};
export default ChangeAddFlows;
