import 'package:chat/data/UserData.dart';
import 'package:chat/data/constants.dart';
import 'package:chat/generated/i18n.dart';
import 'package:chat/models/money_change.dart';
import 'package:chat/utils/ChargeMoney.dart';
import 'package:chat/utils/CustomUI.dart';
import 'package:chat/utils/HttpUtil.dart';
import 'package:chat/utils/MessageMgr.dart';
import 'package:chat/utils/ShadowButton.dart';
import 'package:chat/utils/TokenMgr.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';

const double PaddingSize = 8;

class VipPage extends StatefulWidget {
  VipPage({Key key}) : super(key: key);

  _VipPageState createState() => _VipPageState();
}

enum PayWay {
  wx,
  zfb,
}

class _VipPageState extends State<VipPage> with SingleTickerProviderStateMixin {
  TabController tabCtrl;

  List vipData = [];

  int selectId = 0;

  int selectMoney = 0;

  int payWay = PayWay.wx.index;

  bool isLoadingFish = false;

  bool isNormalVip = true;

  int subMoney = 0;

  List goodsList = [];

  Map memberInfo = {
    'CheckNum': 0,
    'PhotoOrAccount': 0,
    'BurnTime': 0,
    'PublishAd': 0,
    'HumanTranslation': 0,
    'ExclusiveCustomer': 0,
    'PremiumUIDisplay': 0,
  };

  @override
  void initState() {
    super.initState();
    getVipInfo(1);
  }

  void getVipInfo(type) async {
    Map data = {
      "userid": UserData().basicInfo.userId,
    };
    data['sign'] = TokenMgr().getSign(data);
    data['type'] = type;
    Response res = await HttpUtil().post('goods/member/list',
        data: data, failback: () => Navigator.of(context).pop());
    Map resData = res.data;
    if (resData['code'] == 0 &&
        resData['data'] != null &&
        resData['data'].length > 0) {
      if (type == 2) subMoney = upgradNum(vipData, resData['data']['list']);
      memberInfo = resData['data']['memberInfo'];
      vipData = resData['data']['list'];
      selectId = vipData[0]['Id'];
      selectMoney = vipData[0]['TotalPrice'];
      isLoadingFish = true;
      isNormalVip = type == 1;
      setState(() {});
    }
  }

  @override
  void dispose() {
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    Widget content = Scaffold(
        appBar: AppBar(
          backgroundColor: AppColors.NewAppbarBgColor,
          title: Text(
            I18n.of(context).member_centre,
            textScaleFactor: 1.0,
            style: TextStyle(color: AppColors.NewAppbarTextColor),
          ),
          centerTitle: true,
          leading: CustomUI.buildCustomLeading(context),
        ),
        body: SafeArea(
            child: Center(
          child: Container(
            height: MediaQuery.of(context).size.height,
            width: MediaQuery.of(context).size.width,
            child: _buildBody(),
          ),
        )));
    return CustomUI.buildPageLoading(context, content, !isLoadingFish);
  }

  Widget _buildBody() {
    return ListView(
      children: <Widget>[
        _buildTips(),
        _buildGoodsItemList(),
        _buildCommit(),
      ],
    );
  }

