import React, { useState, useEffect, useCallback, useRef } from 'react';
import { FormattedMessage, history, useModel } from 'umi';
import { Spin, Popover, Dropdown, MenuProps } from 'antd';
import styles from './index.less';
import cx from 'classnames';
import PageHeader from '@/sagacare_components/PageHeader';
import Search from '@/sagacare_components/Search';
import Table from '@/sagacare_components/Table';
import Empty from './components/Empty';
import PersonModal from './components/personModal';
import ImportModal from './components/importModal';
import { EllipsisOutlined, InfoCircleOutlined } from '@ant-design/icons';
import Icon from '@/tenants-ui/SgIcon';

import {
  queryUserList,
  queryCompanyOAById,
  queryControlSpaceCompany,
} from '@/services/sagacare_service/member';

const Member: React.FC = () => {
  const { initialState } = useModel('@@initialState');

  const [perVisible, setPerVisible] = useState(false); //人员对话框显示
  const [importVisible, setImportVisible] = useState(false); //人员对话框显示
  const [temporary, setTemporary] = useState(false); //是否是临时成员添加
  const [invalidSign, setInvalidSign] = useState(false); //显示作废
  const [spaceMap, setSpaceMap] = useState<any>();

  const [searchStr, setSearchStr] = useState();
  const [isSyncOa, setIsSyncOa] = useState(true); //是否是OA同步
  const [userList, setUserList] = useState<any>([]);
  const [total, setTotal] = useState();
  const [loading, setLoading] = useState(false);
  const [page, setPage] = useState({
    pageNum: 1,
    pageSize: 10,
  });
  const [checkUser, setCheckUser] = useState({}); //查看的人
  const [checkSign, setCheckSign] = useState('add'); // 三种状态 查看 编辑 新增
  const [refreshNum, setRefreshNum] = useState(0); //刷新列表
  const [showFilterIds, setShowFilterIds] = useState([]);

  // const statusArr = {
  //   2: '正常',
  //   3: '待激活',
  //   5: '已作废',
  // };
  const userTpeyArr = {
    1: '普通成员',
    2: '临时成员',
    3: '管理员',
  };

  const [sorter, setSorter] = useState<any>({
    updateDate: 'DESC', //'ASC' : 'DESC'
  });

  const getColumns = () => {
    return [
      {
        title: '姓名',
        dataIndex: 'name',
        width: 140,
        render: function (content, item, index) {
          return <div>{content}</div>;
        },
      },
      {
        title: '类型',
        dataIndex: 'manageUserType',
        filteredValue: showFilterIds,
        single: false,
        filters: [
          { value: 1, label: '普通成员' },
          { value: 2, label: '临时成员' },
          { value: 3, label: '管理员' },
        ],
        render: function (content, item, index) {
          return <span>{userTpeyArr[content]}</span>;
        },
      },
      {
        title: '手机号',
        dataIndex: 'phone',
      },
      {
        title: '职务',
        dataIndex: 'job',
      },
      {
        title: '常驻工区',
        dataIndex: 'permanentSpaceName',
      },
      {
        title: '可控工区',
        dataIndex: 'isAllControl',
        render: function (content, item, index) {
          return <span>{content ? '部分可控' : '全部可控'}</span>;
        },
      },
      {
        title: '更新时间',
        dataIndex: 'updateDate',
        sorter: true,
        sortered: sorter.updateDate,
      },
      {
        title: '状态',
        dataIndex: 'status',
        render: function (content, item, index) {
          //debugger;
          return (
            <div>
              <span
                className={cx(styles.circle, {
                  [styles.activated]: content == '待激活',
                })}
              ></span>
              <span>{content}</span>
            </div>
          );
        },
      },
      {
        title: '',
        dataIndex: '',
        render: function (content, item) {
          const menuItems: MenuProps['items'] = [
            {
              key: '1',
              label: (
                <div
                  className={styles.operateLi}
                  onClick={() => {
                    checkPerson(item);
                  }}
                >
                  查看
                </div>
              ),
            },
            {
              key: '2',
              label: (
                <div
                  className={styles.operateLi}
                  onClick={() => {
                    editPerson(item);
                  }}
                >
                  编辑
                </div>
              ),
            },
            {
              key: '3',
              label: (
                <div
                  className={cx(styles.operateLi, { [styles.disabled]: item.oaId })}
                  onClick={() => {
                    invalidPerson(item);
                  }}
                >
                  作废
                </div>
              ),
            },
          ];
          return (
            <Dropdown menu={{ items: menuItems }}>
              <EllipsisOutlined style={{ color: '#4D5262', fontSize: '20px' }} />
            </Dropdown>
          );
        },
      },
    ];
  };
  const goToInvalid = () => {
    history.push(`/member/invalid`);
  };
  const refreshList = () => {
    setRefreshNum(refreshNum + 1);
  };
  const onClose = () => {
    setPerVisible(false);
  };

  const onImClose = () => {
    setImportVisible(false);
  };
  const showImport = () => {
    setImportVisible(true);
  };
  useEffect(() => {
    var paramObj = {
      criteria: {
        param: searchStr,
        status: 1,
        companyId: initialState?.currentUser?.companyId,
        // manageUserType: [],
      },
      page: page.pageNum,
      size: page.pageSize,
      orders: [
        {
          column: 'updateDate',
          asc: sorter.updateDate == 'DESC' ? true : false,
        },
      ],
    };
    setLoading(true);
    if (showFilterIds.length > 0) {
      paramObj.criteria = { ...paramObj.criteria, ...{ manageUserType: showFilterIds } };
    }

    queryUserList(paramObj)
      .then((res) => {
        debugger;
        setLoading(false);
        var uarr = res.content || [];
        var count = res.count || 0;
        setUserList(uarr);
        setTotal(count);
      })
      .catch((err) => {
        setLoading(false);
      });
  }, [searchStr, showFilterIds, page, sorter, refreshNum]);

  useEffect(() => {
    //查询受控列表
    var paramObj = {
      criteria: {
        companyId: initialState?.currentUser?.companyId,
      },
    };
    queryControlSpaceCompany(paramObj)
      .then((res) => {
        var data = res.data || {};
        setSpaceMap(data);
      })
      .catch((err) => {});
    queryCompanyOAById({ companyId: initialState?.currentUser?.companyId })
      .then((res) => {
        var isSyncOa = res?.isSyncOa;
        setIsSyncOa(isSyncOa == 1 ? true : false);
      })
      .catch((err) => {});
  }, []);

  const checkPerson = (item) => {
    setPerVisible(true);
    setInvalidSign(false);
    setCheckSign('check'); //设置为查看状态
    setCheckUser(item);
    setTemporary(false);
  };
  const editPerson = (item) => {
    setPerVisible(true);
    setInvalidSign(false);
    setCheckSign('edit');
    setCheckUser(item);
    setTemporary(false);
  };
  //作废用户
  const invalidPerson = (item) => {
    setInvalidSign(true);
    setPerVisible(true);
    setCheckUser(item);
    setTemporary(false);
  };
  //添加临时用户
  const addTemporaryPerson = () => {
    setPerVisible(true);
    setInvalidSign(false);
    setCheckSign('add');
    setCheckUser({});
    setTemporary(true);
  };
  const addNewPerson = () => {
    setPerVisible(true);
    setInvalidSign(false);
    setCheckSign('add');
    setCheckUser({});
    setTemporary(false);
  };

  return (
    <div className={styles.memberwrap}>
      <PageHeader
        title={<FormattedMessage id="menu.member" />}
        action={
          <div className={styles.headerRight}>
            <Search changeSearchStr={setSearchStr} />
            {isSyncOa ? (
              <>
                <div className={styles.allIn}>
                  <InfoCircleOutlined />
                  已开启OA同步
                </div>
                <div
                  className={styles.invalid}
                  onClick={() => {
                    goToInvalid();
                  }}
                >
                  已作废
                </div>
                <div className={styles.addButton} onClick={addTemporaryPerson}>
                  添加临时成员
                </div>
              </>
            ) : (
              <>
                <div className={styles.allIn} onClick={showImport}>
                  <Icon
                    className=""
                    type="import"
                    style={{
                      color: '#4D5262',
                      fontSize: '15px',
                      marginRight: '6px',
                    }}
                  ></Icon>
                  批量导入
                </div>
                <div
                  className={styles.invalid}
                  onClick={() => {
                    goToInvalid();
                  }}
                >
                  <Icon
                    className=""
                    type="cancel"
                    style={{
                      color: '#4D5262',
                      fontSize: '15px',
                      marginRight: '6px',
                    }}
                  ></Icon>
                  已作废
                </div>
                <div className={styles.addButton} onClick={addNewPerson}>
                  新增成员
                </div>
              </>
            )}
          </div>
        }
      />
      <div className={styles.bottomTable}>
        <Table
          columns={getColumns()}
          rowKey="userId"
          dataSource={userList}
          loading={loading}
          page={page}
          total={total}
          pagination={!!userList.length}
          onFilterChange={(key, options) => {
            debugger;
            setShowFilterIds(options);
          }}
          onRowClick={(record) => {}}
          onSortChange={(col: any, direction: string) => {
            setSorter({ [col['dataIndex']]: direction });
          }}
          onPageChange={(p) => {
            setPage(p);
          }}
        />
        {!userList.length && !loading && <Empty />}
      </div>
      {perVisible && (
        <PersonModal
          invalidSign={invalidSign}
          temporary={temporary}
          checkUser={checkUser}
          checkSign={checkSign}
          onClose={onClose}
          setCheckSign={setCheckSign}
          setInvalidSign={setInvalidSign}
          spaceMap={spaceMap}
          refreshList={refreshList}
        ></PersonModal>
      )}
      {importVisible && <ImportModal onClose={onImClose}></ImportModal>}
    </div>
  );
};

export default Member;
