import {Button} from '@nutui/nutui-react-taro'
import {Avatar, Tag, Space} from '@nutui/nutui-react-taro'
import {getUserInfo, getWxOpenId} from '@/api/layout';
import Taro from '@tarojs/taro';
import {useEffect, useState} from "react";
import {User} from "@/api/system/user/model";
import navTo from "@/utils/common";
import {TenantId} from "@/utils/config";

function UserCard() {
  const [IsLogin, setIsLogin] = useState<boolean>(false)
  const [userInfo, setUserInfo] = useState<User>()
  const [roleName, setRoleName] = useState<string>('注册用户')


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

  const reload = () => {
    Taro.getUserInfo({
      success: (res) => {
        const avatar = res.userInfo.avatarUrl;
        setUserInfo({
          avatar,
          nickname: res.userInfo.nickName,
          sexName: res.userInfo.gender == 1 ? '男' : '女'
        })
        getUserInfo().then((data) => {
          if (data) {
            setUserInfo(data)
            setIsLogin(true);
            Taro.setStorageSync('UserId', data.userId)
            // 获取openId
            if (!data.openid) {
              Taro.login({
                success: (res) => {
                  getWxOpenId({code: res.code}).then(() => {
                  })
                }
              })
            }
            // 判断身份
            const roleName = Taro.getStorageSync('RoleName');
            if(roleName){
              setRoleName(roleName)
            }
          }
        }).catch(() => {
          console.log('未登录')
        });
      }
    });
  };

  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}) => {
    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)
              setUserInfo(res.data.data.user)
              setIsLogin(true)
            }
          })
        } else {
          console.log('登录失败！')
        }
      }
    })
  }

  return (
    <>
      <div className={'p-4'}>
        <div
          className={'user-card w-full bg-blue-900 flex flex-col justify-center rounded-xl'}
          style={{
            background: 'linear-gradient(to bottom, #e1dfff, #f3f2f7)', // 这种情况建议使用类名来控制样式（引入外联样式）
            // width: '720rpx',
            // margin: '10px auto 0px auto',
            height: '144px',
            // borderRadius: '22px 22px 0 0',
          }}
        >
          <div className={'user-card-header flex w-full justify-between items-center'}>
            <div className={'flex items-center mx-4'}>
              {
                IsLogin ? (
                  <Avatar size="large" src={userInfo?.avatar} shape="round"/>
                ) : (
                  <div onClick={() => Taro.navigateTo({url: '/passport/wxLogin'})}>
                    <Avatar size="large" src={userInfo?.avatar} shape="round"/>
                  </div>
                )
              }
              <div className={'user-info flex flex-col px-2'}>
                <div className={'py-1 text-black font-bold'}>{IsLogin ? userInfo?.mobile : '请点击头像登录'}</div>
                {IsLogin ? (
                  <Space className={'grade text-xs py-1'}>
                    <Tag type="success" round>
                      <div className={'p-1'}>{roleName || '注册用户'}</div>
                    </Tag>
                    {/*{*/}
                    {/*  userInfo?.organizationName && (*/}
                    {/*    <Tag type="warning" round>*/}
                    {/*      <div className={'p-1'}>{userInfo?.organizationName}</div>*/}
                    {/*    </Tag>*/}
                    {/*  )*/}
                    {/*}*/}
                  </Space>
                ) : ''}
              </div>
            </div>
            <div className={'mx-4 text-sm px-3 py-1 text-black border-gray-400 border-solid border-2 rounded-3xl'}
                 onClick={() => navTo('/user/profile/profile', true)}>
              {'个人资料'}
            </div>
          </div>
        </div>
      </div>
    </>

  )
}

export default UserCard;