  //构建注册按钮
  Widget _buildCommit() {
    Text text = new Text(
        UserData().isVip
            ? I18n.of(context).renewal_fee
            : I18n.of(context).open_immediately,
        textScaleFactor: 1.0,
        style: TextStyle(fontSize: 17, color: Colors.white));

    LinearGradient gradientColor = new LinearGradient(colors: <Color>[
      Constants.ConfrimButtonColor,
      Constants.ConfrimButtonColor,
    ]);
    callback() {
      if (UserData().isSuperVip && isNormalVip) {
        showToast(I18n.of(context).cannot_vip);
        return;
      }

      if (UserData().isVip && !UserData().isSuperVip && !isNormalVip) {
        if (subMoney == 0) {
          return;
        }
        CustomUI.buildOneConfirm(
            context,
            I18n.of(context)
                .becomeSvip
                .replaceFirst('/s1', subMoney.toString()),
            I18n.of(context).determine, () {
          HttpUtil().buyVIP(subMoney, 0, 2, context, () {
            Navigator.of(context).pop();
            MessageMgr().emit('refresh_money');
            MessageMgr().emit('update_data');
          });
        });
        return;
      }

      if (Provider.of<MoneyChangeProvider>(context).money < selectMoney) {
        CustomUI.buildOneConfirm(context, I18n.of(context).balance_insufficien,
            I18n.of(context).recharge, () {
          Navigator.of(context).pop();
          ChargeMoney.showChargeSheet(context, () {
            setState(() {});
          });
        });
        return;
      }

      CustomUI.buildOneConfirm(
          context,
          I18n.of(context).confirm_pay +
              selectMoney.toString() +
              I18n.of(context).mask_coin,
          I18n.of(context).determine, () {
        HttpUtil().buyVIP(selectMoney, selectId, isNormalVip ? 1 : 2, context,
            () {
          Navigator.of(context).pop();
          MessageMgr().emit('refresh_money');
          MessageMgr().emit('update_data');
        });
      });
    }

    return Container(
      child: Column(
        children: <Widget>[
          Row(
            crossAxisAlignment: CrossAxisAlignment.center,
            children: <Widget>[
              Padding(
                padding: EdgeInsets.only(left: 28),
                child: Text(
                  I18n.of(context).total,
                  textScaleFactor: 1.0,
                  style: TextStyle(fontSize: 15.49),
                ),
              ),
              Padding(
                padding: EdgeInsets.only(top: 1),
                child: Text(
                  ' $selectMoney',
                  textScaleFactor: 1.0,
                  style: TextStyle(
                      color: const Color(0xFFE30101),
                      fontSize: 16,
                      fontWeight: FontWeight.normal),
                ),
              ),
              Padding(
                padding: EdgeInsets.only(left: 2, top: 1),
                child: Text(
                  I18n.of(context).mask_coin,
                  textScaleFactor: 1.0,
                  style:
                      TextStyle(color: const Color(0xFFE30101), fontSize: 15),
                ),
              ),
            ],
          ),
          Container(
            margin: EdgeInsets.only(top: 21, left: 31, right: 31, bottom: 20),
            height: 44,
            child: ShadowButton().builder(gradientColor, text, callback),
          )
        ],
      ),
    );
  }

  // Widget _buildVerText(String str) {
  //   List<Widget> child = [];
  //   List list = str.split(' ');
  //   list.forEach((str) {
  //     child.add(Text(
  //       str,
  //       style: TextStyle(fontSize: 14, color: Constants.BlackTextColor),
  //     ));
  //   });
  //   return Column(
  //     mainAxisAlignment: MainAxisAlignment.center,
  //     children: child,
  //   );
  // }

