import {Avatar, Button, Tag} from '@nutui/nutui-react-taro'
import {View} from '@tarojs/components'
import {Scan} from '@nutui/icons-react-taro';
import {getWxOpenId} from '@/api/layout';
import Taro from '@tarojs/taro';
import {useEffect} from "react";
import navTo from "@/utils/common";
import {TenantId} from "@/config/app";
import {useUser} from "@/hooks/useUser";

function UserCard() {
  const {
    user,
    isAdmin,
    isLoggedIn,
    loginUser,
    fetchUserInfo,
    getDisplayName,
    getRoleName
  } = useUser();

  useEffect(() => {
    // Taro.getSetting：获取用户的当前设置。返回值中只会出现小程序已经向用户请求过的权限。
    Taro.getSetting({
      success: (res) => {
        if (res.authSetting['scope.userInfo']) {
          // 用户已经授权过，可以直接获取用户信息
          console.log('用户已经授权过，可以直接获取用户信息')
          reload();
        } else {
          // 用户未授权，需要弹出授权窗口
          console.log('用户未授权，需要弹出授权窗口')
          showAuthModal();
        }
      }
    });
  }, []);


  const reload = async () => {
    // 如果已登录，获取最新用户信息
    if (isLoggedIn) {
      try {
        const data = await fetchUserInfo();
        if (data) {
          // 获取openId
          if (!data.openid) {
            Taro.login({
              success: (res) => {
                getWxOpenId({code: res.code}).then(() => {
                })
              }
            })
          }
        }
      } catch (error) {
        console.error('获取用户信息失败:', error)
      }
    }
  };

  const showAuthModal = () => {
    Taro.showModal({
      title: '授权提示',
      content: '需要获取您的用户信息',
      confirmText: '去授权',
      cancelText: '取消',
      success: (res) => {
        if (res.confirm) {
          // 用户点击确认，打开授权设置页面
          openSetting();
        }
      }
    });
  };


  const openSetting = () => {
    // Taro.openSetting：调起客户端小程序设置界面，返回用户设置的操作结果。设置界面只会出现小程序已经向用户请求过的权限。
    Taro.openSetting({
      success: (res) => {
        if (res.authSetting['scope.userInfo']) {
          // 用户授权成功，可以获取用户信息
          reload();
        } else {
          // 用户拒绝授权，提示授权失败
          Taro.showToast({
            title: '授权失败',
            icon: 'none'
          });
        }
      }
    });
  };

  /* 获取用户手机号 */
  const handleGetPhoneNumber = ({detail}: { detail: { code?: string, encryptedData?: string, iv?: string } }) => {
    const {code, encryptedData, iv} = detail
    Taro.login({
      success: function (loginRes) {
        if (code) {
          Taro.request({
            url: 'https://server.websoft.top/api/wx-login/loginByMpWxPhone',
            method: 'POST',
            data: {
              authCode: loginRes.code,
              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;
              }
              // 登录成功
              const token = res.data.data.access_token;
              const userData = res.data.data.user;

              // 使用useUser Hook的loginUser方法更新状态
              loginUser(token, userData);

              // 显示登录成功提示
              Taro.showToast({
                title: '登录成功',
                icon: 'success',
                duration: 1500
              })

              // 刷新页面数据
              reload();
            }
          })
        } else {
          console.log('登录失败！')
        }
      }
    })
  }

  return (
    <View className={'header-bg'}>
      <View className={'user-card-wrap'}>
        <View
          className={'w-full flex flex-col justify-around'}
          style={{
            // width: '720rpx',
            // margin: '10px auto 0px auto',
            height: '124px',
            // borderRadius: '22px 22px 0 0',
          }}
        >
          <View className={'user-card-header flex w-full justify-between items-center pt-4'}>
            <View className={'flex items-center mx-4'}>
              {
                isLoggedIn ? (
                  <Avatar size="large" src={user?.avatar} shape="round"/>
                ) : (
                  <Button className={'text-black'} style={{
                    maxWidth: '100px',
                    height: '100%',
                  }} open-type="getPhoneNumber" onGetPhoneNumber={handleGetPhoneNumber}>
                    <Avatar size="large" src={user?.avatar} shape="round"/>
                  </Button>
                )
              }
              <View className={'user-info flex flex-col px-3'}>
                <View className={'user-card__name py-1 font-bold'}>{getDisplayName()}</View>
                {isLoggedIn ? (
                  <View className={'grade text-xs py-0'}>
                    <Tag type="success">{getRoleName()}</Tag>
                  </View>
                ) : ''}
              </View>
            </View>
            <View className={'gap-2 flex items-center'}>
              {isAdmin() && <Scan className={'user-card__scan'} size={24} onClick={() => navTo('/user/store/verification', true)} />}
              <View className={'user-card__profile mr-4 text-sm px-3 py-1'}
                    onClick={() => navTo('/user/profile/profile', true)}>
                {'个人资料'}
              </View>
            </View>
          </View>
        </View>
      </View>
    </View>

  )
}

export default UserCard;
