import 'package:chat/generated/i18n.dart';
import 'package:chat/models/daily_bonus.dart';
import 'package:chat/r.dart';
import 'package:chat/utils/CustomUI.dart';
import 'package:chat/utils/HttpUtil.dart';
import 'package:chat/utils/MessageMgr.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:percent_indicator/linear_percent_indicator.dart';

class DailyBonusPage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return DailyBouusState();
  }
}

class DailyBouusState extends State with SingleTickerProviderStateMixin {
  bool isLoadingFish = false;

  int score = 0;
  List<GoodsBean> goods = [];

  DailyBonusBean dailyBonusBean;
  int addScore = 0;
  double progress1 = 0;
  double progress2 = 0;
  double progress3 = 0;

  AnimationController controller;
  Animation<double> animation;
  AnimationStatusListener statusListener;

  @override
  void dispose() {
    animation.removeStatusListener(statusListener);
    animation = null;

    controller.dispose();
    controller = null;
    super.dispose();
  }

  @override
  void initState() {
    super.initState();
    dailyBonusBean = new DailyBonusBean();

    controller = new AnimationController(
        duration: const Duration(milliseconds: 800), vsync: this);
    animation = Tween(begin: 0.95, end: 1.1).animate(controller);

    animation.addStatusListener(statusListener = (status) {
      if (status == AnimationStatus.completed) {
        controller.reverse(from: 1.0);
      } else if (status == AnimationStatus.dismissed) {
        controller.forward();
      }
    });

    controller.addListener(() {
      setState(() {});
//      print(animation.value);
    });
    controller.forward();

    WidgetsBinding.instance.addPostFrameCallback((_) {
      initDailyInfo();
    });
  }

  initDailyInfo() async {
    var daily = await HttpUtil().getDailyBonus();
    if (daily != null) {
      dailyBonusBean = daily;
      setState(() {
        goods = dailyBonusBean.goods;
        print('dailyBonusBean goods length:${dailyBonusBean.goods.length}');
        score = dailyBonusBean.score;

        int currentDay = dailyBonusBean.isSignIn == 0
            ? dailyBonusBean.currentDay + 1
            : dailyBonusBean.currentDay;
        addScore = currentDay * dailyBonusBean.addScore;
        setProgress();
        isLoadingFish = true;
      });
    }
  }

  setProgress() {
    int currentPart = 0;
    double tempProgress = 0;
    for (int k = 0; k < dailyBonusBean.goods.length; k++) {
      GoodsBean bean = dailyBonusBean.goods[k];

      if (score <= bean.s) {
        currentPart = k;
        break;
      }
    }
    print('tempProgress: $tempProgress');
    print('currentPart: $currentPart');
    if (currentPart == 0) {
      GoodsBean bean = dailyBonusBean.goods[0];
      print('GGG $score  ${bean.s}  ${dailyBonusBean.goods.length}');
      tempProgress = score / bean.s;
      progress1 = tempProgress;
      progress2 = 0;
      progress3 = 0;
      if (progress1 > 1) {
        progress1 = 1;
      }
    } else if (currentPart == 1) {
      int s = dailyBonusBean.goods[currentPart].s -
          dailyBonusBean.goods[currentPart - 1].s;
      int current = (score - dailyBonusBean.goods[currentPart - 1].s);

      double p = current / s;
      progress1 = 1;
      progress2 = p;
      print('WWW $s $current $progress2  ');
      progress3 = 0;
      if (progress2 > 1) {
        progress2 = 1;
      }
    } else if (currentPart == 2) {
      int s = dailyBonusBean.goods[currentPart].s -
          dailyBonusBean.goods[currentPart - 1].s;
      int current = (score - dailyBonusBean.goods[currentPart - 1].s);

      double p = current / s;
      progress1 = 1;
      progress2 = 1;
      progress3 = p;
      if (progress3 > 1) {
        progress3 = 1;
      }
      print('WWW $s  $progress3  ');
    }

//    print('progress: $progress');

//    GoodsBean bean = dailyBonusBean.goods[currentPart];
//    print('currentPart:$currentPart');
//    int max = bean.s;
//    double maxProgress = currentPart/(dailyBonusBean.goods.length);
//
//    progress = score/max*maxProgress;
  }

