import { useState, useEffect, useRef } from 'react';
import type { RequestConfig } from "@umijs/max";
import { Layout, Modal, Dropdown, Image, Flex, Col, ConfigProvider, Button, Space } from "antd";
import { HomeOutlined, LogoutOutlined, FileTextOutlined } from '@ant-design/icons';
import { baseUrl } from './constants/index'
import routes from '../config/routes'
import { history, useModel, Link } from '@umijs/max';
import { filterRoutesByAccess, findAccessIndex } from './utils/RouteHelper'

import LoginIndex from '@/components/Login/Index/index'
import FooterIndex from '@/components/Common/Footer/index'



export async function getInitialState(): Promise<{ permissions: object }> {
  const role = localStorage.getItem('role');
  let permissions = {}
  switch (role) {
    case 'personal':
      permissions = {
        managejobseeker: true,
        managejobseekerhome: true,
        managejobseekerresume: true,
        managejobseekerdetail: true,
        managejobseekerrecommend: true,
        managejobseekerresetting: true,
        talentjobdetail: true,
        talentCompanydetail: true, talentResumedetail: true, talentfairdetail: true, talentinformationdetail: true
      }
      break;
    case 'company':
      permissions = {
        company: true,
        companyhome: true,
        companydepartment: true,
        companypost: true,
        companyresume: true,
        companysearch: true,
        companyfair: true,
        companysetting: true,
        talentjobdetail: true,
        talentCompanydetail: true, talentResumedetail: true, talentfairdetail: true, talentinformationdetail: true
      }
      break;
    default:
      permissions = {
        talent: true,
        talenthome: true,
        talentsearch: true,
        talentfair: true,
        talentinformation: true,
        talentdownload: true,
        talentabout: true,
        talentjobdetail: true,
        talentCompanydetail: true, talentResumedetail: true, talentfairdetail: true, talentinformationdetail: true,
        sciencetechnologypark: true,
        sciencetechnologyparkhome: true,
        sciencetechnologyparkabout: true,
        sciencetechnologyparknews: true,
        sciencetechnologyparkcompany: true,
        sciencetechnologyparknotice: true,
        sciencetechnologyparkconversion: true,
        sciencetechnologyparkactivity: true,
        sciencetechnologyparkconstruct: true,
        sciencetechnologyparkpartymembercenter: true,
        partner: true,

      }
  };

  return { permissions };
}



