/* eslint-disable no-cond-assign */
/* eslint-disable react/no-array-index-key */
/* eslint-disable no-undef */
/* 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 } from 'react';
import { Modal, Checkbox, Tabs, Input, Button, Pagination, Empty } from 'antd';
import { CM_Event_LoadDepartmentAndRoles } from '@/services/standingBook/api';

import styles from './incident.less';
const CheckboxGroup = Checkbox.Group;
const { TabPane } = Tabs;
const ChangeAdd = props => {
  const { callBackSubmit = () => {}, isType, pickItem, visible, filed11, newCheckedList } = props;
  const [title, setTitle] = useState([]);
  const [checkedList, setCheckedList] = useState([]); // 选中复选框内容
  const [searchWord, setSearchWord] = useState(''); // 关键字
  const { Search } = Input;
  const [total, setTotal] = useState();
  const [pageSize, setPageSize] = useState(40);
  const [currentPage, setCurrentPage] = useState(1);
  const [roleValue, setRoleValue] = useState([]);
  const [checkDataRole, setCheckDataRole] = useState([]);
  const [checkDataPm, setCheckDataPm] = useState([]);
  const [checkDataSite, setCheckDataSite] = useState([]);
  const [filed1, setFiled1] = useState([]); // 角色全部数据
  const [saveCheckValue, setSaveCheckValue] = useState([]); // 保存选中值
  const [keepOption1, setKeepOption1] = useState([]); // 保存了首次获取的部门列表数据
  const [keepOption2, setKeepOption2] = useState([]); // 保存了首次获取的站点列表数据
  const [keepTabKey, setKeepTabKey] = useState(0); // 保存tabs的key
  const [list, setList] = useState([]);
  const [listPm, setListPm] = useState([]);
  const [listSite, setListSite] = useState([]);
  const [keyValue, setKeyValue] = useState('0');
  const [emptyValue, setEmptyValue] = useState(0);

  const onSubmit = () => {
    // 没有勾选部门下的选项
    if (saveCheckValue[1] == undefined) {
      let data = [];
      newCheckedList.map(checkItem => {
        if (keepOption1.includes(checkItem)) {
          data.push(checkItem);
        }
      });
      saveCheckValue[1] = data;
    }
    // 没有勾选站点下的选项
    if (saveCheckValue[2] == undefined) {
      let data = [];
      newCheckedList.map(checkItem => {
        if (keepOption2.includes(checkItem)) {
          data.push(checkItem);
        }
      });
      saveCheckValue[2] = data;
    }
    let data = [];
    saveCheckValue.map((item, index) => {
      data = data.concat(item);
    });
    callBackSubmit({
      saveCheckValue,
      str: data.join(','),
      pickItem,
      stt: data,
      title,
      filed22: filed1,
      isType,
    });
    setKeyValue('0');
    setSearchWord('');
  };

  useEffect(() => {
    setKeepOption1(filed11['部门']);
    setKeepOption2(filed11['站点']);
    getRoles('角色', '', pageSize, 1);
    setRoleValue(filed1);
    let arr = Object.keys(filed1);
    setTitle(arr);
    let checkArr = [];
    let listdata = [];
    newCheckedList.map(checkItem => {
      if (filed11['角色'].includes(checkItem)) {
        listdata.push(checkItem);
      }
    });
    setCheckDataRole(listdata); // 用于设置首次展示已选列表角色数据
    checkArr[0] = listdata;
    setSaveCheckValue(checkArr);
    setCheckedList(checkArr);
    let pmdata = [];
    newCheckedList.map(checkItem => {
      if (filed11['部门'].includes(checkItem)) {
        pmdata.push(checkItem);
      }
    });
    setCheckDataPm(pmdata);
    let sitedata = [];
    newCheckedList.map(checkItem => {
      if (filed11['站点'].includes(checkItem)) {
        sitedata.push(checkItem);
      }
    });
    setCheckDataSite(sitedata);
  }, [visible]);

  const submitSearchUser = () => {
    if (keepTabKey == 0) {
      sreachRoles('角色', searchWord, pageSize, 1);
    }
    if (keepTabKey == 1) {
      sreachRoles('部门', searchWord, pageSize, 1);
    }
    if (keepTabKey == 2) {
      sreachRoles('站点', searchWord, pageSize, 1);
    }
  };

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

  // 监听分页
  const paginationChange = (page, pageSizes) => {
    if (keepTabKey == 0) {
      getRoles('角色', searchWord, pageSizes, page);
    }
    if (keepTabKey == 1) {
      getRoles('部门', searchWord, pageSizes, page);
    }
    if (keepTabKey == 2) {
      getRoles('站点', searchWord, pageSizes, page);
    }
    setCurrentPage(page);
    setPageSize(pageSizes);
  };
  // 搜索时获取数据
  const sreachRoles = (type, keywords, pageSizes, pageIndex) => {
    CM_Event_LoadDepartmentAndRoles({
      type,
      keywords,
      pageSize: pageSizes,
      pageIndex,
    }).then(res => {
      if (res.msg === 'Ok') {
        setRoleValue(formateArrDataA1(res.data, 'groupType'));
        setFiled1(formateArrDataA1(res.data, 'groupType'));
        setCurrentPage(1);
        setTotal(res.data.count);
        if (res.data.count == 0) {
          setEmptyValue(1);
        } else {
          setEmptyValue(0);
        }
      }
    });
  };

  // 重置
  const onReset = () => {
    // setListPm([]);
    if (keepTabKey == 0) {
      getRoles('角色', '', pageSize, 1);
    }
    if (keepTabKey == 1) {
      getRoles('部门', '', pageSize, 1);
    }
    if (keepTabKey == 2) {
      getRoles('站点', '', pageSize, 1);
    }
    setCurrentPage(1);
    setSearchWord('');
  };

  const getRoles = (type, keywords, pageSizes, pageIndex) => {
    CM_Event_LoadDepartmentAndRoles({
      type,
      keywords,
      pageSize: pageSizes,
      pageIndex,
    }).then(res => {
      if (res.msg === 'Ok') {
        setTotal(res.data.count);
        setRoleValue(formateArrDataA1(res.data, 'groupType'));
        setFiled1(formateArrDataA1(res.data, 'groupType'));
        if (res.data.count == 0) {
          setEmptyValue(1);
        } else {
          setEmptyValue(0);
        }
      }
    });
  };
  // 页面数据改变重新赋值
  useEffect(() => {
    let arr = Object.keys(filed1);
    setTitle(arr);
    let checkArr = [];
    let data = [];
    saveCheckValue.map((item, index) => {
      data = data.concat(item);
    });
    arr.forEach(item => {
      if (item == '角色') {
        checkArr[0] = [];
        checkDataRole.map(checkItem => {
          if (filed1['角色'].includes(checkItem)) {
            checkArr[0].push(checkItem);
          }
        });
        setCheckedList(checkArr); // 按对象数组格式
      } else if (item == '部门') {
        checkArr[1] = [];
        checkDataPm.map(checkItem => {
          if (filed1['部门'].includes(checkItem)) {
            checkArr[1].push(checkItem);
          }
        });
        setCheckedList(checkArr);
      } else if (item == '站点') {
        checkArr[2] = [];
        checkDataSite.map(checkItem => {
          if (filed1['站点'].includes(checkItem)) {
            checkArr[2].push(checkItem);
          }
        });
        setCheckedList(checkArr);
      }
    });
  }, [filed1]);

  const formateArrDataA1 = (initialArr, name) => {
    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);
      });
    });

    // 判定传参是否符合规则
    if (!(a3 instanceof Array)) {
      return '请传入正确格式的数组';
    }
    if (!name) {
      return '请传入对象属性';
    }
    // 先获取一下这个数组中有多少个"name"
    let nameArr = [];
    a3.map(i => {
      if (nameArr.indexOf(i.group) === -1) {
        nameArr.push(i.group);
      }
    });
    // 新建一个包含多个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]);
        }
      }
    }
    for (let key in tempObj) {
      let arr = [];
      tempObj[key].map(item => {
        tempObj[key] = arr;
        arr.push(item.Name);
      });
    }
    return tempObj;
  };

  useEffect(() => {
    let checkedListArr = [...saveCheckValue];
    let data = checkDataRole;
    let DataValue = [];
    // 拿到当前页数据
    checkDataRole.forEach(item => {
      if (roleValue['角色'].indexOf(item) != -1) {
        DataValue.push(item);
      }
    });
    // del
    if (DataValue.length > list.length) {
      DataValue.forEach(item => {
        if (list.indexOf(item) == -1) {
          data.splice(data.findIndex(ele => ele === item), 1);
        }
      });
    } else {
      // add
      list.forEach(item => {
        if (data.indexOf(item) == -1) {
          data.push(item);
        }
      });
    }
    checkedListArr[0] = data;
    setCheckDataRole(data);
    setSaveCheckValue(checkedListArr);
    setCheckedList(checkedListArr);
  }, [list]);

  useEffect(() => {
    let checkedListArr = [...saveCheckValue];
    let data = checkDataPm;
    let DataValue = [];
    // 拿到当前页数据
    checkDataPm.forEach(item => {
      if (roleValue['部门'].indexOf(item) != -1) {
        DataValue.push(item);
      }
    });
    // del
    if (DataValue.length > listPm.length) {
      DataValue.forEach(item => {
        if (listPm.indexOf(item) == -1) {
          data.splice(data.findIndex(ele => ele === item), 1);
        }
      });
    } else {
      // add
      listPm.forEach(item => {
        if (data.indexOf(item) == -1) {
          data.push(item);
        }
      });
    }
    checkedListArr[1] = data;
    setCheckDataPm(data);
    setSaveCheckValue(checkedListArr);
    setCheckedList(checkedListArr);
  }, [listPm]);

  useEffect(() => {
    const checkedListArr = [...saveCheckValue];
    let data = checkDataSite;
    let DataValue = [];
    // 拿到当前页数据
    checkDataSite.forEach(item => {
      if (roleValue['站点'].indexOf(item) != -1) {
        DataValue.push(item);
      }
    });
    // del
    if (DataValue.length > listSite.length) {
      DataValue.forEach(item => {
        if (listSite.indexOf(item) == -1) {
          data.splice(data.findIndex(ele => ele === item), 1);
        }
      });
    } else {
      // add
      listSite.forEach(item => {
        if (data.indexOf(item) == -1) {
          data.push(item);
        }
      });
    }
    checkedListArr[2] = data;
    setCheckDataSite(data);
    setSaveCheckValue(checkedListArr);
    setCheckedList(checkedListArr);
  }, [listSite]);
  const handleParChange = key => {
    setKeyValue(key);
    // setSearchWord('');
    setCurrentPage(1);
    setKeepTabKey(key);
    let value;
    if (key == 0) {
      value = '角色';
      getRoles('角色', searchWord, pageSize, 1);
    }
    if (key == 1) {
      value = '部门';
      getRoles('部门', searchWord, pageSize, 1);
    }
    if (key == 2) {
      value = '站点';
      getRoles('站点', searchWord, pageSize, 1);
    }
  };

  const onChangeListNew = list => {
    setList(list);
  };
  const onChangeListNew1 = list => {
    setListPm(list);
  };
  const onChangeListNew2 = list => {
    setListSite(list);
  };
  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}
      afterClose={() => {
        setKeyValue('0');
        setSearchWord('');
      }}
    >
      <Search
        style={{
          width: 260,
          marginRight: '20px',
          marginBottom: '10px',
        }}
        placeholder="搜索"
        onSearch={submitSearchUser}
        onChange={e => handleSearch(e)}
        enterButton
        value={searchWord}
      />
      <Button type="primary" htmlType="submit" onClick={onReset}>
        重置
      </Button>
      {visible && (
        <div className={styles.listCard1}>
          <div className={styles.cardItem1}>
            <div className={styles.cardContent1}>
              <Tabs activeKey={keyValue} className={styles.tab} onChange={handleParChange}>
                <TabPane tab="角色" key="0">
                  <div className={styles.cardItemData1}>
                    {emptyValue == 0 ? (
                      <CheckboxGroup
                        options={roleValue['角色']}
                        value={checkedList[0]}
                        onChange={onChangeListNew}
                      />
                    ) : (
                      <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="暂无数据" />
                    )}
                  </div>
                </TabPane>
                <TabPane tab="部门" key="1">
                  <div className={styles.cardItemData1}>
                    {emptyValue == 0 ? (
                      <CheckboxGroup
                        options={roleValue['部门']}
                        value={checkedList[1]}
                        onChange={onChangeListNew1}
                      />
                    ) : (
                      <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="暂无数据" />
                    )}
                  </div>
                </TabPane>
                <TabPane tab="站点" key="2">
                  <div className={styles.cardItemData1}>
                    {emptyValue == 0 ? (
                      <CheckboxGroup
                        options={roleValue['站点']}
                        value={checkedList[2]}
                        onChange={onChangeListNew2}
                      />
                    ) : (
                      <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="暂无数据" />
                    )}
                  </div>
                </TabPane>
              </Tabs>
            </div>
          </div>
          <div className={styles.cardItem11}>
            <div className={styles.cardContent1}>
              <Tabs className={styles.tab} activeKey={keyValue} onChange={handleParChange}>
                <TabPane tab="角色" key="0">
                  {checkDataRole.map((item, index) => (
                    <div
                      key={index}
                      style={{
                        marginBottom: '5px',
                      }}
                    >
                      {item}
                    </div>
                  ))}
                </TabPane>
                <TabPane tab="部门" key="1">
                  {checkDataPm.map((item, index) => (
                    <div
                      key={index}
                      style={{
                        marginBottom: '5px',
                      }}
                    >
                      {item}
                    </div>
                  ))}
                </TabPane>
                <TabPane tab="站点" key="2">
                  {checkDataSite.map((item, index) => (
                    <div
                      key={index}
                      style={{
                        marginBottom: '5px',
                      }}
                    >
                      {item}
                    </div>
                  ))}
                </TabPane>
              </Tabs>
            </div>
          </div>
        </div>
      )}
      <Pagination
        total={total}
        showTotal={item => `共 ${item} 条`}
        defaultPageSize={pageSize}
        defaultCurrent={1}
        pageSizeOptions={[10, 20, 40, 100]}
        current={currentPage}
        onChange={paginationChange}
        style={{ marginBottom: '10px' }}
        size="small"
        showQuickJumper
      />
    </Modal>
  );
};

export default ChangeAdd;