  Widget _buildGoodsItem(month, money, oldMoney, leftTop, value) {
    bool isSelect = selectId == value['Id'];
    return InkWell(
        onTap: () {
          setState(() {
            selectId = value['Id'];
            selectMoney = value['TotalPrice'];
          });
        },
        child: Container(
            alignment: Alignment.center,
            height: 49.25,
            margin: EdgeInsets.only(bottom: 15, left: 12.5, right: 12.5),
            decoration: BoxDecoration(
                color: Colors.white,
                border: Border.all(
                    width: 1,
                    color: isSelect
                        ?  const Color(0xFF2D81FF)
                        : const Color(0xFFC9C9C9)),
                boxShadow: [
                  BoxShadow(
                    color: isSelect
                        ? const Color(0x7A2D81FF)
                        : const Color(0x7ABCBCBC),
                    offset: Offset(0, 5),
                    blurRadius: 9,
                  )
                ],
                borderRadius: BorderRadius.all(Radius.circular(10))),
            child: Stack(
              children: <Widget>[
                leftTop
                    ? Positioned(
                        left: 0,
                        top: 0,
                        child: Container(
                          decoration: BoxDecoration(
                            borderRadius: BorderRadius.only(
                                topLeft: Radius.circular(9),
                                bottomRight: Radius.circular(5)),
                            gradient: LinearGradient(
                                begin: Alignment.topCenter,
                                end: Alignment.bottomCenter,
                                colors: <Color>[
                                  const Color(0xFFCE0B0B),
                                  const Color(0xFFFF0000),
                                ]),
                          ),
                          padding: EdgeInsets.only(left: 5, right: 5),
                          child: Text(I18n.of(context).recommend,
                              textScaleFactor: 1.0,
                              style:
                                  TextStyle(fontSize: 13, color: Colors.white)),
                        ))
                    : Positioned(left: 0, top: 0, child: Container()),
                isSelect
                    ? Positioned(
                        right: -1,
                        bottom: 0,
                        child: Image.asset(
                          'assets/images/login/vip_rect2.png',
                         
                        ),
                        width: 25,
                      )
                    : Positioned(
                        right: 0,
                        bottom: 0,
                        child: Container(),
                      ),
                Container(
                  height: double.infinity,
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.end,
                    children: <Widget>[
                      Expanded(
                        child: Container(
                            alignment: Alignment.center,
                            child: Row(
                              crossAxisAlignment: CrossAxisAlignment.center,
                              mainAxisAlignment: MainAxisAlignment.center,
                              children: <Widget>[
                                Text('$money',
                                    textScaleFactor: 1.0,
                                    style: TextStyle(
                                        color: const Color(0xFFE30101),
                                        fontSize: 22,
                                        fontWeight: FontWeight.normal)),
                                Text('${I18n.of(context).mask_coin}',
                                    textScaleFactor: 1.0,
                                    style: TextStyle(
                                        color: const Color(0xFFE30101),
                                        fontSize: 20,
                                        fontWeight: FontWeight.normal)),
                              ],
                            )),
                      ),
                      Image.asset(
                        'assets/images/login/vip_rect3.png',
                        height: 25,
                        color: Colors.grey,
                      ),
                      Container(
                        width: 110,
                        alignment: Alignment.center,
                        child: Text(month,
                            textScaleFactor: 1.0,
                            style: TextStyle(
                                fontSize: 15, color: Constants.BlackTextColor)),
                      ),
                    ],
                  ),
                )
              ],
            )));
  }

  Widget buildSelectContainer(str, bool isSelect, bool isNormalVip) {
    var color = Constants.BlackTextColor;
    return Container(
      alignment: Alignment.center,
      padding: EdgeInsets.only(bottom: isSelect ? 9 : 12),
      decoration: BoxDecoration(
          color: Colors.white,
          border: Border(
              bottom: BorderSide(
                  color:
                      isSelect ? const Color(0xFF2D81FF) : Colors.transparent,
                  width: isSelect ? 4 : 1))),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: <Widget>[
          Padding(
            padding: EdgeInsets.only(top: 0),
            child: Image.asset(
              isNormalVip
                  ? 'assets/images/vip/hy_hy.png'
                  : 'assets/images/vip/hy_cjhy.png',
              width: 18,
            ),
          ),
          SizedBox(width: 5),
          Text(str,
              textScaleFactor: 1.0,
              style: TextStyle(fontSize: 16, color: color))
        ],
      ),
    );
  }

  Widget _buildGoodsItemList() {
    Widget tip = Container(
        color: Colors.white,
        margin: EdgeInsets.only(bottom: 15),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceAround,
          children: <Widget>[
            InkWell(
                onTap: isNormalVip
                    ? null
                    : () {
                        getVipInfo(1);
                      },
                child: buildSelectContainer(
                    I18n.of(context).member, isNormalVip, true)),
            InkWell(
                onTap: !isNormalVip
                    ? null
                    : () {
                        getVipInfo(2);
                      },
                child: buildSelectContainer(
                    I18n.of(context).svip, !isNormalVip, false)),
          ],
        ));
    List<Widget> list = [tip];
    vipData.forEach((k) {
      var name = k['MonthValue'] == 0.5
          ? I18n.of(context).half_month
          : I18n.of(context)
              .month2
              .replaceFirst('/s1', k['MonthValue'].toInt().toString());
      list.add(_buildGoodsItem(
          name, k['TotalPrice'], 72, vipData.indexOf(k) == 0, k));
    });
    list.add(Container(
      height: 1,
      color: const Color(0xFFDADADA),
      margin: EdgeInsets.only(left: 14, right: 14, bottom: 13),
    ));
    return Container(
      child: Wrap(
        alignment: WrapAlignment.spaceEvenly,
        children: list,
      ),
    );
  }

  double subNum(data) {
    return data['MonthPrice'] / 30;
  }

