import React, { useEffect } from 'react';
import { EnvironmentFilled, LogoutOutlined } from '@ant-design/icons';
import { Button, Dropdown, MenuProps, Modal } from 'antd';
import dayjs from 'dayjs';
import Cookies from 'js-cookie';
import { useRouter } from 'next/router';
import { useDispatch, useSelector } from 'react-redux';
import { CommonAPI } from '@/api';
import { HeaderWrap } from '@/components/layout/header/styled';
import { RootState } from '@/store';
import { AddressState, setAddress } from '@/store/module/address';
import { setGlobalData } from '@/store/module/globalData';
import { setSystem, SystemState } from '@/store/module/system';
import { setUserInfo, UserInfoState } from '@/store/module/userInfo';
import getLocationByIP from '@/utils/getLocationByIP';

const HeaderView: React.FC<{
  placeholder: boolean;
}> = ({ placeholder }) => {
  const token = Cookies.get('SHAREFLY-WEB-TOKEN');
  // 当前的路由数据
  const router = useRouter();
  // store
  const dispatch = useDispatch();
  // system
  const system = useSelector((state: RootState) => state.system) as SystemState;
  // address
  const address = useSelector(
    (state: RootState) => state.address,
  ) as AddressState;
  // userInfo
  const userInfo = useSelector(
    (state: RootState) => state.userInfo,
  ) as UserInfoState;
  // 打开登录弹窗
  const handleLogin = () => {
    dispatch(
      setGlobalData({
        loginModalVisible: true,
      }),
    );
  };
  // 获取用户信息
  const getAccountInfo = async () => {
    if (!system?.token || !token) return;
    const res = await CommonAPI.getAccountInfo();
    if (res && res.code === '200') {
      dispatch(setUserInfo(res.result));
    }
  };
  // 计算天数与当前时间的差值
  const getDiffDay = (date: string) => dayjs().diff(dayjs(date), 'day');
  // 组件挂载
  useEffect(() => {
    // 获取当前地址
    getLocationByIP().then((res) => {
      dispatch(setAddress(res));
    });
  }, []);
  // 当前是否登录
  useEffect(() => {
    if (!system?.token || !token) return;
    getAccountInfo().then();
  }, [system?.token]);
  // 右上角按钮
  const items: MenuProps['items'] = [
    {
      key: '1',
      label: (
        <div style={{ textAlign: 'left', marginBottom: '20px' }}>
          <div style={{ fontWeight: 'bold', marginBottom: '4px' }}>
            用户信息：
          </div>
          <div>昵称：{userInfo?.nickName}</div>
          <div>手机号：{userInfo?.phoneNum}</div>
          <div>来到云享飞 {getDiffDay(userInfo?.createTime)} 天</div>
        </div>
      ),
    },
    {
      key: '0',
      label: (
        <Button
          style={{ color: '#666666' }}
          type="link"
          icon={<LogoutOutlined />}
          onClick={() => {
            Modal.confirm({
              title: '退出登录',
              content: '退出后未保存数据将会丢失，确定登出吗？',
              onOk: () => {
                dispatch(setUserInfo(null));
                dispatch(setSystem({ token: undefined }));
                Cookies.remove('SHAREFLY-TOKEN');
              },
            });
          }}
        >
          退出登录
        </Button>
      ),
    },
  ];
  return (
    <>
      <HeaderWrap
        style={{
          background: placeholder ? '#2A2A2A' : 'rgba(86, 86, 86, 0.25)',
        }}
      >
        <div className="header-wrap">
          <div className="header-location">
            <div className="location-icon">
              <EnvironmentFilled
                style={{ color: '#FF552D', fontSize: '0.86rem' }}
              />
            </div>
            <Button type={'link'} className="location-address">
              {address?.city || '定位中...'}
            </Button>
            <div className="location-hello">Hi，欢迎来到云享飞</div>
          </div>
          <div className="header-nav">
            <div className="nav-tab">
              <Button type={'link'} className="tab-item">
                个人中心
              </Button>
              <Button type={'link'} className="tab-item">
                购物车
              </Button>
              <Button type={'link'} className="tab-item">
                我的订单
              </Button>
              <Button type={'link'} className="tab-item">
                消息
              </Button>
              <Button type={'link'} className="tab-item">
                联系客服
              </Button>
            </div>
            {!!userInfo?.id && (
              <div className="nav-user">
                <Dropdown
                  overlayStyle={{ textAlign: 'center' }}
                  menu={{ items }}
                  placement="bottomRight"
                  arrow
                >
                  <div
                    className="user-avatar"
                    style={{ backgroundImage: `url(${userInfo?.userImg})` }}
                  ></div>
                </Dropdown>
              </div>
            )}
            <div className="nav-action">
              {!userInfo?.id && (
                <Button
                  type={'primary'}
                  className="action-item"
                  onClick={handleLogin}
                >
                  登录
                </Button>
              )}
              <Button type={'primary'} className="action-item">
                发布需求
              </Button>
              <Button type={'primary'} className="action-item">
                加盟入驻
              </Button>
            </div>
          </div>
        </div>
      </HeaderWrap>
      {placeholder && (
        <div
          className="header-wrap"
          style={{ width: '100%', height: '3rem' }}
        ></div>
      )}
    </>
  );
};

export default HeaderView;
