import 'dart:io';

import 'package:flutter/material.dart';
import 'package:flutter_alibc/alibc_model.dart';
import 'package:flutter_alibc/flutter_alibc.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:zhiying_comm/models/profile/profile_model.dart';
import 'package:zhiying_comm/util/taobao/taobao_auth_alert.dart';
import 'package:zhiying_comm/zhiying_comm.dart';
import 'package:provider/provider.dart';

class TaobaoAuth {
  // static ProfileModel _profile;

  // 淘宝授权
  static auth(BuildContext context) async {
    bool isAuth = await TaobaoAuth.isAuth();
    if (isAuth) {
      Fluttertoast.showToast(msg: '你已经授权过了');
      Provider.of<UserInfoNotifier>(context, listen: false).updateUserAuth(true);
      return;
    }

    bool isConfirm = await showDialog(
        context: context,
        builder: (BuildContext context) {
          return TaobaoAuthAlert();
        });
    if (isConfirm != null && isConfirm == true) {
      Map<String, dynamic> data = Map<String, dynamic>.from(await NetUtil.post('/api/v1/taobao/auth', method: NetMethod.GET));
      Logger.debug(data);
      if (data['code'] != 1) {
        return;
      }
      String url = data['data']['redirect_url'];
      print("授权链接" + url);
      TradeResult result;
      if (Platform.isAndroid) {
        result = await FlutterAlibc.openByUrl(url: url, backUrl: "alisdk://", isAuth: true);
      } else if (Platform.isIOS) {
        result = await FlutterAlibc.openByUrl(url: url);
      }
      Logger.log('${result.errorCode}   ${result.errorMessage} ');
      // if(null != result && result.errorCode == '0'){
      //   Provider.of<UserInfoNotifier>(context, listen: false).updateUserAuth(true);
      // }
      await initAuth(context);
    }
  }

  // 返回是否授权
  static Future<bool> isAuth() async {
    // if (_profile != null) {
    //   return _profile.isAuth;
    // }
    try {
      Map<String, dynamic> data = Map<String, dynamic>.from(await NetUtil.post('/api/v1/user/profile', method: NetMethod.GET));
      if (data['code'] == 1) {
        ProfileModel _profile = ProfileModel.fromJson(Map<String, dynamic>.from(data['data']));
        return _profile.isAuth;
      }
    }catch(e, s){
      Logger.error(e, s);
    }
    return false;
  }

  // 返回是否授权
  static void initAuth(BuildContext context) async {
    try {
      Map<String, dynamic> data = Map<String, dynamic>.from(await NetUtil.post('/api/v1/user/profile', method: NetMethod.GET));
      if (data['code'] == 1) {
        ProfileModel model = ProfileModel.fromJson(Map<String, dynamic>.from(data['data']));
        if(null != model && model.isAuth){
          Provider.of<UserInfoNotifier>(context, listen: false).updateUserAuth(true);
        }
      }
    }catch(e, s){
      Logger.error(e, s);
    }

  }

}
