import 'dart:async';

import 'package:flutter/material.dart';
import 'package:sport/utils/toast.dart';
import 'package:tencent_kit/tencent_kit.dart';

typedef QqLogin = void Function(
    TencentLoginResp login, TencentUserInfoResp userInfo);

mixin TencentMixin<T extends StatefulWidget> on State<T> {
  static const String _TENCENT_APPID = '1110701531';

  Tencent _tencent = Tencent()..registerApp(appId: _TENCENT_APPID);

  StreamSubscription<TencentLoginResp> _qqlogin;
  StreamSubscription<TencentShareResp> _qqshare;
  TencentLoginResp _loginResp;

  StreamController<TencentUserInfoResp> _qqloginRespStream;
  StreamSubscription<TencentUserInfoResp> _qqloginRespSubscription;

  void initState() {
    super.initState();
    _qqlogin = _tencent.loginResp().listen(_listenLogin);
    _qqshare = _tencent.shareResp().listen(_listenShare);
  }

  void dispose() {
    _qqlogin?.cancel();
    _qqlogin = null;
    _qqshare?.cancel();
    _qqshare = null;
    _qqloginRespSubscription?.cancel();
    _qqloginRespSubscription = null;
    super.dispose();
  }

  Future<bool> qqSupport() async {
    return await _tencent.isQQInstalled() || await _tencent.isTIMInstalled();
  }

  void qqlogin(QqLogin login) {
    _qqloginRespStream = StreamController<TencentUserInfoResp>();
    _qqloginRespSubscription = _qqloginRespStream.stream.listen((event) {
      login.call(_loginResp, event);
    });
    _tencent?.login(
      scope: <String>[TencentScope.GET_SIMPLE_USERINFO],
    );
  }

  void qqShare(String filePath) async {
    await _tencent.shareImage(
      scene: TencentScene.SCENE_QQ,
      imageUri: Uri.file(filePath),
    );
  }

  void qqShareLink(String url) async{
    await _tencent.shareWebpage(scene: TencentScene.SCENE_QQ, title: "分享页面" ,targetUrl: url);
  }

  void _listenLogin(TencentLoginResp resp) async {
    _loginResp = resp;
    if (_loginResp != null &&
        _loginResp.isSuccessful()&&
        !_loginResp.isExpired()) {
      TencentUserInfoResp userInfo = await _tencent.getUserInfo(
        appId: _TENCENT_APPID,
        openid: _loginResp.openid,
        accessToken: _loginResp.accessToken,
      );
      if (userInfo.isSuccessful()) {
        print(
            '用户信息 ${userInfo.nickname} - ${userInfo.gender} - ${userInfo.genderType} ${userInfo.figureurl1}');
      } else {
        ToastUtil.show("获取用户信息：${userInfo.ret} - ${userInfo.msg}");
      }

      _qqloginRespStream.add(userInfo);
    } else {
      _qqloginRespStream.add(null);
    }
  }

  void _listenShare(TencentShareResp resp) {
    String content = 'share: ${resp.ret} - ${resp.msg}';
    print('分享$content}');
  }
}
