import 'package:chat/chat/gift_page.dart';
import 'package:chat/data/UserData.dart';
import 'package:chat/data/constants.dart';
import 'package:chat/data/gift_data_mgr.dart';
import 'package:chat/generated/i18n.dart';
import 'package:chat/models/gift_item_model.dart';
import 'package:chat/models/gift_select_provider.dart';
import 'package:chat/models/money_change.dart';
import 'package:chat/proto/chat.pb.dart';
import 'package:chat/r.dart';
import 'package:chat/utils/ChargeMoney.dart';
import 'package:chat/utils/HttpUtil.dart';
import 'package:chat/utils/TokenMgr.dart';
import 'package:chat/utils/anim_effect_overlay.dart';
import 'package:chat/utils/msgHandler.dart';
import 'package:chat/utils/screen.dart';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:oktoast/oktoast.dart';
import 'package:provider/provider.dart';

class GiftSelectWidget extends StatefulWidget {
  final int friendId;
  final Function sendMsg;
  GiftSelectWidget(this.friendId, this.sendMsg);
  @override
  _GiftSelectWidgetState createState() => _GiftSelectWidgetState();
}

class _GiftSelectWidgetState extends State<GiftSelectWidget> {
  //打赏礼物信息
  List<GiftItemModel> giftList;
//礼物数量
  int curGiftValue = 1;

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

  getGiftList() async {
    giftList = await GiftMgr().getGiftList();
    if (mounted) {
      setState(() {});
    }
  }

