import {useEffect, useState} from "react";
import Taro from '@tarojs/taro';
import {Button, Space} from '@nutui/nutui-react-taro'
import {TriangleDown} from '@nutui/icons-react-taro'
import {Popup, Avatar, NavBar} from '@nutui/nutui-react-taro'
import {getUserInfo} from "@/api/layout";
import {TenantId} from "@/utils/config";
import {getOrganization} from "@/api/system/organization";
import {myUserVerify} from "@/api/system/userVerify";

const Header = (props: any) => {
  const [IsLogin, setIsLogin] = useState<boolean>(true)
  const [showBasic, setShowBasic] = useState(false)
  const [statusBarHeight, setStatusBarHeight] = useState<number>()
  const [roleName, setRoleName] = useState<string>()

  const onNav = () => {
    if (!IsLogin) {

      return false;
    }
    Taro.switchTab({
      url: '/pages/user/user',
    })
  }
  const reload = () => {
    Taro.getSystemInfo({
      success: (res) => {
        setStatusBarHeight(res.statusBarHeight)
      },
    })
    getUserInfo().then( async (data) => {
      if (data) {
        console.log(data.organizationName,'0000')
        setIsLogin(true);
        Taro.setStorageSync('UserId', data.userId)
        Taro.setStorageSync('Phone',data.phone)
        // 机构ID
        Taro.setStorageSync('OrganizationId',data.organizationId)
        // 父级机构ID
         await getOrganization(Number(data.organizationId)).then(res => {
          Taro.setStorageSync('OrganizationParentId',res.parentId)
        })
        // 所属站点名称
        if(data.organizationName){
          Taro.setStorageSync('OrganizationName',data.organizationName)
        }
        // 是否已认证
        if(data.certification){
          Taro.setStorageSync('Certification','1')
        }
        // 安装人员
        const isInstaller = data.roles?.findIndex(item => item.roleCode == 'Installer')
        if(isInstaller != -1){
          setRoleName('安装人员')
          Taro.setStorageSync('RoleName', '安装人员')
          Taro.setStorageSync('RoleCode', 'Installer')
          return false;
        }
        // 管理员
        const isKdy = data.roles?.findIndex(item => item.roleCode == 'admin')
        if(isKdy != -1){
          setRoleName('管理员')
          Taro.setStorageSync('RoleName', '管理')
          Taro.setStorageSync('RoleCode', 'admin')
          return false;
        }
        // 交警
        const isJj = data.roles?.findIndex(item => item.roleCode == 'jiaojing')
        if(isJj != -1){
          setRoleName('交警')
          Taro.setStorageSync('RoleName', '交警')
          Taro.setStorageSync('RoleCode', 'jiaojing')
          Taro.setStorageSync('Certification', 'jj')
          return false;
        }
        // 邮政协会/管局
        const isYz = data.roles?.findIndex(item => item.roleCode == 'youzheng')
        if(isYz != -1){
          setRoleName('邮政协会/管局')
          Taro.setStorageSync('RoleName', '邮政协会/管局')
          Taro.setStorageSync('RoleCode', 'youzheng')
          Taro.setStorageSync('Certification', 'yz')
          return false;
        }
        // 快递公司
        const isKd = data.roles?.findIndex(item => item.roleCode == 'kuaidi')
        if(isKd != -1){
          setRoleName('快递公司')
          Taro.setStorageSync('RoleName', '快递公司')
          Taro.setStorageSync('RoleCode', 'kuaidi')
          return false;
        }
        const isZD = data.roles?.findIndex(item => item.roleCode == 'zhandian')
        if(isZD != -1){
          setRoleName('快递站点')
          Taro.setStorageSync('RoleName', '快递站点')
          Taro.setStorageSync('RoleCode', 'zhandian')
        }
        // 快递员
        const isKdyy = data.roles?.findIndex(item => item.roleCode == 'kuaidiyuan')
        if(isKdyy != -1){
          setRoleName('快递员')
          Taro.setStorageSync('RoleName', '快递员')
          Taro.setStorageSync('RoleCode', 'kuaidiyuan')
          return false;
        }
        // 注册用户
        const isUser = data.roles?.findIndex(item => item.roleCode == 'user')
        if(isUser != -1){
          setRoleName('注册用户')
          Taro.setStorageSync('RoleName', '注册用户')
          Taro.setStorageSync('RoleCode', 'user')
          return false;
        }
      }
    }).catch(() => {
      setIsLogin(false);
      console.log('未登录')
    });
    myUserVerify({status: 1}).then(data => {
      if(data?.realName){
        Taro.setStorageSync('RealName',data.realName)
      }
    })
  }

  /* 获取用户手机号 */
  const handleGetPhoneNumber = ({detail}) => {
    const {code, encryptedData, iv} = detail
    Taro.login({
      success: function () {
        if (code) {
          Taro.request({
            url: 'https://server.websoft.top/api/wx-login/loginByMpWxPhone',
            method: 'POST',
            data: {
              code,
              encryptedData,
              iv,
              notVerifyPhone: true,
              refereeId: 0,
              sceneType: 'save_referee',
              tenantId: TenantId
            },
            header: {
              'content-type': 'application/json',
              TenantId
            },
            success: function (res) {
              Taro.setStorageSync('access_token', res.data.data.access_token)
              Taro.setStorageSync('UserId', res.data.data.user.userId)
              setIsLogin(true)
              // 重新加载小程序
              Taro.reLaunch({
                url: '/pages/index/index'
              })
            }
          })
        } else {
          console.log('登录失败！')
        }
      }
    })
  }

  useEffect(() => {
    reload()
  }, [])

  return (
    <>
      <NavBar
        fixed={true}
        style={{marginTop: `${statusBarHeight}px`, backgroundColor: 'transparent'}}
        onBackClick={() => {
        }}
        left={
          !IsLogin ? (
            <div style={{display: 'flex', alignItems: 'center'}} onClick={() => Taro.navigateTo({url: '/passport/wxLogin'})}>
              <Space>
                <Avatar
                  size="22"
                  src={props.user?.avatar}
                />
                <span style={{color: '#000'}}>{props.user?.nickname}</span>
              </Space>
              <TriangleDown size={9}/>
            </div>
          ) : (
            <div style={{display: 'flex', alignItems: 'center', gap: '8px'}} onClick={onNav}>
              <Avatar
                size="22"
                src={props.user?.avatar}
              />
              {props.user?.nickname}{roleName && <span>({roleName})</span>}
              <TriangleDown size={9}/>
            </div>
          )}>
      </NavBar>
      <Popup
        visible={showBasic}
        position="bottom"
        style={{width: '100%', height: '100%'}}
        onClose={() => {
          setShowBasic(false)
        }}
      >
        <div style={{padding: '12px 0', fontWeight: 'bold', textAlign: 'center'}}>车辆信息</div>
      </Popup>
    </>
  )
}
export default Header
