import 'package:chat/data/constants.dart';
import 'package:chat/generated/i18n.dart';
import 'package:chat/home/IndexPage.dart';
import 'package:chat/home/VipPage.dart';
import 'package:chat/utils/CustomUI.dart';
import 'package:flutter/material.dart';

import 'package:oktoast/oktoast.dart';
import '../utils/ShadowButton.dart';
import '../home/EditData.dart';
import 'package:flutter/services.dart';
import '../home/VerificationPage.dart';
import '../data/UserData.dart';
import '../utils/TokenMgr.dart';
import 'package:dio/dio.dart';
import '../utils/HttpUtil.dart';
import 'GetRegisterCodePage.dart';
import '../utils/MessageMgr.dart';

import 'package:chat/models/money_change.dart';
import 'package:provider/provider.dart';

class WelcomePage extends StatefulWidget {
  WelcomePage({Key key, bool flag}) : super(key: key);

  _WelcomePageState createState() => _WelcomePageState();
}

class _WelcomePageState extends State<WelcomePage> {
  List registerList = [];
  String registerCode = '';
  bool isCanApplay = true;
  @override
  void initState() {
    super.initState();
    getNewData(null);
    MessageMgr().on('register_code', getNewData);
    MessageMgr().on('refresh_money', msgBuyVip);
  }

  msgBuyVip(data) {
    HttpUtil().getWealth(context, (data) {
      if (mounted) {
        Provider.of<MoneyChangeProvider>(context).initMoney(data['CoinValue']);

      }
    });
  }

  initList(resData) {
    if (resData != null) {
      registerList = resData;
    }
    isCanApplay = true;
    for (int i = 0; i < registerList.length; i++) {
      if (registerList[i]['Status'] == 0 || registerList[i]['Status'] == 1) {
        isCanApplay = false;
        break;
      }
    }
    setState(() {});
  }

  void getNewData(data) {
    getRegisterState(initList);
  }

  @override
  void dispose() {
    MessageMgr().off('register_code', getNewData);
    MessageMgr().off('refresh_money', msgBuyVip);
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    Widget appBar = new AppBar(
      elevation: 1,
      // leading: IconButton(
      //   onPressed: () {
      //     HttpUtil().clearCacheData();
      //     Navigator.of(context).pushAndRemoveUntil(new MaterialPageRoute(
      //       builder: (context) {
      //         return IndexPage();
      //       },
      //     ), (route) => route == null);
      //   },
      //   icon: Icon(Icons.arrow_back),
      // ),
      leading: CustomUI.buildCustomLeading(context, onTap: () {
        HttpUtil().clearCacheData();
        Navigator.of(context).pushAndRemoveUntil(new MaterialPageRoute(
          builder: (context) {
            return IndexPage();
          },
        ), (route) => route == null);
      }),
      title: new Text(
        I18n.of(context).welcome,
        textScaleFactor: 1.0,
      ),
      centerTitle: true,
    );
    return Scaffold(
      body: SafeArea(
          child: Center(
        child: Container(
          height: MediaQuery.of(context).size.height,
          width: MediaQuery.of(context).size.width,
          child: _buildBody(),
        ),
      )),
      appBar: appBar,
      resizeToAvoidBottomPadding: false,
    );
  }

  Widget _buildBody() {
    return SingleChildScrollView(
      child: Column(
        children: <Widget>[
          Container(
            margin: EdgeInsets.only(top: 10),
            width: double.infinity,
            color: Colors.white,
            child: Column(
              children: <Widget>[
                _buildTopTips(),
                _buildInput(),
                _buildRegisterButton(),
              ],
            ),
          ),
          Container(
            margin: EdgeInsets.only(top: 59, bottom: 8.5),
            child: Text(
              I18n.of(context).how_get,
              style: TextStyle(fontSize: 11.59, color: Constants.GreyTextColor),
            ),
          ),
          _buildBottom(),
        ],
      ),
    );
  }

  void getRegisterState(callback) async {
    Map data = {
      "userId": UserData().basicInfo.userId,
    };
    data['sign'] = TokenMgr().getSign(data);
    try {
      Response res = await HttpUtil().post('user/apply/records', data: data);
      var resData = res.data;
      print(resData);
      if (resData['code'] == 0) {
        callback(resData['data']);
      } else {
        showToast(resData['msg']);
      }
    } catch (e) {}
  }

  Widget _buildTopTips() {
    return Container(
      margin: EdgeInsets.only(top: 22),
      child: Column(
        children: <Widget>[
          Text(
            I18n.of(context).enter_incode,
            textScaleFactor: 1.0,
            style: TextStyle(fontWeight: FontWeight.normal, fontSize: 16),
          ),
          SizedBox(height: 8),
          Text(
            I18n.of(context).must_incode,
            textScaleFactor: 1.0,
            style: TextStyle(color: const Color(0xFFC3C3C3), fontSize: 11.53),
          )
        ],
      ),
    );
  }

