import 'dart:io';

import 'package:flutter/cupertino.dart';
import 'package:flutter_alibc/alibc_model.dart';
import 'package:flutter_alibc/flutter_alibc.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:jdsdk/jdsdk.dart';
import 'package:url_launcher/url_launcher.dart';
import 'package:zhiying_comm/models/user/user_info_model.dart';
import 'package:zhiying_comm/util/dialog/loading/loading.dart';
import 'package:zhiying_comm/util/empty_util.dart';
import 'package:zhiying_comm/util/global_config.dart';
import 'package:zhiying_comm/util/log/let_log.dart';
import 'package:zhiying_comm/util/net_util.dart';
import 'package:zhiying_comm/util/taobao/taobao_auth.dart';
import 'package:zhiying_comm/util/turn_chain/turn_chain_dialog_repository.dart';
import 'package:zhiying_comm/util/turn_chain/turn_chain_style_model.dart';

import '../router_util.dart';
import 'turn_chain_dialog.dart';

class TurnChainUtil {
  ///
  /// 跳转app或者打开url进行领券
  /// userInfoModel: 用户登陆的带有token 与 淘宝是否授权的 model类
  /// provider: 商品的渠道
  /// data: 转链需要的请求参数
  ///
  /// 一些常用的APP的 URL scheme:
  /// 来源：https://blog.csdn.net/jdazy/article/details/79208754
  /// QQ： mqq://
  /// 微信： weixin://
  /// 京东： openapp.jdmobile://
  /// 淘宝： taobao://
  /// 美团： imeituan://
  /// 点评： dianping://
  /// 1号店： wccbyihaodian://
  /// 支付宝： alipay://
  /// 微博： sinaweibo://
  /// 腾讯微博： TencentWeibo://
  /// weico微博： weico://
  /// 知乎： zhihu://
  /// 豆瓣fm： doubanradio://
  /// 网易公开课： ntesopen://
  /// Chrome： googlechrome://
  /// QQ浏览器： mqqbrowser://
  /// uc浏览器： ucbrowser://
  /// 搜狗浏览器： SogouMSE://
  /// 百度地图： baidumap:// bdmap://
  /// 优酷： youku://
  /// 人人： renren://
  /// 我查查： wcc://
  /// 有道词典： yddictproapp://
  /// 微盘： sinavdisk://
  /// 名片全能王： camcard://
  ///
  static Future<void> openReceiveCoupon(BuildContext context, UserInfoModel userInfoModel, String goodsId, String provider, Map<String, dynamic> data) async {
    /// 1、先判断是否登陆
    if (EmptyUtil.isEmpty(userInfoModel) || EmptyUtil.isEmpty(userInfoModel?.token)) {
      RouterUtil.goLogin(context);
      return;
    }

    /// 2、如果是淘宝，判断是否授权
    if (provider == GlobalConfig.PROVIDER_TB && !userInfoModel.isTBAuth) {
      TaobaoAuth.auth(context);
      return;
    }

    /// 3、获取转链，进行跳转
    Map<String, dynamic> result = await getTurnChainResult(context, goodsId, provider, data, isShare: false);
    if (!EmptyUtil.isEmpty(result)) {
      String openAppUrl = result['open_app_url'];
      String appUrl = result['app_url'];
      String webUrl = result['no_open_app_url'];

      /// 4、根据渠道进行不同的跳转
      switch (provider) {
        case GlobalConfig.PROVIDER_TB:
        case GlobalConfig.PROVIDER_TM:
          if (!EmptyUtil.isEmpty(openAppUrl)) {
            TradeResult tradeResult;
            if (Platform.isAndroid) {
              tradeResult = await FlutterAlibc.openByUrl(url: openAppUrl, backUrl: "alisdk://");
            } else if (Platform.isIOS) {
              tradeResult = await FlutterAlibc.openByUrl(url: openAppUrl);
            }
            Logger.debug('taobao result =  ${tradeResult.errorCode}   ${tradeResult.errorMessage} ');
          } else if (!EmptyUtil.isEmpty(webUrl)) {
            RouterUtil.openWebview(webUrl, context);
          } else {
            Fluttertoast.cancel();
            Fluttertoast.showToast(msg: '购买链接不存在');
          }

          break;
        case GlobalConfig.PROVIDER_JD:
          String tempURLScheme1 = 'openapp.jdmobile://virtual?params=%';
          String tempURLScheme2 = 'openapp.jdmobile://';
          if (!EmptyUtil.isEmpty(openAppUrl) && await canLaunch(tempURLScheme1) || await canLaunch(tempURLScheme2)) {
            Jdsdk.openUrl(url: openAppUrl);
          } else if (!EmptyUtil.isEmpty(webUrl)) {
            RouterUtil.openWebview(webUrl, context);
          } else {
            Fluttertoast.cancel();
            Fluttertoast.showToast(msg: '购买链接不存在');
          }
          break;
        case GlobalConfig.PROVIDER_KL:
        case GlobalConfig.PROVIDER_PDD:
        case GlobalConfig.PROVIDER_SN:
        case GlobalConfig.PROVIDER_VIP:
          bool launchable = await canLaunch(appUrl);
          if (Platform.isIOS) {
            launchable = await launch(appUrl);
          }
          if (launchable) {
            if (!Platform.isIOS) {
              await launch(appUrl);
            }
          } else if (!EmptyUtil.isEmpty(webUrl)) {
            Logger.log('打开${provider} webUrl, url = ${webUrl}');
            RouterUtil.openWebview(webUrl, context);
          } else {
            Fluttertoast.cancel();
            Fluttertoast.showToast(msg: '购买链接不存在');
          }
          break;
      }
    } else {
      Fluttertoast.cancel();
      Fluttertoast.showToast(msg: '购买链接不存在');
    }
  }