//补差价
  int upgradNum(vipList, sVipList) {
    if (UserData().memberEndTime == '') {
      return 0;
    }
    int day = 0;
    const moneyDay = 30;
    try {
      DateTime endTime = DateTime.parse(UserData().memberEndTime);
      day = endTime.difference(DateTime.now()).inDays;
      if (day < 0) {
        return 0;
      }
      //小于最小天数按最小天数补
      if (day < vipList[0]['MonthValue'] * moneyDay) {
        return (day * (subNum(sVipList[0]) - subNum(vipList[0]))).ceil();
      }

      //大于最大天数按最大天数补
      if (day > vipList[vipList.length - 1]['MonthValue'] * moneyDay) {
        return (day *
                (subNum(sVipList[vipList.length - 1]) -
                    subNum(vipList[vipList.length - 1])))
            .ceil();
      }
      for (int i = 0; i < vipList.length; i++) {
        int standDay = (vipList[i]['MonthValue'] * moneyDay).ceil();

        if (day < standDay) {
          return (day * (subNum(sVipList[i - 1]) - subNum(vipList[i - 1])))
              .ceil();
        }
      }
    } catch (e) {}
    return 0;
  }

  Widget _buildTipItem(leftStr, rightStr, {isShow = true}) {
    var color = isShow ? Colors.white : Colors.white.withOpacity(0);
    return Container(
      margin: EdgeInsets.only(left: 39, right: 5),
      child: Row(
        children: <Widget>[
          Container(
            margin: EdgeInsets.only(right: 20.5),
            child: Text(
              leftStr,
              textScaleFactor: 1.0,
              style: TextStyle(
                  color: color, fontSize: 11.44, fontWeight: FontWeight.w600),
            ),
          ),
          Expanded(
              child: Container(
            padding: EdgeInsets.only(right: 5),
            child: Text(
              rightStr,
              textScaleFactor: 1.0,
              style: TextStyle(
                color: color,
                fontSize: 10.4,
              ),
            ),
          )),
        ],
      ),
    );
  }

  Widget _buildTips() {
    Widget tip = Container(
        margin: EdgeInsets.only(left: PaddingSize, right: PaddingSize),
        padding: EdgeInsets.only(top: 9, left: 12, bottom: 10),
        child: Row(
          children: <Widget>[
            Image.asset(
              'assets/images/vip/hy_tq.png',
              width: 16,
            ),
            Text(
              I18n.of(context).members_privilege,
              textScaleFactor: 1.0,
              style: TextStyle(color: Colors.white, fontSize: 13.54),
            ),
          ],
        ));
    return Container(
        color: Colors.white,
        width: Screen.width,
        child: Stack(
          children: <Widget>[
            Container(
              color: Colors.white,
              margin: EdgeInsets.only(left: PaddingSize, right: PaddingSize),
              alignment: Alignment.center,
              child: Image.asset(
                'assets/images/vip/hy_bg.png',
                fit: BoxFit.fitWidth,
              ),
            ),
//                        Container(
//                          height: 150,
//              margin: EdgeInsets.only(top:5,left: PaddingSize, right: PaddingSize),
//              alignment: Alignment.center,
//               child: Text(''),
//               decoration: BoxDecoration(
//                   borderRadius: BorderRadius.circular(12),
//                   gradient: LinearGradient(
//                 begin: Alignment.centerLeft,
//                 end: Alignment.centerRight,
//                 colors: [Color(0xffff9186), Color(0xffff5599)],
//
//               )),
//            ),
            Positioned(
                child: Container(
                    height: (Screen.width - PaddingSize * 2) / 2.18,
                    padding: EdgeInsets.only(bottom: 15),
                    child: Column(
                      mainAxisAlignment: MainAxisAlignment.spaceAround,
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: <Widget>[
                        tip,
                        _buildTipItem(I18n.of(context).see_more,
                            I18n.of(context).unlimited_see),
                        _buildTipItem(
                            I18n.of(context).see_cheaper,
                            I18n.of(context).free10.replaceFirst('/s1',
                                memberInfo['PhotoOrAccount'].toString())),
                        _buildTipItem(
                            I18n.of(context).see_longer,
                            I18n.of(context).towto6.replaceFirst('/s1',
                                (memberInfo['BurnTime'] + 2).toString())),
                        _buildTipItem(
                            I18n.of(context).see_better,
                            I18n.of(context).free_program.replaceFirst(
                                '/s1', memberInfo['PublishAd'].toString())),
                        _buildTipItem(I18n.of(context).right5,
                            I18n.of(context).free_translate,
                            isShow: !isNormalVip),
                        _buildTipItem(I18n.of(context).right6,
                            I18n.of(context).personalTraff,
                            isShow: !isNormalVip),
                      ],
                    ))),
          ],
        ));
  }
}
