import 'dart:async';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:chat/data/UserData.dart';
import 'package:chat/data/WebData.dart';
import 'package:chat/data/constants.dart';
import 'package:chat/data/conversation.dart';
import 'package:chat/generated/i18n.dart';
import 'package:chat/home/ProfilePage.dart';
import 'package:chat/home/rich_title.dart';
import 'package:chat/utils/CustomUI.dart';
import 'package:chat/utils/HttpUtil.dart';
import 'package:chat/utils/TokenMgr.dart';
import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_inapp_purchase/flutter_inapp_purchase.dart';

import 'package:fluwx_no_pay/fluwx_no_pay.dart' as fluwx;
import 'package:oktoast/oktoast.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

class _ConversationItem extends StatelessWidget {
  const _ConversationItem(
      {Key key,
      this.conversation,
      this.callback,
      this.showRight = true,
      this.rightButton,
      this.showReturn = false,
      this.applyInfo,
      this.bgColor,
      this.isInCome = false,
      this.money,
      this.title})
      : assert(conversation != null),
        super(key: key);
  final Widget rightButton;
  final Conversation conversation;
  final callback;
  final int money;
  final bool showRight;
  final title;
  final applyInfo;
  final bgColor;
  final bool showReturn;
  final bool isInCome;

  @override
  Widget build(BuildContext context) {
    Widget avatar;
    double width = 44.55;
    if (conversation.isAvatarFromNet()) {
      avatar = ClipRRect(
          borderRadius: BorderRadius.circular(10),
          child: CachedNetworkImage(
            imageUrl: conversation.avatar,
            placeholder: (context, url) => Image.asset(
              Constants.DefaultHeadImgUrl,
              width: width,
              height: width,
            ),
            fit: BoxFit.cover,
            width: width,
            height: width,
          ));
    } else {
      avatar = ClipRRect(
          borderRadius: BorderRadius.circular(10),
          child: Container(
              width: width,
              height: width,
              alignment: Alignment.center,
              decoration: BoxDecoration(
                  gradient: this.bgColor,
                  borderRadius: BorderRadius.all(Radius.circular(50))),
              child: Image.asset(
                conversation.avatar,
                height: 27,
              )));
    }

    return InkWell(
      child: Container(
        padding: const EdgeInsets.only(
            left: 21, top: 12.5, bottom: 12.5, right: 24.5),
        decoration: BoxDecoration(
            color: Color(AppColors.ConversationItemBgColor),
            border: Border(
                bottom: BorderSide(
                    color: AppColors.DividerColor,
                    width: Constants.DividerWidth))),
        child: Row(
          crossAxisAlignment: CrossAxisAlignment.center,
          children: <Widget>[
            avatar,
            Container(width: 14.0),
            Expanded(
                child: Container(
              padding: EdgeInsets.only(top: 3),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: <Widget>[
                  Container(
                      child: title == null
                          ? Text(conversation.title,
                              textScaleFactor: 1.0,
                              style: TextStyle(
                                  fontSize: 11,
                                  color: Constants.LightGreyTextColor))
                          : title),
                  Container(
                    padding: EdgeInsets.only(top: 10),
                    child: Text(conversation.desc,
                        textScaleFactor: 1.0,
                        style: TextStyle(
                            fontSize: 11, color: Constants.LightGreyTextColor)),
                  )
                ],
              ),
            )),
            Container(
              height: width,
              margin: EdgeInsets.only(left: 10),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.end,
                mainAxisAlignment: MainAxisAlignment.center,
                children: <Widget>[
                  Text(
                    '${money > 0 ? '+' : ''}${this.isInCome ? money * 1000 : (money.toString() + I18n.of(context).mask_coin)}',
                    textScaleFactor: 1.0,
                    style: TextStyle(
                        fontSize: 14,
                        fontWeight: FontWeight.w500,
                        color:
                            money > 0 ? Color(0xFFFE4624) : Color(0xFF5498FF)),
                  ),
                  showReturn
                      ? Padding(
                          padding: EdgeInsets.only(top: 3),
                          child: Text(
                            I18n.of(context).alreay_back,
                            textScaleFactor: 1.0,
                            style: TextStyle(
                                fontSize: 12,
                                fontWeight: FontWeight.normal,
                                color: Constants.BlackTextColor),
                          ))
                      : Container()
                ],
              ),
              alignment: Alignment.center,
            ),
          ],
        ),
      ),
      onTap: () {
        callback();
      },
    );
  }
}