  @override
  Widget build(BuildContext context) {
    List<String> signStr = I18n.of(context).today_score.split('/s1');
    int signTotalDay = dailyBonusBean != null ? dailyBonusBean.currentDay : 0;
    String rules = '''${I18n.of(context).sign_tips}''';
    Widget content = Material(
      child: Stack(
        children: <Widget>[
          Container(
            height: MediaQuery.of(context).size.height,
            color: Color(0xffF0F0F0),
          ),
          Container(
            child: Image.asset(
              'assets/images/daily_bg_1.png',
              width: MediaQuery.of(context).size.width,
              height: 200,
              fit: BoxFit.cover,
            ),
          ),
          Scaffold(
            appBar: AppBar(
              title: Text(
                I18n.of(context).sign_in,
                textScaleFactor: 1.0,
                style: TextStyle(color: Colors.white),
              ),
              centerTitle: true,
              leading: CustomUI.buildCustomLeading(context),
              backgroundColor: Colors.transparent,
              iconTheme: IconThemeData(color: Colors.white),
            ),
            backgroundColor: Colors.transparent,
            body: SafeArea(
                child: SingleChildScrollView(
              child: Column(
                children: <Widget>[
                  Padding(
                    padding: EdgeInsets.symmetric(horizontal: 10),
                    child: Stack(
                      children: <Widget>[
                        Image.asset(R.assetsImagesDailyBg2, fit: BoxFit.cover),
                        Container(
                          padding: EdgeInsets.only(left: 30, right: 20),
                          height: 150,
                          alignment: Alignment.center,
                          child: Row(
                            children: <Widget>[
                              Expanded(
                                  flex: 4,
                                  child: Column(
                                    crossAxisAlignment:
                                        CrossAxisAlignment.center,
                                    children: <Widget>[
                                      SizedBox(
                                        height: 50,
                                      ),
                                      Text(
                                        I18n.of(context).my_score,
                                        textScaleFactor: 1.0,
                                        style: TextStyle(
                                            color: Color(0xff6D6D6E),
                                            fontSize: 16),
                                      ),
                                      Text(
                                        '$score',
                                        textScaleFactor: 1.0,
                                        style: TextStyle(
                                            color: Color(0xff0060FF),
                                            fontSize: 33),
                                      ),
                                    ],
                                  )),
                              Expanded(
                                  flex: 6,
                                  child: Container(
                                    padding: EdgeInsets.only(left: 20),
                                    child: Column(
                                      children: <Widget>[
                                        SizedBox(
                                          height: 50,
                                        ),
                                        GestureDetector(
                                          child: Container(
                                            alignment: Alignment.center,
                                            constraints: BoxConstraints(
                                                minHeight: 38,
                                                minWidth: 113,
                                                maxWidth: 150),
                                            child: Text(
                                              I18n.of(context).signin_now,
                                              textScaleFactor: 1.0,
                                              style: TextStyle(
                                                  color: Colors.white,
                                                  fontSize: 16),
                                            ),
                                            decoration: BoxDecoration(
                                                color: Color(
                                                    dailyBonusBean.isSignIn == 0
                                                        ? 0xff2D81FF
                                                        : 0xffB5B5B5),
                                                borderRadius:
                                                    BorderRadius.circular(6)),
                                          ),
                                          onTap: () {
                                            signInBouus();
                                          },
                                        ),
                                        SizedBox(
                                          height: 10,
                                        ),
                                        RichText(
                                            maxLines: 3,
                                            textAlign: TextAlign.center,
                                            text: TextSpan(children: [
                                              TextSpan(
                                                  text: signStr[0],
                                                  style: TextStyle(
                                                      color: Color(0xff6D6D6E),
                                                      fontSize: 10)),
                                              TextSpan(
                                                  text: '$addScore',
                                                  style: TextStyle(
                                                      color: Color(0xffFF0000),
                                                      fontSize: 10)),
                                              TextSpan(
                                                  text: signStr[1],
                                                  style: TextStyle(
                                                      color: Color(0xff6D6D6E),
                                                      fontSize: 10)),
                                            ]))
                                      ],
                                    ),
                                  ))
                            ],
                          ),
                        )
                      ],
                    ),
                  ),
                  SizedBox(
                    height: 15,
                  ),
                  Container(
                    ///签到进度
                    height: 118,

                    width: MediaQuery.of(context).size.width,
                    margin: EdgeInsets.symmetric(horizontal: 17),
                    child: Column(
                      children: <Widget>[
                        Container(
                          alignment: Alignment.center,
                          height: 105,
                          width: 360,
                          child: Stack(
                            children: <Widget>[
                              Container(
                                alignment: Alignment.center,
                                child: Padding(
                                  padding: EdgeInsets.only(left: 10, top: 12),
                                  child: Row(
                                    children: <Widget>[
                                      LinearPercentIndicator(
                                        width: 51,
                                        lineHeight: 10,
                                        percent: progress1,
                                        padding: null,
                                        progressColor: Color(0xff008AFF),
                                        backgroundColor: Color(0xffD3D3D3),
                                      ),
                                      SizedBox(
                                        width: 15,
                                      ),
                                      LinearPercentIndicator(
                                        width: 94,
                                        lineHeight: 10,
                                        percent: progress2,
                                        padding: null,
                                        progressColor: Color(0xff008AFF),
                                        backgroundColor: Color(0xffD3D3D3),
                                      ),
                                      SizedBox(
                                        width: 23,
                                      ),
                                      LinearPercentIndicator(
                                        width: 94,
                                        lineHeight: 10,
                                        percent: progress3,
                                        padding: null,
                                        progressColor: Color(0xff008AFF),
                                        backgroundColor: Color(0xffD3D3D3),
                                      ),
                                    ],
                                  ),
                                ),
                              ),
                              getGoods()
                            ],
                          ),
                        ),
                      ],
                    ),
                    decoration: BoxDecoration(
                        color: Colors.white,
                        borderRadius: BorderRadius.circular(6)),
                  ),
                  SizedBox(
                    height: 22,
                  ),
                  Container(
                    ///签到天数
                    constraints: BoxConstraints(minHeight: 420),
                    width: MediaQuery.of(context).size.width,
                    margin: EdgeInsets.symmetric(horizontal: 17),
                    child: Column(
                      children: <Widget>[
                        Container(
                          alignment: Alignment.center,
                          height: 46,
                          margin: EdgeInsets.all(20),
                          child: Row(
                            children: <Widget>[
                              Image.asset(R.assetsImagesDailyIcon),
                              Expanded(
                                  child: Text(
                                I18n.of(context).sign_in_day.replaceFirst(
                                    '/s1', signTotalDay.toString()),
                                textAlign: TextAlign.center,
                                textScaleFactor: 1.0,
                                style: TextStyle(
                                    color: Colors.white, fontSize: 13),
                              ))
                            ],
                          ),
                          decoration: BoxDecoration(
                              borderRadius: BorderRadius.circular(23),
                              gradient: LinearGradient(
                                colors: [Color(0xff8683EA), Color(0xff4BAAFB)],
                              )),
                        ),

                        ///签到天数表格
                        Container(
                          height: 246,
                          padding: EdgeInsets.only(left: 20, right: 20),
                          child: GridView.builder(
                            physics: NeverScrollableScrollPhysics(),
                            gridDelegate:
                                SliverGridDelegateWithFixedCrossAxisCount(
                                    crossAxisCount: 7,
                                    crossAxisSpacing: 15.0,
                                    mainAxisSpacing: 13.0),
                            itemBuilder: (context, index) {
                              bool isCheck = index < dailyBonusBean.currentDay;
                              return ClipOval(
                                child: Container(
                                  alignment: Alignment.center,
                                  color:
                                      Color(isCheck ? 0xff2D81FF : 0xffD3D3D3),
                                  child: isCheck
                                      ? Icon(
                                          Icons.check,
                                          color: Colors.white,
                                        )
                                      : Text(
                                          '${index + 1}',
                                          textScaleFactor: 1.0,
                                          style: TextStyle(color: Colors.white),
                                        ),
                                ),
                              );
                            },
                            itemCount: dailyBonusBean.days,
                            padding: EdgeInsets.all(5.0),
                          ),
                        ),
                        Padding(
                          padding: EdgeInsets.fromLTRB(18, 0, 18, 18),
                          child: Text(
                            rules,
                             textScaleFactor: 1.0,
                            style: TextStyle(
                                color: Color(0xffFF0000), fontSize: 12),
                          ),
                        )
                      ],
                    ),
                    decoration: BoxDecoration(
                        color: Colors.white,
                        borderRadius: BorderRadius.circular(6)),
                  ),
                  SizedBox(
                    height: 22,
                  ),
                ],
              ),
            )),
          )
        ],
      ),
    );
    return CustomUI.buildPageLoading(context, content, !isLoadingFish);
  }