  ///
  /// 获取分享的转链
  /// userInfoModel: 用户登陆的带有token 与 淘宝是否授权的 model类
  /// provider: 商品的渠道
  /// data: 转链需要的请求参数
  ///
  /// 返回参数: 只需要获取返回结果的 open_app_url 值即可。
  /// 例如: Map<String, dynamic> result = await getShareTurnChain(context, _user, provider, data);
  /// String buyUrl = result['open_app_url']
  ///
  static Future<Map<String, dynamic>> getShareTurnChain(BuildContext context, UserInfoModel userInfoModel, String goodsId, String provider, Map<String, dynamic> data) async {
    /// 1、先判断是否登陆
    if (EmptyUtil.isEmpty(userInfoModel) || EmptyUtil.isEmpty(userInfoModel?.token)) {
      RouterUtil.goLogin(context);
      return null;
    }

    /// 2、如果是淘宝，判断是否授权
    if (provider == GlobalConfig.PROVIDER_TB && !userInfoModel.isTBAuth) {
      TaobaoAuth.auth(context);
      return null;
    }

    /// 3、获取转链的结果
    Map<String, dynamic> result = await getTurnChainResult(context, goodsId, provider, data, isShare: true);
    if (!EmptyUtil.isEmpty(result) && !EmptyUtil.isEmpty(result['open_app_url'])) {
      return result;
    }
    Fluttertoast.cancel();
    Fluttertoast.showToast(msg: '购买链接不存在');
    return null;
  }

  ///
  /// 获取跳转的dialog样式
  ///
  static Future<dynamic> getCacheTurnChainDialogStyle(String goodsId, String provider, String commission, String coupon) async {
    TurnChainDialogRepository repository = TurnChainDialogRepository();
    var result = await repository.fetchCacheData(goodsId, provider, commission, coupon);
    if (!EmptyUtil.isEmpty(result)) {
      return result;
    }
    return null;
  }

  ///
  /// 缓存跳转的dialog样式
  ///
  static Future<bool> cacheTurnChainDialogStyle(String goodsId, String provider, String commission, String coupon) async {
    TurnChainDialogRepository repository = TurnChainDialogRepository();
    bool result = await repository.cacheData(goodsId, provider, commission, coupon);
    return result;
  }

  ///
  /// 接口文档：https://www.showdoc.com.cn/1003739271891029?page_id=5760575662067820
  /// 根据商品id等信息，获取领券或者分享的转链接
  ///
  ///
  static Future<Map<String, dynamic>> getTurnChainResult(BuildContext context, String goodsId, String provider, Map<String, dynamic> data, {bool isShare = false}) async {
    try {
      TurnChainDialogRepository repository = TurnChainDialogRepository();
      if (!EmptyUtil.isEmpty(context) && !EmptyUtil.isEmpty(provider) && !EmptyUtil.isEmpty(data) && !EmptyUtil.isEmpty('gid')) {
        TurnChainStyleModel model = await repository.fetchCacheData(goodsId, provider, data['commission'], data['coupon_price']);
        // 设置是否分享还是转链
        data['is_share'] = isShare ? '1' : '0';
        if (EmptyUtil.isEmpty(model)) {
          // 开启loading
          Loading.show(context);
        } else {
          TurnChainLoading.show(context, model);
        }
        var result = await NetUtil.post('/api/v1/convert/$provider', params: data, method: NetMethod.POST);
        if (EmptyUtil.isEmpty(model)) {
          // 关闭loading
          Loading.dismiss();
        } else {
          TurnChainLoading.dismiss();
        }
        if (NetUtil.isSuccess(result) && !EmptyUtil.isEmpty(result[GlobalConfig.HTTP_RESPONSE_KEY_DATA])) {
          return result[GlobalConfig.HTTP_RESPONSE_KEY_DATA];
        }
      }
    } catch (e, s) {
      Logger.error(e, s);
    }
    return null;
  }
}
