/* 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,
  Input,
  Button,
  Pagination,
} from 'antd';
import DragTable from '@/components/DragTable/DragTable';
import { CM_Event_LoadDepartmentAndRoles } from '@/services/standingBook/api';

import Sortable from 'sortablejs';
import { add } from 'lodash-es';
import { string } from 'prop-types';
import { setServiceType } from '@/services/webConfig/api';
import { ContinuousLegend } from '@antv/g2/lib/dependents';
import { ConsoleSqlOutlined } from '@ant-design/icons';
import styles from './incident.less';
const CheckboxGroup = Checkbox.Group;
const { TabPane } = Tabs;
const AddModal = props => {
  const {
    callBackSubmit = () => {},
    isType,
    pickItem,
    visible,
    filed,
    filed1,
    characterValue,
    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([]);
  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);
  const [roleValue, setRoleValue] = 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);
      }
    });
    // } 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);
    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 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 onSubmit1 = () => {
    console.log(selectData);
    let aRR = [];
    selectData.map(item => {
      console.log(typeof item);
      if (typeof item == 'string') {
        console.log(1111);
        aRR = selectData;
      } else {
        aRR.push(item.name);
      }
    });
    console.log(aRR);
    let newArr = selectData.map(item => item.name);
    isType === 'rule'
      ? callBackSubmit(
          `${
            value === '无' || value === '' ? '' : `${value},`
          }${checkValue.join(',')}`,
        )
      : callBackSubmit({
          checkedList,
          str: aRR.join(','),
          pickItem,
          stt: aRR,
          title,
          filed22: filed1,
          isType,
        });
  };

  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);
    isType === 'rule'
      ? callBackSubmit(
          `${
            value === '无' || value === '' ? '' : `${value},`
          }${checkValue.join(',')}`,
        )
      : callBackSubmit({
          checkedList,
          str: aRR.join(','),
          pickItem,
          stt: aRR,
          title,
          filed22: filed1,
          isType,
        });
  };
  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);
  };

  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 = () => {
    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(lastArr);
        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(() => {
    setRoleValue(filed1);
    if (visible) {
      setFlagg(1);
      if (isType != '' && isType === 'add') {
        let arr = Object.keys(filed);
        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 (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);
        });
        console.log(checkArr);
        console.log(indeterminateArr);
        console.log(checkAllArr);
        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 if (isType === 'app') {
        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]);

  // useEffect(() => {
  //   setCurrentPage(1);
  // }, [visible]);
  const dragCallBack = arr => {
    console.log(arr);
    if (arr) {
      console.log(111);
      setSelectData(arr);
      let newArr = [];
      arr.map(item => {
        newArr.push(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 getRoles = () => {
    CM_Event_LoadDepartmentAndRoles().then(res => {
      if (res.msg === 'Ok') {
        // setRoleValue(formateArrDataA1(res.data, 'groupType'));
        console.log(formateArrDataA1(res.data, 'groupType'));
      }
    });
  };

  const formateArrDataA1 = (initialArr, name) => {
    console.log(initialArr);
    let aa = [];
    let a1 = [];
    let a2;
    let a3 = [];
    initialArr.data.map(i => {
      a2 = i.groupType;
      a1 = i.root;
      a1.map(j => {
        j.group = a2;
      });
      aa.push(i.root);
    });
    aa.map(p => {
      p.map(o => {
        a3.push(o);
      });
    });
    console.log(a3);

    // 判定传参是否符合规则
    if (!(a3 instanceof Array)) {
      return '请传入正确格式的数组';
    }
    if (!name) {
      return '请传入对象属性';
    }
    // 先获取一下这个数组中有多少个"name"
    let nameArr = [];
    a3.map(i => {
      if (nameArr.indexOf(i.group) === -1) {
        nameArr.push(i.group);
      }
    });
    console.log(nameArr);
    // 新建一个包含多个list的结果对象
    let tempObj = {};
    // 根据不同的"name"生成多个数组
    for (let k in nameArr) {
      for (let j in a3) {
        if (a3[j].group == nameArr[k]) {
          // 每次外循环时新建一个对应"name"的数组, 内循环时当前数组不变
          tempObj[nameArr[k]] = tempObj[nameArr[k]] || [];
          tempObj[nameArr[k]].push(a3[j]);
        }
      }
    }
    console.log(tempObj);
    for (let key in tempObj) {
      let arr = [];
      tempObj[key].map(item => {
        tempObj[key] = arr;
        arr.push(item.Name);
      });
    }
    return tempObj;
  };

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

  const handleParChange = key => {
    console.log(key);
    let value;
    if (key == 0) {
      value = '角色';
    }
    if (key == 1) {
      value = '部门';
    }
    if (key == 2) {
      value = '站点';
    }
    console.log(value);
    // getRoles();
  };
  if (isType != 'app') {
    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}>
                        <span
                          style={{
                            color: 'red',
                            fontSize: '1rem',
                            marginLeft: '25px',
                          }}
                        >
                          表字段缺失请先配置表/字段
                        </span>
                      </div>
                    </>
                  ) : (
                    <>
                      <div className={styles.cardContent}>
                        {title.map((item, index) => (
                          <div className={styles.cardItemData} 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}
                            </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>
    );
  }
  if (isType === 'app') {
    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}
                  onChange={handleParChange}
                >
                  {title.map((item, index) => (
                    <TabPane tab={item} key={index}>
                      <div className={styles.cardItemData1} key={index}>
                        <Divider
                          orientation="left"
                          style={{
                            margin: '0 0 10px -10px',
                            color: '#15428b',
                            borderTopColor: '#99bbe8',
                          }}
                        >
                          <Checkbox
                            indeterminate={indeterminate[index]}
                            onChange={onCheckAllChange}
                            index={index}
                            checkvalue={roleValue[item]}
                            checked={checkAll[index]}
                            style={{ marginRight: '7px' }}
                          />
                          {item}
                        </Divider>
                        <CheckboxGroup
                          options={roleValue[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 AddModal;
