/* 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 } from 'antd';
import DragTable from '@/components/DragTable/DragTable';

import Sortable from 'sortablejs';
import { add } from 'lodash-es';
import styles from './incident.less';
import { setServiceType } from '@/services/webConfig/api';
const CheckboxGroup = Checkbox.Group;
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(); // 是否全选
  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(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;
    setCheckedList(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);
  };

  const onSubmit1 = () => {
    let newArr = selectData.map(item => item.name);
    isType === 'rule'
      ? callBackSubmit(
          `${
            value === '无' || value === '' ? '' : `${value},`
          }${checkValue.join(',')}`,
        )
      : callBackSubmit({
          checkedList,
          str: newArr.join(','),
          pickItem,
          stt: newArr,
          title,
          filed22: filed1,
          isType,
        });
  };

  const onSubmit = () => {
    isType === 'rule'
      ? callBackSubmit(
          `${
            value === '无' || value === '' ? '' : `${value},`
          }${checkValue.join(',')}`,
        )
      : callBackSubmit({
          checkedList,
          str: selectData.join(','),
          pickItem,
          stt: selectData,
          title,
          filed22: filed1,
          isType,
        });
  };
  const onCheckAllChange1 = e => {
    console.log(11212123213);
    setData(1);
    const indeterminateArr = [...indeterminate];
    const checkAllArr = [...checkAll];
    const checkedListArr = [...checkedList];
    checkAllArr[e.target.index] = e.target.checked;
    console.log(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 => {
    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);
    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);
      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);
        });
        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);
        setSelectData(newArr);
      }
    } 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 columns = [
    {
      title: '字段名',
      dataIndex: 'name',
      width: 150,
      key: 'name',
    },
  ];
  if (isType != 'app') {
    return (
      <Modal
        title="字段集选择"
        bodyStyle={{ width: '100%', minHeight: '100px' }}
        width="700px"
        destroyOnClose
        centered
        cancelText="取消"
        okText="确认"
        {...props}
        onOk={() => onSubmit1()}
        forceRender
        getContainer={false}
      >
        {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>

              {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}>
              <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>
    );
  }
  if (isType === 'app') {
    return (
      <Modal
        title="部门或角色"
        bodyStyle={{ width: '100%', minHeight: '100px' }}
        width="1400px"
        style={{ top: '10px' }}
        destroyOnClose
        centered
        cancelText="取消"
        okText="确认"
        {...props}
        onOk={() => onSubmit()}
        forceRender
        getContainer={false}
      >
        {visible && (
          <div className={styles.listCard1}>
            <div
              className={styles.cardItem1}
              //   style={{ borderRight: '1px solid #99bbe8' }}
            >
              <Divider
                orientation="left"
                style={{ margin: '0 0 10px 0', backgroundColor: '#dfe8f6' }}
              >
                待选部门站点角色
              </Divider>
              <div className={styles.cardContent1}>
                {title.map((item, 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>
                ))}
              </div>
            </div>
          </div>
        )}
      </Modal>
    );
  }
};
export default AddModal;