export const layout = () => {
  const [openPreview, setOpenPreview] = useState(false);
  const { initialState, loading, error, refresh, setInitialState } = useModel('@@initialState');

  return {
    title: '菊城人才网',
    logo: '/images/onlylogo.jpg',
    headerTitleRender: (logo, title, props) => {
      return (
        <>
          <div style={{ cursor: 'pointer' }} onClick={() => {
            localStorage.setItem('role', 'common')
            history.replace('/talent/home');
            window.location.reload()
          }
          }>
            <Flex align='center' >
              {logo}
              <div style={{ margin: '0 40px 0 8px', fontSize: 18, color: '#000000' }}>菊城人才网</div>
            </Flex>
          </div>

        </>
      );
    },
    menuRender: false,
    layout: 'top',
    token: {
      pageContainer: {
        paddingBlockPageContainerContent: 40,
        paddingInlinePageContainerContent: 314,
        colorBgPageContainer: '#f5f5f5'

      },
      header: {
        colorTextMenuSelected: '#19be6e',
        heightLayoutHeader: 90,

      },
    },
    onPageChange: (location) => {
      const role = localStorage.getItem('role');
      switch (role) {
        case 'personal':
          setInitialState((s) => ({
            ...s,
            permissions: {
              managejobseeker: true,
              managejobseekerhome: true,
              managejobseekerdetail: true,
              managejobseekerresume: true,
              managejobseekerrecommend: true,
              managejobseekerresetting: true,
              talentjobdetail: true,
              talentCompanydetail: true, talentResumedetail: true, talentfairdetail: true, talentinformationdetail: true
            },
          }));
          break;
        case 'company':
          setInitialState((s) => ({
            ...s,
            permissions: {
              managecompany: true,
              managecompanyhome: true,
              managecompanypost: true,
              managecompanyresume: true,
              managecompanyrecommend: true,
              managecompanyinfo: true,
              managecompanydepartment: true,
              managecompanyfair: true,
              managecompanysetting: true,
              talentjobdetail: true,
              talentCompanydetail: true, talentResumedetail: true, talentfairdetail: true, talentinformationdetail: true
            },
          }));
          break;
        default:
          setInitialState((s) => ({
            ...s,
            permissions: {
              talent: true,
              talenthome: true,
              talentsearchjob: true,
              talentsearchcompany: true,
              talentfair: true,
              talentinformation: true,
              talentdownload: true,
              talentabout: true,
              talentjobdetail: true,
              talentCompanydetail: true, talentResumedetail: true, talentfairdetail: true, talentinformationdetail: true,
              sciencetechnologypark: true,
              sciencetechnologyparkhome: true,
              sciencetechnologyparkabout: true,
              sciencetechnologyparknews: true,
              sciencetechnologyparkcompany: true,
              sciencetechnologyparknotice: true,
              sciencetechnologyparkconversion: true,
              sciencetechnologyparkactivity: true,
              sciencetechnologyparkconstruct: true,
              sciencetechnologyparkpartymembercenter: true,
              sciencetechnologyparkformationdetail: true,
              partner: true,
            },
          }));

      }
    },
    menuDataRender: () => {
      if (localStorage.getItem('path') == '/talent/search/job' ||
        localStorage.getItem('path') == '/talent/search/company' ||
        localStorage.getItem('path') == '/talent/home' ||
        localStorage.getItem('path') == '/talent/fair' ||
        localStorage.getItem('path') == '/talent/information' ||
        localStorage.getItem('path') == '/talent/about') {
        localStorage.setItem('role', 'common')
      }
      if (localStorage.getItem('path') == '/manage/jobseeker/resume' ||
        localStorage.getItem('path') == '/manage/jobseeker/home' ||
        localStorage.getItem('path') == '/manage/jobseeker/recommend' ||
        localStorage.getItem('path') == '/manage/jobseeker/setting') {
        localStorage.setItem('role', 'personal')
      }
      if (localStorage.getItem('path') == '/manage/company/home' ||
        localStorage.getItem('path') == '/manage/company/info' ||
        localStorage.getItem('path') == '/manage/company/post' ||
        localStorage.getItem('path') == '/manage/company/resume' ||
        localStorage.getItem('path') == '/manage/company/recommend' ||
        localStorage.getItem('path') == '/manage/company/department' ||
        localStorage.getItem('path') == '/manage/company/fair' ||
        localStorage.getItem('path') == '/manage/company/setting'
      ) {
        localStorage.setItem('role', 'company')
      }

      const role = localStorage.getItem('role');
      switch (role) {
        case 'personal':
          routes[4].flatMenu = true;
          setInitialState((s) => ({
            ...s,
            permissions: {
              managejobseeker: true,
              managejobseekerhome: true,
              managejobseekerresume: true,
              managejobseekerrecommend: true,
              managejobseekerresetting: true,
              talentjobdetail: true,
              talentCompanydetail: true, talentResumedetail: true, talentfairdetail: true, talentinformationdetail: true
            }
          }));
          return [routes[4]]

        case 'company':
          routes[5].flatMenu = true;
          setInitialState((s) => ({
            ...s,
            permissions: {
              managecompany: true,
              managecompanyhome: true,
              managecompanypost: true,
              managecompanyresume: true,
              managecompanyrecommend: true,
              managecompanyinfo: true,
              managecompanydepartment: true,
              managecompanysetting: true,
              talentjobdetail: true,
              talentCompanydetail: true, talentResumedetail: true, talentfairdetail: true, talentinformationdetail: true
            },
          }));
          return [routes[5]]
        default:
          setInitialState((s) => ({
            ...s,
            permissions: {
              talent: true,
              talenthome: true,
              talentsearch: true,
              talentfair: true,
              talentinformation: true,
              talentdownload: true,
              talentabout: true,
              talentjobdetail: true,
              talentCompanydetail: true, talentResumedetail: true, talentfairdetail: true, talentinformationdetail: true,
              sciencetechnologypark: true,
              sciencetechnologyparkhome: true,
              sciencetechnologyparkabout: true,
              sciencetechnologyparknews: true,
              sciencetechnologyparkcompany: true,
              sciencetechnologyparknotice: true,
              sciencetechnologyparkconversion: true,
              sciencetechnologyparkactivity: true,
              sciencetechnologyparkconstruct: true,
              sciencetechnologyparkpartymembercenter: true,
              sciencetechnologyparkformationdetail: true,
              partner: true,
            },
          }));
          if (localStorage.getItem('idx') != null && localStorage.getItem('idx') != '-1') {
            let idx = localStorage.getItem('idx')
            if (Number(idx) == 1) {
              routes[Number(idx)].flatMenu = true;
              routes[2].flatMenu = false;
            }
            if (Number(idx) == 2) {
              routes[Number(idx)].flatMenu = true;
              routes[1].flatMenu = false;
            }
            if (Number(idx) == 3) {
              routes[2].flatMenu = true;
            }
          } else {
            routes[1].flatMenu = false;
            routes[2].flatMenu = true;
          }
          return [routes[0], routes[1], routes[2], routes[3]]
        // return [routes[0], routes[3]]


      }
    },
    footerRender: () => {
      return (<>
        <ConfigProvider theme={{
          components: {
            Layout: {
              footerPadding: 0
            },
          },
        }}>
          <Layout.Footer style={{ background: '#f0f2f5' }} id='about'>
            <FooterIndex></FooterIndex>
          </Layout.Footer>
        </ConfigProvider>

      </>)
    },
    avatarProps: {
      src: 'https://gw.alipayobjects.com/zos/antfincdn/efFD%24IOql2/weixintupian_20170331104822.jpg',
      size: 'small',
      title: '王二狗',
      render: (props, dom) => {
        let roleItem: any = []
        if (localStorage.getItem('companyid')) {
          roleItem = [
            {
              key: 'company',
              icon: <FileTextOutlined />,
              label: '企业中心',
            },
            {
              key: 'talent',
              icon: <HomeOutlined />,
              label: '求职首页',
            },
            {
              key: 'logout',
              icon: <LogoutOutlined />,
              label: '退出登录',
            }
          ]
        } else {
          roleItem = [
            {
              key: 'resume',
              icon: <FileTextOutlined />,
              label: '我的简历',
            },
            {
              key: 'talent',
              icon: <HomeOutlined />,
              label: '求职首页',
            },
            {
              key: 'logout',
              icon: <LogoutOutlined />,
              label: '退出登录',
            }
          ]
        }

        return (
          <>
            {
              localStorage.getItem('token') ? <Dropdown
                menu={{
                  items: roleItem,
                  onClick: ({ key }) => {
                    console.log(key);
                    switch (key) {
                      case 'resume':
                        localStorage.setItem('role', 'personal')
                        history.replace('/manage/jobseeker/home');
                        window.location.reload()
                        break;
                      case 'company':
                        localStorage.setItem('role', 'company')
                        history.replace('/manage/company/home');
                        window.location.reload()
                        break;
                      case 'talent':
                        localStorage.setItem('role', 'common')
                        history.replace('/talent/home');
                        window.location.reload()
                        break;
                      case 'logout':
                        localStorage.clear();
                        localStorage.setItem('role', 'common')
                        history.replace('/');
                        window.location.reload()
                        break;
                    }
                  }
                }}
              >
                {dom}
              </Dropdown> : <Button onClick={() => {
                setOpenPreview(true)
              }}>登录</Button>
            }

            {/* 登录 */}
            <Modal
              open={openPreview}
              centered
              footer={null}
              onCancel={() => setOpenPreview(false)}
              destroyOnClose
              maskClosable={false}
              style={{ minWidth: 540 }}
            >
              <LoginIndex type={''} loginChangeStatus={(isLogin: boolean) => {
                console.log(isLogin)
                setOpenPreview(isLogin)
              }}></LoginIndex>
            </Modal>
          </>
        );
      }
    }
  };
};