  Widget _buildRegisterButton() {
    Text text = new Text(I18n.of(context).determine,
        textScaleFactor: 1.0,
        style: TextStyle(fontSize: 15, color: Colors.white));

    LinearGradient gradientColor = new LinearGradient(colors: <Color>[
      Constants.ConfrimButtonColor,
      Constants.ConfrimButtonColor,
    ]);
    callback() async {
      if (registerCode == null || registerCode == '') {
        showToast(I18n.of(context).enter_incode);
        return;
      }
      var data = {
        "UserId": UserData().basicInfo.userId,
        "Code": registerCode,
      };
      data['sign'] = TokenMgr().getSign(data);
      try {
        Response res = await HttpUtil().post('user/register/code', data: data);
        var resData = res.data;
        print(resData);
        if (resData['code'] == 0) {
          Navigator.of(context).push(
            new MaterialPageRoute(
              builder: (context) {
                return EditPage(
                  isEditPage: false,
                );
              },
            ),
          );
        } else {
          showToast(resData['msg']);
        }
      } catch (e) {}
    }

    return new Container(
      margin: EdgeInsets.only(top: 36, left: 34, right: 34, bottom: 50),
      height: 42.7,
      child: ShadowButton().builder(gradientColor, text, callback),
    );
  }

  Widget _buildInput() {
    return Container(
      margin: EdgeInsets.only(top: 34, left: 34, right: 34),
      child: TextField(
        keyboardAppearance: Brightness.light,
        onChanged: (str) {
          registerCode = str;
        },
        textAlign: TextAlign.center,
        inputFormatters: [
          WhitelistingTextInputFormatter.digitsOnly,
          LengthLimitingTextInputFormatter(6)
        ],
        style: TextStyle(textBaseline: TextBaseline.alphabetic),
        decoration: InputDecoration(
          hintText: I18n.of(context).your_incode,
          hintStyle: TextStyle(fontSize: 19.21, color: const Color(0xFFB4B4B4)),
          contentPadding: EdgeInsets.all(10.0),
          border: OutlineInputBorder(
            borderRadius: BorderRadius.circular(30.0),
          ),
        ),
      ),
    );
  }