  _sendGift(BuildContext context) async {
    int curSelectIndex =
        Provider.of<GiftSelectProvider>(context).curSelectIndex;
    var curGift = giftList[curSelectIndex];

    int price = curGift.price;
    int giftId = curGift.id;
    int total = curGiftValue * price;
    if (total > Provider.of<MoneyChangeProvider>(context).money) {
      showToast(I18n.of(context).not_enough);
      return;
    }

    int buyCount = 0;
    if (curGiftValue > curGift.amount) {
      buyCount = curGiftValue - curGift.amount;
    }
    Map data = {
      "userId": UserData().basicInfo.userId,
      "rUserId": widget.friendId,
      "id": giftId,
      "price": price,
      "amount": curGiftValue,
      "totalPrice": total,
      "payNum": buyCount
    };
    data['sign'] = TokenMgr().getSign(data);

    Response res = await HttpUtil().post('reward/gift', data: data);
    if (res == null) {
      return;
    }
    Map resData = res.data;

    //showToast(resData['msg']);

    if (resData['code'] == 0) {
      //赠送成功
      print('赠送金额：${resData['data']}');
      if (curGift.amount >= curGiftValue) {
        curGift.amount -= curGiftValue;
      }

      int receiveAmount = resData['data'];

      Provider.of<MoneyChangeProvider>(context, listen: false).subMoney(total);
      AnimEffect.showEffect(context, giftId);
      AnimEffect.showDashangEffect(context, true, curGiftValue, curGift.name);

      var msgContetnt = GiftChat.create();
      msgContetnt.giftAmount = curGiftValue;
      msgContetnt.suId = UserData().basicInfo.userId;
      msgContetnt.tuId = widget.friendId;

      msgContetnt.giftId = giftId;
      msgContetnt.giftName = curGift.name;
      msgContetnt.money = receiveAmount;

      var msg = MsgHandler.createSendMsg(
          ChatType.GiftChatType, msgContetnt.writeToBuffer(),
          friendId: widget.friendId, channelType: ChatChannelType.Session);

      widget.sendMsg(msg);

      setState(() {});
    } else {
      print(resData['msg']);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Container(
        height: 320,
        width: Screen.width,
        decoration: BoxDecoration(
          color: Colors.white,
        ),
        child: giftList == null
            ? Center(child: Text(I18n.of(context).no_gift))
            : Column(
                children: <Widget>[
                  Container(
                    padding: EdgeInsets.symmetric(vertical: 5, horizontal: 20),
                    child: Row(
                      children: <Widget>[
                        Text(I18n.of(context).sent_gift,
                            textScaleFactor: 1.0,
                            style: TextStyle(
                                fontSize: 16,
                                fontWeight: FontWeight.bold,
                                color: Constants.BlackTextColor)),
                        Expanded(
                          child: SizedBox(),
                        ),
                        Image.asset(
                          R.assetsImagesCoin,
                          scale: 2,
                        ),
                        SizedBox(
                          width: 5,
                        ),
                        fixedText(
                            I18n.of(context)
                                .available_balance
                                .replaceFirst('/s1', ''),
                            color: Constants.GreyTextColor),
                        Consumer<MoneyChangeProvider>(
                          builder:
                              (context, MoneyChangeProvider counter, child) =>
                                  fixedText(counter.money.toString(),
                                      color: Color(0xFFDB305D)),
                        ),
                        fixedText(I18n.of(context).mask_coin,
                            color: Color(0xFFDB305D)),
                      ],
                    ),
                  ),
                  Container(
                    alignment: Alignment.topCenter,
                    padding: EdgeInsets.all(10),
                    height: 150,
                    child: GiftPage(giftList, 0),
                  ),
                  Expanded(child: SizedBox()),
                  Padding(
                    padding: EdgeInsets.symmetric(vertical: 10, horizontal: 20),
                    child: Row(
                      children: <Widget>[
                        Expanded(
                            child: SizedBox(
                          height: 36,
                          child: RaisedButton(
                            padding: EdgeInsets.symmetric(horizontal: 5),
                            child: Text(
                              I18n.of(context).recharge,
                              textScaleFactor: 1.0,
                              maxLines: 1,
                              style: TextStyle(
                                  fontSize: 16, fontWeight: FontWeight.bold),
                            ),
                            elevation: 2.0,
                            color: Colors.orangeAccent,
                            textColor: Colors.white,
                            onPressed: () {
                              ChargeMoney.showChargeSheet(context, () {});
                            },
                            shape: RoundedRectangleBorder(
                              borderRadius:
                                  BorderRadius.all(Radius.circular(20)),
                            ),
                          ),
                        )),
                        SizedBox(width: 20),
                        Expanded(
                            flex: 2,
                            child: Container(
                                height: 36,
                                decoration: BoxDecoration(
                                    boxShadow: [
                                      BoxShadow(
                                          blurRadius: 2.0,
                                          color: Colors.white24)
                                    ],
                                    borderRadius:
                                        BorderRadius.all(Radius.circular(20)),
                                    border: Border.all(color: Colors.red)),
                                child: Row(
                                  children: <Widget>[
                                    Expanded(
                                        child: DropdownButton(
                                      isExpanded: true,
                                      underline: Container(),
                                      value: curGiftValue,
                                      style: TextStyle(fontSize: 16),
                                      iconEnabledColor: Colors.redAccent,
                                      onChanged: (newValue) {
                                        setState(() {
                                          curGiftValue = newValue;
                                        });
                                      },
                                      items: <int>[1, 6, 8, 66]
                                          .map<DropdownMenuItem>((v) =>
                                              DropdownMenuItem(
                                                  value: v,
                                                  child: Container(
                                                      padding: EdgeInsets.only(
                                                          left: 20),
                                                      child: fixedText(
                                                          v.toString(),
                                                          color: v ==
                                                                  curGiftValue
                                                              ? Colors.redAccent
                                                              : Colors.black))))
                                          .toList(),
                                    )),
                                    Expanded(
                                        child: InkWell(
                                      child: Container(
                                        decoration: BoxDecoration(
                                          color: Color(0xFFFD6E8F),
                                          borderRadius: BorderRadius.only(
                                              topRight: Radius.circular(20),
                                              bottomRight: Radius.circular(20)),
                                        ),
                                        height: 36,
                                        alignment: Alignment.center,
                                        child: Text(
                                          I18n.of(context).give,
                                          textScaleFactor: 1.0,
                                          style: TextStyle(
                                              color: Colors.white,
                                              fontSize: 16,
                                              fontWeight: FontWeight.bold),
                                        ),
                                      ),
                                      onTap: () {
                                        _sendGift(context);
                                      },
                                    ))
                                  ],
                                )))
                      ],
                    ),
                  )
                ],
              ));
  }
}