export const onRouteChange = ({ location }) => {
  localStorage.setItem('path', location.pathname)
  let routes_idx = findAccessIndex(routes, location?.pathname)
  if (routes_idx) {
    localStorage.setItem('idx', routes_idx.parentIndex.toString())
  }
}


export const request: RequestConfig = {
  baseURL: baseUrl,
  errorConfig: {
    // 错误抛出
    errorThrower: (res) => {
      const { success, data, errorCode, errorMessage, showType } = res;
      if (!success) {

      }
    },
  },
  // 配置请求头
  requestInterceptors: [
    (config: object) => {
      // 拦截请求配置，进行个性化处理。
      const token = localStorage.getItem('token');
      if (token) {
        config.headers.Authorization = `${token}`;
      }
      return config;
    },
  ],
  // 配置响应拦截
  responseInterceptors: [
    (response) => {
      const msgModel = (val: String, code: number) => {
        Modal.error({
          title: val,
          centered: true
        });
      }
      // 拦截响应数据，进行个性化处理
      const { data } = response;
      switch (data.code) {
        case -1:
          msgModel(data.msg, data.code)
          break;
        case 0:
          break;
        case 1:
          return response;
          break;
        case 401:
          msgModel(data.msg, data.code)
          localStorage.clear();
          history.push('/talent/home');
          window.location.reload()
          break;
        case 403:
          msgModel(data.msg, data.code)
          break;
        case 404:
          break;
        case 600:
          if (data.errors && Object.keys(data.errors).length > 0) {
            msgModel(data.errors, data.code)
          } else {
            msgModel(data.msg, data.code)
          }
        case 601:
          if (data.errors && Object.keys(data.errors).length > 0) {
            msgModel(data.errors, data.code)
          } else {
            msgModel(data.msg, data.code)
          }
        default:

      }
      return response;
    }
  ]
}