  Widget _buildBottom() {
    return Container(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.end,
        children: <Widget>[
          _buildBottomItemFirst(),
          _buildBottomItemSecond(),
        ],
      ),
    );
  }

  Widget _buildBottomItemFirst() {
    double leftPadding = 30;
    register() async {
      Navigator.of(context).push(
        new MaterialPageRoute(
          builder: (context) {
            return GetRegisterCodePage();
          },
        ),
      );
    }

    var color = isCanApplay ? const Color(0xFF2D81FF) : Colors.grey;
    Widget left = Container(
      padding: EdgeInsets.only(left: leftPadding),
      width: MediaQuery.of(context).size.width * 0.6,
      child: Column(
        children: <Widget>[
          Container(
            padding: EdgeInsets.only(top: 10),
            alignment: Alignment.centerLeft,
            child: Text(
              I18n.of(context).free,
              textScaleFactor: 1.0,
              style: TextStyle(
                  fontSize: 14,
                  fontWeight: FontWeight.w500,
                  color: Constants.BlackTextColor),
            ),
          ),
          Container(
            padding: EdgeInsets.only(top: 4),
            alignment: Alignment.centerLeft,
            child: Text(
              I18n.of(context).so_get,
              textScaleFactor: 1.0,
              style: TextStyle(color: const Color(0xFF949494), fontSize: 13),
            ),
          ),
        ],
      ),
    );
    Widget right = new Container(
      padding: EdgeInsets.only(top: 10),
      width: MediaQuery.of(context).size.width * 0.4,
      child: Column(
        children: <Widget>[
          InkWell(
              onTap: isCanApplay ? register : null,
              child: Container(
                padding:
                    EdgeInsets.only(top: 5, left: 20, right: 20, bottom: 5),
                decoration: BoxDecoration(
                    border: Border.all(color: color, width: 1),
                    color: Colors.white,
                    borderRadius: BorderRadius.all(Radius.circular(30))),
                child: Text(
                  isCanApplay
                      ? I18n.of(context).apply_now
                      : I18n.of(context).already_applied,
                  textScaleFactor: 1.0,
                  style: TextStyle(color: color),
                ),
              )),
          InkWell(
            onTap: () {
              getRegisterState((data) {
                initList(data);
                Navigator.of(context).push(
                  new MaterialPageRoute(
                    builder: (context) {
                      return VerificationPage(
                        applyList: data == null ? [] : data,
                      );
                    },
                  ),
                );
              });
            },
            child: Align(
              child: Container(
                padding: EdgeInsets.only(right: 25, top: 10),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.end,
                  children: <Widget>[
                    Text(
                      I18n.of(context).check_incode,
                      textScaleFactor: 1.0,
                      style: TextStyle(color: Colors.red, fontSize: 13),
                    ),
                    Icon(
                      IconData(0xe63c, fontFamily: 'iconfont'),
                      size: 18.0,
                      color: Colors.red,
                      //color: const Color(0xFF2D81FF),
                    ),
                  ],
                ),
              ),
            ),
          )
        ],
      ),
    );

    return Container(
        padding: EdgeInsets.only(bottom: 20),
        margin: EdgeInsets.only(bottom: 10),
        color: Colors.white,
        child: Column(
          children: <Widget>[
            Container(
              alignment: Alignment.centerLeft,
              padding: EdgeInsets.only(left: leftPadding, top: 2, bottom: 2),
              width: double.infinity,
              child: Text(
                I18n.of(context).method1,
                style: TextStyle(
                    fontSize: 15,
                    fontWeight: FontWeight.w500,
                    color: Constants.BlackTextColor),
              ),
              decoration: BoxDecoration(
                  border: Border(
                      bottom: BorderSide(color: const Color(0xFFF3F3F3)))),
            ),
            Row(
              children: <Widget>[left, right],
            ),
          ],
        ));
  }

  Widget _buildBottomItemSecond() {
    double leftPadding = 30;
    Widget left = Container(
      padding: EdgeInsets.only(left: leftPadding),
      width: MediaQuery.of(context).size.width * 0.6,
      child: Column(
        children: <Widget>[
          Container(
            padding: EdgeInsets.only(top: 10),
            alignment: Alignment.centerLeft,
            child: Text(
              I18n.of(context).joinvip,
              textScaleFactor: 1.0,
              style: TextStyle(
                  fontSize: 14,
                  fontWeight: FontWeight.w500,
                  color: Constants.BlackTextColor),
            ),
          ),
          Container(
            padding: EdgeInsets.only(top: 4),
            alignment: Alignment.centerLeft,
            child: Text(
              I18n.of(context).join_odds,
              textScaleFactor: 1.0,
              style: TextStyle(color: const Color(0xFF949494), fontSize: 13),
            ),
          ),
        ],
      ),
    );
    Widget right = new Container(
      width: MediaQuery.of(context).size.width * 0.4,
      child: Column(
        children: <Widget>[
          InkWell(
              onTap: () {
                Navigator.of(context).push(
                  new MaterialPageRoute(
                    builder: (context) {
                      return UserData().isVip
                          ? EditPage(
                              isEditPage: false,
                            )
                          : VipPage();
                    },
                  ),
                );
              },
              child: Container(
                padding:
                    EdgeInsets.only(top: 5, left: 15, right: 15, bottom: 5),
                decoration: BoxDecoration(
                    border:
                        Border.all(color: const Color(0xFF2D81FF), width: 1),
                    color: Colors.white,
                    borderRadius: BorderRadius.all(Radius.circular(30))),
                child: Text(
                  UserData().isVip
                      ? I18n.of(context).joined
                      : I18n.of(context).join_now,
                  textScaleFactor: 1.0,
                  style: TextStyle(color: const Color(0xFF2D81FF)),
                ),
              )),
          // UserData().isVip
          //     ? InkWell(
          //         onTap: () {
          //           Navigator.of(context).push(
          //             new MaterialPageRoute(
          //               builder: (context) {
          //                 return EditPage(
          //                   isEditPage: false,
          //                 );
          //               },
          //             ),
          //           );
          //         },
          //         child: Align(
          //           child: Container(
          //             padding: EdgeInsets.only(
          //                 right: MediaQuery.of(context).size.width * 0.1,
          //                 top: 10),
          //             child: Row(
          //               mainAxisAlignment: MainAxisAlignment.end,
          //               children: <Widget>[
          //                 Text(
          //                   I18n.of(context).joined,
          //                   textScaleFactor: 1.0,
          //                   style: TextStyle(
          //                       color: const Color(0xFFB4B4B4), fontSize: 13),
          //                 ),
          //                 Text(
          //                   '>',
          //                   textScaleFactor: 1.0,
          //                   style: TextStyle(color: const Color(0xFFF6C5CC)),
          //                 )
          //               ],
          //             ),
          //           ),
          //         ),
          //       )
          //     : Container(
          //         height: 13,
          //       ),
          Container(
            height: 13,
          )
        ],
      ),
    );

    return Container(
        padding: EdgeInsets.only(bottom: 20),
        margin: EdgeInsets.only(bottom: 10),
        color: Colors.white,
        child: Column(
          children: <Widget>[
            Container(
              alignment: Alignment.centerLeft,
              padding: EdgeInsets.only(left: leftPadding, top: 2, bottom: 2),
              width: double.infinity,
              child: Text(
                I18n.of(context).method2,
                style: TextStyle(
                    fontSize: 15,
                    fontWeight: FontWeight.w500,
                    color: Constants.BlackTextColor),
              ),
              decoration: BoxDecoration(
                  border: Border(
                      bottom: BorderSide(color: const Color(0xFFF3F3F3)))),
            ),
            Row(
              children: <Widget>[left, right],
            ),
          ],
        ));
  }
}
