/* eslint-disable no-lonely-if */
import React, { useEffect, useState } from 'react';
import { GetRoleUser } from '@/services/workflow/workflow';
import { Modal, Checkbox, notification, Empty, Divider, Input } from 'antd';
import './Undertaker.less';

const { Search } = Input;
const Undertaker = props => {
  const { onSubumit, handleCancel, visible, chooseUser } = props;
  const [checkedList, setCheckedList] = useState([]); // 选中的数据
  const [plainOptions, setPlainOptions] = useState([]); // 默认的的数据
  const [indeterminate, setIndeterminate] = useState(false); // 全选框的有选择但是没有全选的样式
  const [checkAll, setCheckAll] = useState(false); // 全选框全选样式
  const CheckboxGroup = Checkbox.Group;
  const [searchValue, setSearchValue] = useState();
  const [keepCheckedList, setKeepCheckedList] = useState([]);
  useEffect(() => {
    if (visible) {
      getData('', '1');
    } else {
      setCheckedList([]);
      setPlainOptions([]);
      setCheckAll(false);
      setIndeterminate(false);
    }
  }, [visible]);
  // useEffect(() => {
  //   // 选中列表回显
  //   console.log(keepCheckedList);
  //   debugger;
  //   if (chooseUser && plainOptions.length > 0) {
  //     if (keepCheckedList) {
  //       // onChange(chooseUser.defaultUserId);
  //     } else {
  //       onChange(chooseUser.defaultUserId);
  //     }
  //   }
  // }, [plainOptions]);

  // 获取可选默认承办人数据
  const getData = (val, flag) => {
    GetRoleUser({
      pageIndex: 1,
      pageSize: 1,
      roleId: chooseUser.roleId,
      Type: Number(chooseUser.type),
      keyword: val ? val : searchValue,
    }).then(res => {
      if (res.code === 0) {
        let arr = [];
        let data = res.data.data[0].userList.map(item => {
          arr.push(item.id);
          return { value: item.id, label: item.name };
        });
        setPlainOptions(data);
        if (flag) {
          setCheckedList(chooseUser.defaultUserId);
          setKeepCheckedList(chooseUser.defaultUserId);
          setIndeterminate(
            !!chooseUser.defaultUserId.length && chooseUser.defaultUserId.length < data.length,
          );
          setCheckAll(chooseUser.defaultUserId.length === data.length);
        } else {
          if (val) {
            let list = [];
            checkedList.forEach(i => {
              if (arr.indexOf(i) !== -1) {
                list.push(i);
              }
            });
            setCheckedList(list);
            setIndeterminate(!!list.length && list.length < data.length);
            setCheckAll(list.length === data.length);
          } else {
            setCheckedList(keepCheckedList);
            setIndeterminate(!!keepCheckedList.length && keepCheckedList.length < data.length);
            setCheckAll(keepCheckedList.length === data.length);
          }
        }
      } else {
        notification.error({
          message: '提示',
          duration: 3,
          description: res.msg,
        });
      }
    });
  };

  // 保存选择默认承办人
  const onSave = () => {
    let userName = [];
    let mapList = new Map();
    plainOptions.forEach(item => {
      mapList.set(item.value, item.label);
    });
    checkedList.forEach(item => {
      if (mapList.has(item)) {
        userName.push(mapList.get(item));
      }
    });
    onSubumit(userName.join(','), checkedList);
  };

  // 复选框全选监听
  const onCheckAllChange = e => {
    let allOptions = plainOptions.map(item => item.value);
    if (e.target.checked) {
      let data = Array.from(new Set([...keepCheckedList, ...allOptions]));
      setKeepCheckedList(data);
    } else {
      let arr = [...keepCheckedList];
      allOptions.forEach(i => {
        if (arr.indexOf(i) !== -1) {
          arr = arr.filter(item => item !== i);
        }
      });
      setKeepCheckedList(arr);
    }

    setCheckedList(e.target.checked ? allOptions : []);
    setIndeterminate(false);
    setCheckAll(e.target.checked);
  };

  // 复选框监听事件
  const onChange = list => {
    setCheckedList(list);
    setIndeterminate(!!list.length && list.length < plainOptions.length);
    setCheckAll(list.length === plainOptions.length);
    if (list.length > checkedList.length) {
      let data = Array.from(new Set([...keepCheckedList, ...list]));
      setKeepCheckedList(data);
    } else {
      let arr = [...keepCheckedList];
      checkedList.forEach(i => {
        if (list.indexOf(i) === -1) {
          arr = arr.filter(item => item !== i);
        }
      });
      setKeepCheckedList(arr);
    }
  };

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

  const submitSearchUser = e => {
    getData(e);
  };
  return (
    <div>
      <Modal
        title="选择默认承办人"
        visible={visible}
        onOk={onSave}
        width={400}
        onCancel={handleCancel}
        maskClosable={false}
        destroyOnClose
      >
        <div>
          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
            <Checkbox indeterminate={indeterminate} onChange={onCheckAllChange} checked={checkAll}>
              <span style={{ fontWeight: 700 }}>用户列表</span>
            </Checkbox>
            <Search
              style={{
                width: '180px',
              }}
              placeholder="请输入用户名称"
              value={searchValue}
              onSearch={submitSearchUser}
              onChange={e => handleSearch(e)}
            />
          </div>
          <Divider style={{ margin: '10px 0' }} />
          <div style={{ height: '380px', overflowY: 'scroll' }}>
            {plainOptions.length > 0 ? (
              <CheckboxGroup options={plainOptions} value={checkedList} onChange={onChange} />
            ) : (
              <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="未有查找到用户" />
            )}
          </div>
        </div>
      </Modal>
    </div>
  );
};

export default Undertaker;
