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 {getShopInfo, getUserInfo, getWxOpenId} from "@/api/layout";
import {TenantId} from "@/config/app";
import {getOrganization} from "@/api/system/organization";
import {myUserVerify} from "@/api/system/userVerify";
import {CmsWebsite} from "@/api/cms/cmsWebsite/model";
import {User} from "@/api/system/user/model";
import MySearch from "./MySearch";
import './Header.scss';

const Header = (props: any) => {
  const [userInfo, setUserInfo] = useState<User>()
  const [IsLogin, setIsLogin] = useState<boolean>(true)
  const [config, setConfig] = useState<CmsWebsite>()
  const [showBasic, setShowBasic] = useState(false)
  const [statusBarHeight, setStatusBarHeight] = useState<number>()

  const reload = async () => {
    Taro.getSystemInfo({
      success: (res) => {
        setStatusBarHeight(res.statusBarHeight)
      },
    })
    // 获取站点信息
    getShopInfo().then((data) => {
      setConfig(data);
      console.log(userInfo)
    })
    // 获取用户信息
    getUserInfo().then((data) => {
      if (data) {
        setIsLogin(true);
        setUserInfo(data)
        console.log('用户信息>>>', data.phone)
        // 保存userId
        Taro.setStorageSync('UserId', data.userId)
        // 获取openId
        if (!data.openid) {
          Taro.login({
            success: (res) => {
              getWxOpenId({code: res.code}).then(() => {
              })
            }
          })
        }
        // 是否已认证
        if (data.certification) {
          Taro.setStorageSync('Certification', '1')
        }
        // 机构ID
        Taro.setStorageSync('OrganizationId', data.organizationId)
        // 父级机构ID
        if (Number(data.organizationId) > 0) {
          getOrganization(Number(data.organizationId)).then(res => {
            Taro.setStorageSync('OrganizationParentId', res.parentId)
          })
        }
        // 管理员
        const isKdy = data.roles?.findIndex(item => item.roleCode == 'admin')
        if (isKdy != -1) {
          Taro.setStorageSync('RoleName', '管理')
          Taro.setStorageSync('RoleCode', 'admin')
          return false;
        }
        // 注册用户
        const isUser = data.roles?.findIndex(item => item.roleCode == 'user')
        if (isUser != -1) {
          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) {
              if (res.data.code == 1) {
                Taro.showToast({
                  title: res.data.message,
                  icon: 'error',
                  duration: 2000
                })
                return false;
              }
              // 登录成功
              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().then()
  }, [])

  return (
    <>
      <div className={'fixed top-0 header-bg'} style={{
        height: !props.stickyStatus ? '180px' : '148px',
      }}>
        <MySearch/>
        {/*{!props.stickyStatus && <MySearch done={reload}/>}*/}
      </div>
      <NavBar
        style={{marginTop: `${statusBarHeight}px`, marginBottom: '0px', backgroundColor: 'transparent'}}
        onBackClick={() => {
        }}
        left={
          !IsLogin ? (
            <div style={{display: 'flex', alignItems: 'center'}}>
              <Button style={{color: '#000'}} open-type="getPhoneNumber" onGetPhoneNumber={handleGetPhoneNumber}>
                <Space>
                  <Avatar
                    size="22"
                    src={config?.websiteLogo}
                  />
                  <span style={{color: '#000'}}>{config?.websiteName}</span>
                </Space>
              </Button>
              <TriangleDown size={9}/>
            </div>
          ) : (
            <div style={{display: 'flex', alignItems: 'center', gap: '8px'}}>
              <Avatar
                size="22"
                src={config?.websiteLogo}
              />
              <span className={'text-white'}>{config?.websiteName}</span>
              <TriangleDown className={'text-white'} 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
