/**
 * 钟是志
 * 2022年10月12日
 * 禅道 http://scjoyedu.eicp.net:88/zentao/bug-view-28974.html
 * 选辅导员,教师,学生的通用组件
 * api 文档 https://console-docs.apipost.cn/preview/caa25e097e7386d0/a2d8620d944c56b5
 * */
import React, { useState, useEffect } from 'react';
import styles from './styles/styles.less';
import { Modal, Button, Input, Checkbox, message, Icon, Tree, Spin, Tooltip } from 'antd';
import { formatTreeData, colorTranslate, getApis } from './publicFunctions';
import lowCodeProps from './lowCodeProps';
import request from '@/webPublic/one_stop_public/utils/request';

function requestData(data, url){
  url = window.specialImportantSystemConfig.httpServer + url;
  return request(url, data, {
    method: 'POST',
  });
}


export default function SelectPerson(props) {
  const [show, setShow] = useState(false);
  const propsDiy = window.smartFormSelectPersonComponent?.lowCodeProps || lowCodeProps();
  const apis = getApis(propsDiy.searchType);
  const [authInstitutionInfo, setAuthInstitutionInfo] = useState(null); // 楼栋信息
  const [searchKey, setSearchKey] = useState(''); // 搜索框的内容
  const [searchResult, setSearchResult] = useState([]); // 搜索到的内容
  const [detailList, setDetailList] = useState([]); // 第三列显示的列表
  const [sgUsers, setSelectUsers] = useState([]); // 选中的item
  const [sgUserIds, setSgUserIds] = useState([]); // 选中的businessKey
  const [checkedList, setCheckedList] = useState([]); // 树节点中选中的复选框
  const [jqpp, setJqpp] = useState(false); // 是否精确匹配
  function changeShow() {
    setShow(!show);
  }

  function initShowData(stateList = {}) {
    setCheckedList(stateList.checkedList || []);
    setSgUserIds(stateList.sgUserIds || []);
    setSelectUsers(stateList.sgUsers || []);
    setSearchKey(stateList.searchKey || '');
    setSearchResult(stateList.searchResult || []);
    setDetailList(stateList.detailList || []);
  }

  useEffect(() => {
    window.smartFormSelectPersonComponent = {
      changeShow,
      initShowData,
      lowCodeProps: lowCodeProps(),
      callback: ({
                   value,
                   componentState,
                 }) => {
        console.log(value, componentState);
      },
    };
  }, []);

  // 第二栏树形数据
  const getTreeList = () => {
    requestData({
      ...propsDiy.apiParams,
    }, apis.findTree)
      .then(res => {
        if (res) {
          res = formatTreeData(res);
          setAuthInstitutionInfo(res);
        }
      });
  };

  //根据关键字搜索
  const search = () => {
    if (searchKey === '') {
      setSearchResult([]);
    } else {
      if (searchKey.length < 2) {
        message.warning('请至少输入2个字符');
        return false;
      }
      requestData(
        {
          keyword: searchKey,
          isExact: jqpp,
          ...propsDiy.apiParams,
        },
        apis.search,
      )
        .then(res => {
          if (res && Array.isArray(res)) {
            setSearchResult(res);
          }
        });
    }
  };

  //清空搜索条件
  const clear = () => {
    setSearchKey('');
    setSearchResult([]);
  };

  //根据id进行搜索
  const searchById = (selectedKeys, e) => {
    const {
      businessKey,
      selectType
    } = e.node.props;
    let bKey = businessKey;
    requestData(
      {
        businessKey: bKey,
        selectType,
        ...propsDiy.apiParams,
      },
      apis.findList,
    )
      .then(res => {
        if (res) {
          setDetailList(res);
        }
      });
  };

  //选中的人
  const selectUser = user => {
    setSelectUsers([...sgUsers, user]);
    setSgUserIds([...sgUserIds, user.businessKey]);
  };

  //删除选中的人
  const deleteSg = (x, index, e) => {
    // 阻止事件冒泡
    e.stopPropagation();
    let sgNew = [...sgUsers];
    sgNew = sgNew.filter(g => {
      return x.businessKey !== g.businessKey;
    });
    setSelectUsers(sgNew);
    setSgUserIds(
      sgUserIds.filter(g => {
        return x.businessKey !== g;
      }),
    );

    setCheckedList(checkedList.filter((g) => {
      return x.businessKey !== g.businessKey && !g.businessKey.startsWith(x.businessKey);
    }));
  };

  // 确认按钮
  const auth = () => {
    const data = {
      businessKey: [...sgUserIds, ...checkedList.map(g => g.businessKey)],
      ...propsDiy.apiParams,
    };
    if (!data.businessKey.length) {
      message.warning(propsDiy.getResultProps.emptySelectMessage);
      return false;
    }
    message.info(propsDiy.getResultProps.message);
    requestData(data, apis[propsDiy.getDataMethod]?apis[propsDiy.getDataMethod]:apis.getData)
      .then(res => {
        if (res) {
          message.success('操作成功');
          if (window.smartFormSelectPersonComponent.callback) {
            window.smartFormSelectPersonComponent.callback({
              value: res,
              componentState: {
                checkedList,
                sgUserIds,
                sgUsers,
                searchKey,
                searchResult,
                // detailList,
              },
            });
          }
          changeShow();
          // props.getData();
        }
      });
  };

  const changeJqpp = e => {
    setJqpp(e.target.checked);
  };


  useEffect(() => {
    if (show) {
      getTreeList();
    }
  }, [show]);

  const changeTreeCheck = (checkedKeys, e) => {
    const keys = e.checkedNodes.map(g => {
      const {
        businessKey,
        businessMemo,
        businessName,
        noCheckNum,
        preCheckInNum,
        selectType,
        level,
        bedNum,
        isSelect,
        checkInNum,
        womanNoCheckNum,
        manNoCheckNum,
      } = g.props;
      return {
        womanNoCheckNum,
        manNoCheckNum,
        businessKey,
        businessMemo,
        businessName,
        noCheckNum,
        preCheckInNum,
        selectType,
        level,
        bedNum,
        isSelect,
        checkInNum,
      };
    });
    setCheckedList(keys);
  };

  const distinctArr = () => {
    let arr = checkedList.concat(sgUsers);
    let map = new Map();
    for (let item of arr) {
      map.set(item.businessKey, item);
    }
    arr = [...map.values()];
    arr.sort((a, b) => { // 排序解决 多层子级的问题。
      if (a.businessKey && b.businessKey) {
        return a.businessKey.length - b.businessKey.length;
      }
      return 0;
    });
    const distnctBusinessKey = arr.reduce(function (response, current, index) {
      // 删除子级 key 保证数据唯一性
      let add = true;
      for (let item of response) {
        if (current.businessKey.startsWith(item.businessKey)) {
          add = false;
        }
      }
      if (add) {
        response.push(current);
        return response;
      }
      return response;
    }, []);
    return distnctBusinessKey;
  };

  const distinctA = distinctArr();

  return (
    <>
      {show && (
        <Modal
          className={styles.distribution}
          visible={true}
          width={1300}
          onOk={auth}
          maskClosable={false}
          onCancel={changeShow}
          {...propsDiy.ModalProps}
        >
          <div className={styles.modalContent}>
            <div className={styles.one} style={{ border: 'none' }}>
              <div>
                <Input
                  {...propsDiy.firstSearchProps.inputProps}
                  value={searchKey}
                  onChange={e => setSearchKey(e.target.value)}
                />
                <div className={styles.options}>
                  <Button className={styles.search} onClick={search}>
                    搜索
                  </Button>
                  <Button className={styles.clear} onClick={clear}>
                    清空
                  </Button>
                </div>
                <div>
                  <div className={styles.search_option}>搜索选项</div>
                  <Checkbox onChange={changeJqpp} checked={jqpp}>
                    精确匹配
                  </Checkbox>
                </div>
                <div className={styles.result}>
                  <div>{propsDiy.firstSearchProps.searchResultTitle}</div>
                  <div className={styles.search}>
                    {searchResult.length > 0 ? (
                      <div className={styles.search_result}>
                        {searchResult
                          ?.filter(g => {
                            return g.isSelect;
                          })
                          .map(x => {
                            return (
                              <div
                                key={x.businessKey}
                                onClick={
                                  sgUserIds.includes(x.businessKey) || !x.isSelect
                                    ? null
                                    : () => selectUser(x)
                                }
                              >
                                <span style={{ color: sgUserIds.includes(x.businessKey) && 'red' }}>
                                  {x.businessName}
                                </span>
                              </div>
                            );
                          })}
                      </div>
                    ) : (
                      <div className={styles.search_no_result}>无搜索结果</div>
                    )}
                  </div>
                </div>
              </div>
            </div>
            <div className={styles.one}>
              <div className={styles.one_title}>{propsDiy.secondTreeProps.title}</div>
              {authInstitutionInfo && Array.isArray(authInstitutionInfo) ? (
                <Tree
                  treeData={authInstitutionInfo}
                  checkable={true}
                  onSelect={searchById}
                  className={styles.treeDiv}
                  defaultExpandedKeys={['0000']}
                  checkedKeys={checkedList.map(g => g.businessKey)}
                  onCheck={changeTreeCheck}
                />
              ) : (
                <div className={styles.no_result}>
                  <Spin spinning={true} tip={propsDiy.secondTreeProps.loadingTreeDataMessage}
                        size="large"/>
                </div>
              )}
            </div>
            <div className={styles.one}>
              <div className={styles.one_title}>
                {propsDiy.thirdDetailListProps.title}
              </div>
              <div className={styles.list_content}>
                {detailList.length > 0 ? (
                  <div className={styles.search_result}>
                    {detailList?.filter(g => {
                      return g.isSelect;
                    })
                      .map(x => {
                        return (
                          <div
                            key={x.businessKey}
                            onClick={sgUserIds.includes(x.businessKey) ? null : () => selectUser(x)}
                          >
                            <span
                              style={
                                !x.isSelect
                                  ? {
                                    cursor: 'not-allowed',
                                    fontWeight: 'normal',
                                  }
                                  : {
                                    color: sgUserIds.includes(x.businessKey) && 'red',
                                  }
                              }
                            >
                              {x.businessName}
                            </span>
                          </div>
                        );
                      })}
                  </div>
                ) : (
                  <div
                    className={styles.no_result}>{propsDiy.thirdDetailListProps.emptyMessage}</div>
                )}
              </div>
            </div>
            <div className={styles.one}>
              <div className={styles.one_title}>{propsDiy.fourRangeProps.title}</div>
              <div className={styles.list_content}>
                {distinctA.length ? (
                  <div className={styles.search_result}>
                    {distinctA.map((x, index) => {
                      return (
                        <div
                          key={x.businessKey}
                          className={styles.selectSg}
                          style={{
                            backgroundColor: colorTranslate(x),
                          }}
                        >
                          <div className={styles.oneSelectedInfo}>
                            <Icon
                              type="delete"
                              style={{ marginRight: '5px' }}
                              onClick={e => deleteSg(x, index, e)}
                            />
                            {x.businessName}
                            {/*<Tooltip title={x.businessName}>*/}
                            {/*  {x.businessName}*/}
                            {/*</Tooltip>*/}
                          </div>
                        </div>
                      );
                    })}
                  </div>
                ) : (
                  <div className={styles.no_result}>{propsDiy.fourRangeProps.emptyMessage}</div>
                )}
              </div>
            </div>
          </div>
        </Modal>
      )}
    </>
  );
}