class MoneyDetailPage extends StatefulWidget {
  final int type;
  MoneyDetailPage({Key key, this.type}) : super(key: key);
  MoneyDetailPageState createState() => MoneyDetailPageState();
}

class MoneyDetailPageState extends State<MoneyDetailPage>
    with SingleTickerProviderStateMixin {
  List list = new List(); //列表要展示的数据
  RefreshController _refreshController =
      RefreshController(initialRefresh: true);

  int _page = 1; //加载的页数
  int rows = 20;

  TabController tabCtrl;

  var bindAccount;

  @override
  void initState() {
    super.initState();

    tabCtrl = TabController(length: 2, vsync: this);

    fluwx.responseFromPayment.listen((data) {
      if (data.errCode == 0) {
        Navigator.of(context).pop();
        setState(() {});
        showToast(I18n.of(context).payment_successful);
      }
    });
  }

  void addList(data) {
    if (data == null || data.length == 0) {
      _page--;
      _refreshController.loadNoData();
    } else {
      list.addAll(data);
      _refreshController.loadComplete();
    }
    setState(() {});
  }

  void _onLoading() async {
    _page++;
    getNewData(addList);
  }

  @override
  void dispose() {
    tabCtrl.dispose();
    _refreshController.dispose();
    if (_conectionSubscription != null) {
      _conectionSubscription.cancel();
      _conectionSubscription = null;
    }
    if (_purchaseUpdatedSubscription != null) {
      _purchaseUpdatedSubscription.cancel();
      _purchaseUpdatedSubscription = null;
    }

    if (_purchaseErrorSubscription != null) {
      _purchaseErrorSubscription.cancel();
      _purchaseErrorSubscription = null;
    }

    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    Widget content = Scaffold(
      resizeToAvoidBottomPadding: false,
      appBar: AppBar(
        leading: CustomUI.buildCustomLeading(context),
        backgroundColor: AppColors.NewAppbarBgColor,
        title: Text(
          widget.type == 1
              ? I18n.of(context).my_money_info
              : I18n.of(context).get_money_detail,
          textScaleFactor: 1.0,
        ),
        centerTitle: true,
      ),
      body: SafeArea(child: showCoin()),
    );
    return content;
    //return CustomUI.buildPageLoading(context, content, !isLoadingFish);
  }

  Widget showCoin() {
    return Scaffold(
        body: SafeArea(
            child: Center(
      child: Container(
        height: MediaQuery.of(context).size.height,
        width: MediaQuery.of(context).size.width,
        child: _buildCoinBody(),
      ),
    )));
  }

  void _onRefresh() async {
    _page = 1;
    getNewData(initList);
  }

  void initList(data) {
    list.clear();
    if (data != null) {
      list.addAll(data);
    }
    setState(() {});
  }

  getNewData(callback) async {
    Map data = {
      "userId": UserData().basicInfo.userId,
      'type': widget.type,
    };
    data['sign'] = TokenMgr().getSign(data);
    data["page"] = _page;
    data['rows'] = rows;

    Response res = await HttpUtil().post('wallet/balance/detail', data: data);
    var resData = res.data;
    _refreshController.refreshCompleted();
    print(resData);
    if (resData['code'] == 0) {
      callback(resData['data']);
    } else {
      showToast(resData['msg']);
    }
  }

  bool isAdd(int type) {
    if (widget.type == 1) {
      return type == 1 ||
          type == 2 ||
          type == 3 ||
          type == 12 ||
          type == 13 ||
          type == 14;
    } else {
      return !(type == 1 || type == 2);
    }
  }

  //钱包通知
  Widget _buildMoneyInfo(data) {
    print(data);
    String imgUrl = data['HeadImg'] == null ||
            data['HeadImg'] == '' ||
            data['ChangeUserId'] == 0
        ? UserData().basicInfo.headimgurl
        : data['HeadImg'];

    return _ConversationItem(
      conversation: Conversation(
        avatar: imgUrl,
        title: '',
        desc: WebData().getLoginTime(context, data['CreateTime']),
        updateAt: '',
      ),
      bgColor: Constants.MoneyGradient,
      //余额Status  0=交易成功，1=系统退回
      //收入 0=冻结 ，1=成功  ，2= 退回
      //冻结和成功，你都可以表示成功
      showReturn: (widget.type == 1 && data['Status'] ==1) || (widget.type == 2 && data['Status'] ==2),
      isInCome: widget.type == 2,
      money: isAdd(data['DetailType']) ? data['Value'] : -data['Value'],
      title: RichTitle.getRichTitleWidget(data, context,
          widget.type == 1 ? InfoType.MyMoney : InfoType.IncomeMoney,
          titleStyle: TextStyle(fontSize: 12, color: const Color(0XFF7F7F7F)),
          nameStyle: TextStyle(
              fontWeight: FontWeight.normal,
              fontSize: 13,
              color: Constants.BlackTextColor)),
      callback: () {
        if (data['ChangeUserId'] != 0) {
          Navigator.of(context).push(
            new MaterialPageRoute(
              builder: (context) {
                return ProfilePage(
                  userId: data['UserId'] == UserData().basicInfo.userId
                      ? data['ChangeUserId']
                      : data['UserId'],
                );
              },
            ),
          );
        }
      },
    );
  }

  Widget _renderRow(BuildContext context, int index) {
    if (index < list.length) {
      var userInfo = list[index];
      Widget result = _buildMoneyInfo(userInfo);
      if (index == 0) {
        result = Padding(padding: EdgeInsets.only(top: 10), child: result);
      }

      return result;
    }
    return Container();
  }

  Widget _buildCoinBody() {
    return SmartRefresher(
      enablePullDown: true,
      enablePullUp: true,
      header: MaterialClassicHeader(),
      footer: CustomUI.buildLoadingFooter(),
      controller: _refreshController,
      onRefresh: _onRefresh,
      onLoading: _onLoading,
      child: (_refreshController.headerStatus == RefreshStatus.completed &&
              list.length == 0)
          ? CustomUI.buildNoData(context)
          : ListView.builder(
              itemBuilder: _renderRow,
              itemCount: list.length,
            ),
    );
  }

  static String currentGoodsId = '';
  static StreamSubscription _conectionSubscription,
      _purchaseUpdatedSubscription,
      _purchaseErrorSubscription;

  ///ios 内购初始化
  static Future initPayConf(BuildContext context) async {
    if (_purchaseErrorSubscription != null) {
      return;
    }

    // prepare
    print('initPayConf   --------   start: ');
    var result = await FlutterInappPurchase.instance.initConnection;
    print('initPayConf   --------   result: $result');
    FlutterInappPurchase.instance.clearTransactionIOS();

    _conectionSubscription =
        FlutterInappPurchase.connectionUpdated.listen((connected) {
      print('connected: $connected');
    });

    _purchaseUpdatedSubscription =
        FlutterInappPurchase.purchaseUpdated.listen((productItem) {
      print('支付成功,成功回调  ------    purchase-updated: $productItem');
//      showToast('支付成功,成功回调  ------    purchase-updated: $productItem');
      if (productItem.transactionReceipt != null &&
          productItem.transactionReceipt.isNotEmpty) {
        HttpUtil().createOrder(currentGoodsId, productItem.transactionReceipt,
            productItem.purchaseToken,
            context: context);

        showToast(I18n.of(context).payment_successful);
      }
      Navigator.of(context).pop();
    });

    _purchaseErrorSubscription =
        FlutterInappPurchase.purchaseError.listen((purchaseError) {
//      showToast('支付失败回调    --------  purchase-error: $purchaseError');
      FlutterInappPurchase.instance.clearTransactionIOS();
      Navigator.of(context).pop();
    });
  }
}
