import 'package:cached_network_image/cached_network_image.dart';
import 'package:chat/data/UserData.dart';
import 'package:chat/generated/i18n.dart';
import 'package:chat/models/ChatMsg.dart';
import 'package:chat/models/UserInfo.dart';
import 'package:chat/models/ref_name_provider.dart';
import 'package:chat/proto/all.pbserver.dart';
import 'package:chat/r.dart';
import 'package:chat/utils/CustomUI.dart';
import 'package:chat/utils/HttpUtil.dart';
import 'package:chat/utils/TokenMgr.dart';
import 'package:chat/utils/screen.dart';
import 'package:chat/utils/sql_util.dart';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:oktoast/oktoast.dart';
import 'package:provider/provider.dart';

import '../utils/MessageMgr.dart';

class CoinBagInfoPage extends StatefulWidget {
  final MsgModel msgModel;
  final String titleStr;
  CoinBagInfoPage(this.msgModel, {this.titleStr});
  @override
  _CoinBagInfoPageState createState() => _CoinBagInfoPageState();
}

class _CoinBagInfoPageState extends State<CoinBagInfoPage> {
  UserInfo friendInfo;
  RedWallet wallet;
  @override
  void initState() {
    super.initState();
    wallet = RedWallet.fromBuffer(widget.msgModel.msgContent);
    getInfo();
  }

  getInfo() async {
    int sendId = wallet.suId;
    if (sendId == UserData().basicInfo.userId) {
      friendInfo = UserData().basicInfo;
    } else {
      friendInfo = await HttpUtil().getFriendInfo(sendId);
      setState(() {});
    }

    updateRedWalletState();
  }

  @override
  Widget build(BuildContext context) {
    var foreColor = const Color(0xEEF9E3B2);

    return Scaffold(
        backgroundColor: Color(0xFFE86A52),
        appBar: AppBar(
          backgroundColor: Color(0xFFE86A52),
          leading: CustomUI.buildCustomLeading(context),
        ),
        body: SafeArea(
            child: Center(
                child: friendInfo == null
                    ? CircularProgressIndicator(
                        backgroundColor: Colors.orange,
                        valueColor: AlwaysStoppedAnimation(Colors.orange))
                    : Container(
                        padding:
                            EdgeInsets.only(left: 20,right: 20, bottom: 40),
                        child: Column(
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: <Widget>[
                            Container(
                              padding: EdgeInsets.symmetric(
                                  vertical: 40, horizontal: 20),
                              child: Column(
                                children: <Widget>[
                                  ClipRRect(
                                    borderRadius: BorderRadius.circular(8),
                                    child: CachedNetworkImage(
                                      imageUrl: friendInfo.headimgurl,
                                      placeholder: (context, url) {
                                        return Container(
                                            padding: EdgeInsets.all(10),
                                            child: CircularProgressIndicator(
                                                valueColor:
                                                    AlwaysStoppedAnimation(
                                                        foreColor)));
                                      },
                                      width: 100,
                                      height: 100,
                                    ),
                                  ),
                                  fixedText(
                                      I18n.of(context).ones_money.replaceFirst(
                                          '/s1',
                                          Provider.of<RefNameProvider>(context)
                                              .getRefName(friendInfo.userId,
                                                  friendInfo.nickName)),
                                      fontSize: 12,
                                      color: foreColor),
                                  SizedBox(height: 40),
                                  Text(
                                    widget.titleStr,
                                    textScaleFactor: 1.0,
                                    textAlign: TextAlign.center,
                                    style: TextStyle(
                                        fontSize: 24,
                                        color: foreColor,
                                        fontWeight: FontWeight.w500),
                                  ),
                                ],
                              ),
                            ),
                            SizedBox(height: 20),
                            _info(),
                            Expanded(child: SizedBox()),
                            fixedText(I18n.of(context).back_money,
                                fontSize: 12, color: foreColor)
                          ],
                        ),
                      ))));
  }

  _info() {
    var myId = UserData().basicInfo.userId;
    if (wallet.suId != myId) {
      //不是我发的
      if (wallet.state == RedWalletState.Uncollected) {
        return _openBtn();
      } else {
        return _getInfo();
      }
    } else {
      return _sendInfo();
    }
  }

