import React, { useRef, useState, useEffect } from 'react';
import { useHistory } from 'react-router-dom';
import { Button, Divider } from 'antd';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import ProTable from '@ant-design/pro-table';
import { connect } from 'umi';

// data
import { ACCOUNT_MANAGE } from '@/../config/permission.config';
import { getColumns } from './data';
// compoents
import RolePermissionsModal from './components/RolePermissionsModal';
import UpdateStatusModal from './components/UpdateStatusModal';
import ResetPasswordModal from './components/ResetPasswordModal';

// mock
import { getUserList } from '../service';

const Account = props => {
  const { permissions } = props;
  const history = useHistory();
  const actionRef = useRef();
  const formRef = useRef();

  const rolePermissionsModalRef = useRef();
  const updateStatusModalRef = useRef();
  const resetPasswordModal = useRef();

  // 权限控制-新增/修改
  const canEditable = permissions[ACCOUNT_MANAGE.EDITABLE];

  // 获取当前用户组织信息
  const userInfo = JSON.parse(localStorage.getItem('user') || '{}');

  // 临时缓存当前账户的角色id
  const setSelectedRoleIds = roleIds => {
    window.sessionStorage.setItem('_selectedRoleIds', JSON.stringify(roleIds));
  };

  // 清空临时缓存的角色id
  const clearnSelectedRoleIds = () => {
    window.sessionStorage.removeItem('_selectedRoleIds');
  };

  // 新增编辑
  const toUserInfo = ({ id, roles = [] } = {}) => {
    const query = id ? { id } : {};

    if (id) {
      const roleIds = roles.map(role => role.id);
      setSelectedRoleIds(roleIds);
    }
    history.push({
      pathname: '/systemManage/account/userInfo',
      query,
    });
  };

  // 角色权限 modal
  const openRolePermissionsModal = record => {
    rolePermissionsModalRef.current.open(record);
  };

  // 修改状态 modal
  const openUpdateStatusModal = record => {
    updateStatusModalRef.current.open(record);
  };

  // 重置密码 modal
  const openResetPasswordModal = record => {
    resetPasswordModal.current.open(record);
  };

  const reload = () => {
    actionRef.current.reload();
  };

  // 获取列表配置
  const columns = getColumns({
    toUserInfo,
    openRolePermissionsModal,
    openUpdateStatusModal,
    openResetPasswordModal,
    canEditable,
  });

  // 表格属性
  const tableProps = {
    columns,
    rowKey: 'id',
    request: async params => {
      console.log('搜索', params);
      const { current: page, pageSize: size } = params;
      const res = await getUserList({
        page,
        size,
        id: userInfo,
      });
      const { content = [], totalElements } = res.data;
      return {
        data: content,
        success: true,
        total: totalElements,
      };
    },
    toolBarRender: () => {
      // TODO: 权限控制
      if (canEditable) {
        return [
          <Button type="primary" onClick={() => toUserInfo()}>
            新增用户
          </Button>,
        ];
      }
      return [];
    },
  };

  // 搜索属性
  const searchProps = {
    collapsed: false,
    collapseRender: () => null,
  };

  useEffect(() => {
    clearnSelectedRoleIds();
  }, []);

  return (
    <PageHeaderWrapper>
      <ProTable actionRef={actionRef} formRef={formRef} {...tableProps} search={false}></ProTable>

      <RolePermissionsModal ref={rolePermissionsModalRef} />
      <UpdateStatusModal reload={reload} ref={updateStatusModalRef} />
      <ResetPasswordModal reload={reload} ref={resetPasswordModal} />
    </PageHeaderWrapper>
  );
};

export default connect(({ menu }) => ({
  permissions: menu.permissions,
}))(Account);