  Widget getGoods() {
    return goods.length < 3
        ? Container()
        : Container(
            width: 400,
            height: 105,
            child: Row(
              children: <Widget>[
                SizedBox(
                  width: 46,
                ),
                getGoodsItem(goods[0], 0),
                SizedBox(
                  width: 39,
                ),
                getGoodsItem(goods[1], 1),
                SizedBox(
                  width: 38,
                ),
                getGoodsItem(goods[2], 2),
              ],
            ),
          );
  }

  getGoodsItem(GoodsBean bean, int index) {
    bool isEnough = score >= bean.s;

    bool needAnimate = isEnough && bean.state == 0;

    return GestureDetector(
      onTap: () {
        exchangeBonus(index);
      },
      child: Column(
        children: <Widget>[
          Container(
            alignment: Alignment.center,
            margin: EdgeInsets.only(top: 12, bottom: 5),
            constraints: BoxConstraints(minWidth: 61),
            padding: EdgeInsets.fromLTRB(3, 1, 3, 1),
            decoration: BoxDecoration(
                color: Color(isEnough ? 0xff2D81FF : 0xffCBCBCB),
                borderRadius: BorderRadius.circular(8)),
            child: Text(
              bean.state == 1
                  ? I18n.of(context).have_get
                  : '${bean.h}${I18n.of(context).daily_translate_voucher}',
              textScaleFactor: 1.0,
              style: TextStyle(color: Colors.white, fontSize: 12),
            ),
          ),
          Stack(
            children: <Widget>[
//       Container(width: 49,),
              Positioned(
                  top: 48,
                  child: Text('${bean.s}',
                      textScaleFactor: 1.0,
                      style: TextStyle(
                          color: Color(isEnough ? 0xff2D81FF : 0xffCBCBCB),
                          fontSize: 13))),
              Container(
                margin: EdgeInsets.only(bottom: 25),
                alignment: Alignment.center,
                width: 40,
                height: 40,
                child: Container(
                    alignment: Alignment.center,
                    width: 37,
                    height: 37,
                    child: Image.asset(
                      R.assetsImagesImgFyj,
                      width: needAnimate ? animation.value * 24 : 24,
                      height: needAnimate ? animation.value * 24 : 24,
                    ),
                    decoration: BoxDecoration(
                        color: Color(isEnough ? 0xff2D81FF : 0xffCBCBCB),
                        borderRadius: BorderRadius.circular(30))),
                decoration: BoxDecoration(
                    color: Colors.white,
                    borderRadius: BorderRadius.circular(30)),
              ),
            ],
          ),
        ],
      ),
    );
  }

  signInBouus() async {
    if (dailyBonusBean.isSignIn == 0) {
      int addScore = (dailyBonusBean.currentDay + 1) * dailyBonusBean.addScore;
      bool isSuccess = await HttpUtil().signInBounus(addScore);
      if (isSuccess) {
        setState(() {
          score = score + addScore;
          dailyBonusBean.isSignIn = 1;
          dailyBonusBean.currentDay = dailyBonusBean.currentDay + 1;
        });
      }
    }
  }

  exchangeBonus(int index) async {
    GoodsBean goodsBean = goods[index];
    if (score >= goodsBean.s && goodsBean.state == 0) {
//      int addScore=  (dailyBonusBean.currentDay+1)*dailyBonusBean.addScore;
      bool isSuccess = await HttpUtil().signInExchange(goodsBean);
      if (isSuccess) {
        setState(() {
          score = score - goodsBean.s;
          goods[index].state = 1;
          setProgress();
        });
        MessageMgr().emit('refresh_money');

        ///兑换成功后加了金币刷新余额
      }
    }
  }
}
