import React from 'react';
import { PageLoading } from '@ant-design/pro-layout';
import { Redirect, connect, ConnectProps, StateType, history, Link } from 'umi';
import { stringify } from 'querystring';
import { ConnectState } from '@/models/connect';
import { CurrentUser } from '@/models/user';
import { getCookie } from '@/utils/method';
import { message } from 'antd';
import moment from 'moment';
import { logOut } from '@/utils/log';

interface SecurityLayoutProps extends ConnectProps {
  loading?: boolean;
  currentUser?: CurrentUser;
  login?: StateType;
}

interface SecurityLayoutState {
  token: String;
  isReady: boolean;
}

class SecurityLayout extends React.Component<SecurityLayoutProps, SecurityLayoutState> {
  state: SecurityLayoutState = {
    isReady: false,
    token: '',
  };

  render() {
    const { children, loading } = this.props;
    // You can replace it to your authentication rule (such as check token exists)
    // 你可以把它替换成你自己的登录认证规则（比如判断 token 是否存在）

    const perList = [
      { key: '1', path: '/UserManagement/LIFEUserManagement' },
      { key: '18', path: '/UserManagement/ServiceProviderManagement' },
      { key: '15', path: '/PropertyManagement' },
      { key: '17', path: '/CommercialService/CommunityMaintenance' },
      { key: '20', path: '/CommercialService/OwnerComplaints' },
      { key: '23', path: '/CommercialService/ProblemFeedback' },
      { key: '26', path: '/CommercialService/RenovationApplication' },
      { key: '29', path: '/CommercialService/AccessCardApplication' },
      { key: '33', path: '/CommercialService/ReportOnline' },
      { key: '36', path: '/CommercialService/ShelfLifeService' },
      // cellee 负责部分
      // 合同
      { key: '39', path: '/ContractManagement' },
      { key: '40', path: '/ContractManagement/Detail' },
      { key: '41', path: '/ContractManagement/Add' },
      { key: '42', path: '/ContractManagement/Edit' },
      // 小区
      { path: '/CommunityManagement/CellList', title: '小区列表', key: '44' },
      { path: '/CommunityManagement/CellList/Detail', title: '查看小区', key: '44' },
      { path: '/CommunityManagement/CellList/Add', title: '编辑小区', key: '45' },
      { path: '/CommunityManagement/CellList/Add', title: '添加小区', key: '46' },
      // 小区公告
      { path: '/CommunityManagement/CommunityAnnouncement', title: '小区公告', key: '48' },
      { path: '/CommunityManagement/CommunityAnnouncement/Detail', title: '查看公告', key: '49' },
      { path: '/CommunityManagement/CommunityAnnouncement/Edit', title: '编辑公告', key: '50' },
      { path: '/CommunityManagement/CommunityAnnouncement/Add', title: '添加公告', key: '51' },
      // 小区设施
      { path: '/CommunityManagement/FacilityBookings', title: '小区设施', key: '52' },
      { path: '/CommunityManagement/FacilityBookings/Detail', title: '查看预约设施', key: '53' },
      { path: '/CommunityManagement/FacilityBookings/Booking', title: '添加预约设施', key: '54' },
      {
        path: '/CommunityManagement/FacilityBookings/FacilityApply',
        title: '添加预约设施',
        key: '54',
      },
      {
        path: '/CommunityManagement/FacilityBookings/FacilityDetail',
        title: '查看设施',
        key: '57',
      },
      { path: '/CommunityManagement/FacilityBookings/FacilityEdit', title: '编辑设施', key: '58' },
      { path: '/CommunityManagement/FacilityBookings/Adding', title: '添加设施', key: '59' },
      // 访客记录
      { path: '/CommunityManagement/VisitorRecord', title: '访客记录', key: '60' },
      // 账号管理
      { path: '/AccountManagement/account', title: '账号管理', key: '62' },
      { path: '/AccountManagement/account/Detail', title: '查看账号', key: '63' },
      { path: '/AccountManagement/account/edit', title: '编辑账号', key: '64' },
      { path: '/AccountManagement/account/Add', title: '添加账号', key: '65' },
    ];

    // 用户重新打开需要重新登录
    let time = localStorage.getItem('loginTime');
    const tokenLogin = time ? JSON.parse(time) : '';

    if (history.location.pathname == '/') {
      // const isLogin = currentUser && currentUser.name;//isLogin为关键点
      var isLogin = false;
      if (getCookie('token').length != 0) {
        isLogin = true;
      }
      const queryString = stringify({
        redirect: window.location.href,
      });
      if (!isLogin && loading) {
        return <PageLoading />;
      }
      if (!isLogin && window.location.pathname !== '/user/login') {
        return <Redirect to={`/user/login?${queryString}`} />;
      }

      return children;
    } else if (tokenLogin && moment().diff(moment(tokenLogin), 'minutes') < 30) {
      // 刷新时间
      localStorage.setItem('loginTime', JSON.stringify(moment().format('YYYY-MM-DD HH:mm:ss')));

      // 在判断权限
      const permission = JSON.parse(localStorage.getItem('permission') || '[]');

      let perObj = perList.filter((obj) => {
        return obj.path === location.pathname;
      });

      if (perObj.length !== 0) {
        if (permission.indexOf(perObj[0].key) < 0) {
          history.push('/403');
        }
      }

      return children;
    } else {
      // 退出登录
      message.warning('Expired login !');
      setTimeout(function () {
        logOut();
      }, 1000);
      return false;
    }
  }
}

export default connect(({ user, loading, login }: ConnectState) => ({
  currentUser: user.currentUser,
  loading: loading.models.user,
  login: login,
}))(SecurityLayout);