  _receiveCoinBag() async {
    Map data = {
      "userId": UserData().basicInfo.userId,
      "redNo": wallet.orderId,
    };
    data['sign'] = TokenMgr().getSign(data);

    print(DateTime.now());
    Response res = await HttpUtil().post('red/packet/receive', data: data);

    if (res == null) {
      return null;
    }
    Map resData = res.data;

    if (resData['code'] == 0) {
      //领取成功
      print(DateTime.now());
      wallet.state = RedWalletState.Received;
      print('获得的金额${resData['data']['price']}');
      wallet.amount = resData['data']['price'];

      widget.msgModel.msgContent = wallet.writeToBuffer();

      MessageMgr().emit('Update RedWalletState', wallet);

      SqlUtil().updateWalletState(widget.msgModel);
      setState(() {});
    } else if (resData['code'] == -4) {
      //红包已过期
      showToast(I18n.of(context).money_over);
    } else if (resData['code'] == -5) {
      //红包已领过或者领取失败
      showToast(I18n.of(context).already_money);
    } else if (resData['code'] == -3) {
      //红包不存在
      showToast(I18n.of(context).no_money);
    } else {
      showToast(resData['msg']);
    }

    return null;
  }

  _openBtn() {
    return SizedBox(
        width: 100,
        height: 100,
        child: RaisedButton(
          padding: EdgeInsets.all(10.0),
          onPressed: _receiveCoinBag,
          shape: CircleBorder(),
          elevation: 2.0,
          child: Text(I18n.of(context).open,
              style: TextStyle(fontSize: 28),
              textAlign: TextAlign.center,
              textScaleFactor: 1.0),
          textColor: Color(0xFFD84F46),
          color: Color(0xFFFFE3AF),
        ));
  }

  _getInfo() {
    var infoStr = '';
    if (wallet.state == RedWalletState.Received) {
      infoStr = I18n.of(context).already_money;
    } else {
      infoStr = I18n.of(context).money_over;
    }

    return Container(
      child: Column(
        children: <Widget>[
          Row(
            mainAxisAlignment: MainAxisAlignment.center,
            crossAxisAlignment: CrossAxisAlignment.end,
            children: <Widget>[
              Text(wallet.amount.toString(),
                  textScaleFactor: 1.0,
                  style: TextStyle(fontSize: 50, color: Color(0xEEF9E3B2))),
              Padding(
                  padding: EdgeInsets.only(left: 10, bottom: 15),
                  child: Image.asset(R.assetsImagesCoin, scale: 3))
            ],
          ),
          fixedText(infoStr, color: Color(0xEEF9E3B2)),
        ],
      ),
    );
  }

  updateRedWalletState() async {
    Map data = {
      "userId": UserData().basicInfo.userId,
      "redNo": wallet.orderId,
    };
    data['sign'] = TokenMgr().getSign(data);

    Response res = await HttpUtil().post('red/packet/status', data: data);

    if (res == null) {
      return;
    }
    Map resData = res.data;

    if (resData['code'] == 0) {
      wallet.state = RedWalletState.valueOf(resData['data']['status']);
      if (wallet.state != RedWalletState.Uncollected) {
        if (mounted) {
          setState(() {});
        }
      }
    }
  }

  _sendInfo() {
    var msg;
    switch (wallet.state) {
      case RedWalletState.Expire:
        msg = I18n.of(context).back_user;
        break;
      case RedWalletState.Uncollected:
        msg = I18n.of(context).waiting_user;
        break;
      case RedWalletState.Received:
        msg = I18n.of(context).other_get;
        break;
      default:
    }

    return Container(
      child: Column(
        children: <Widget>[
          Row(
            mainAxisAlignment: MainAxisAlignment.center,
            crossAxisAlignment: CrossAxisAlignment.end,
            children: <Widget>[
              Text(wallet.amount.toString(),
                  textScaleFactor: 1.0,
                  style: TextStyle(fontSize: 50, color: Color(0xEEF9E3B2))),
              Padding(
                  padding: EdgeInsets.only(left: 10, bottom: 15),
                  child: Image.asset(R.assetsImagesCoin, scale: 3))
            ],
          ),
          fixedText(msg, color: Color(0xEEF9E3B2)),
        ],
      ),
    );
  }
}
