import 'package:flutter/material.dart';
import 'package:flutter_redux/flutter_redux.dart';
import 'package:flutter/cupertino.dart';
import '../redux/AppState.dart';
import '../model/ProductInfo.dart';
import '../widget/Dialog.dart';
import '../redux/UserRedux.dart';
import '../model/UserInfo.dart';
import '../styles/colors.dart';
import '../net/HttpManager.dart';
import '../net/Result.dart';
import '../styles/totast.dart';
import 'ChoosePay.dart';
import 'dart:io';

class ShoppingMall extends StatefulWidget {
  @override
  ShoppingMallState createState() => ShoppingMallState();
}

class ShoppingMallState extends State<ShoppingMall> {
  // final List<Tab> myTabs = <Tab>[Tab(text: '门票购买'), Tab(text: '会员充值')];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        // backgroundColor: PRIMARY_COLOR,
        title: Text('充值参赛券'),
        centerTitle: true,
      ),
      body: Recharge(type: 0),
    );
  }
}

class Recharge extends StatefulWidget {
  Recharge({Key key, this.type}) : super(key: key);
  final int type; //类型 0 金币 1 会员
  @override
  RechargeState createState() => RechargeState();
}

class RechargeState extends State<Recharge> {
  Future<void> getUserInfo() async {
    Result res = await HttpManager.get('userInfo/getUserInfo');
    if (res.success) {
      print(res.data);
      StoreProvider.of<AppState>(context).dispatch(UpdateUserAction(UserInfo.fromJson(res.data)));
    } else {}
  }

  List moneyList = [100, 300, 500, 1000, 2000, 5000];
  List vipList = [
    {'name': 'VIP1', 'value': 100},
    {'name': 'VIP2', 'value': 300},
    {'name': 'VIP3', 'value': 500},
    {'name': 'VIP4', 'value': 1000},
    {'name': 'VIP5', 'value': 2000},
    {'name': 'VIP6', 'value': 5000}
  ];
  List<ProductInfo> productInfoList = [];
  int chooseMoney = 0;
  ProductInfo chooseProduct;

  Future<void> getInfoList() async {
    Toast.show(context, '加载中', -1, 'loading');
    final Result res = await HttpManager.get('productInfo/all', data: {'typeFlag': widget.type});
    Toast.hide();
    if (res.success) {
      for (var item in res.data) {
        ProductInfo product;
        product = ProductInfo.fromJson(item);
        setState(() {
          productInfoList.add(product);
        });
      }
      // if (productInfoList.isNotEmpty) {
      //   setState(() {
      //     chooseProduct = productInfoList[0];
      //   });
      // }
    }

    final Result res2 = await HttpManager.get('payCodeStock/allUsedMoney', data: {'typeFlag': widget.type});
    if (res2.success) {
      for (var item in productInfoList) {
        for (var k in res2.data) {
          if (item.money == k['money']) {
            item.canUse = true;
          }
        }
      }
    }

    for (var item in productInfoList) {
      if (item.canUse) {
        setState(() {
          chooseProduct = item;
        });
        break;
      }
    }
  }

  Future<void> showDialog(id) async {
    Toast.show(context, '加载中', -1, 'loading');
    Result res = await HttpManager.get('alertMessage/getOne', data: {'id': id});
    Toast.hide();
    if (res.success) {
      MyDialog.showDialog(context, res.data['remark']);
    }
  }

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

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        color: BG_COLOR,
        child: ListView.builder(
            itemCount: productInfoList.length + 1,
            itemBuilder: (BuildContext context, int index) {
              if (index == productInfoList.length) {
                return Container(
                  height: 80,
                  child: Center(
                    child: Text('0点至8点到账缓慢，请提前充值', style: TextStyle(color: Color(0xFF727785), fontSize: 14)),
                  ),
                );
              }
              bool isChoose = false;
              if (chooseProduct != null && productInfoList[index].id == chooseProduct.id) {
                isChoose = true;
              }
              return Container(
                padding: EdgeInsets.symmetric(horizontal: 15),
                margin: EdgeInsets.only(top: 10),
                height: 60,
                child: FlatButton(
                  color: Color(0xFF24263A),
                  padding: EdgeInsets.all(0),
                  shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(4.0),
                      side: BorderSide(color: isChoose ? Theme.of(context).primaryColor : Colors.transparent, width: 1)),
                  disabledColor: Color(0xFF24263A).withOpacity(0.8),
                  child: Container(
                    child: Stack(
                      children: <Widget>[
                        Center(
                          child: Row(
                            mainAxisAlignment: MainAxisAlignment.center,
                            children: <Widget>[
                              Text(productInfoList[index].productName,
                                  style: TextStyle(
                                      color: productInfoList[index].canUse ? Color(0xFFFFFFFF) : Color(0xFF666666), fontWeight: FontWeight.w500, fontSize: 15)),
                              Container(
                                width: 10,
                              ),
                              Text(
                                '¥' + productInfoList[index].money.toString(),
                                style: TextStyle(
                                    color: productInfoList[index].canUse ? Color(0xFF727785) : Color(0xFF666666), fontWeight: FontWeight.w400, fontSize: 14),
                              )
                            ],
                          ),
                        ),
                        Positioned(
                          right: 0,
                          bottom: 0,
                          child: isChoose ? Image.asset('images/icon_xuanzhong.png') : Container(),
                        )
                      ],
                    ),
                  ),
                  onPressed: productInfoList[index].canUse
                      ? () {
                          if (!isChoose) {
                            setState(() {
                              chooseProduct = productInfoList[index];
                            });
                          }
                        }
                      : null,
                ),
              );
            }),
      ),
      floatingActionButton: Container(
        width: double.infinity,
        padding: EdgeInsets.symmetric(horizontal: 15),
        height: 48,
        child: FlatButton(
          color: PRIMARY_COLOR,
          textColor: Colors.white,
          child: Text('立即充值'),
          onPressed: () async {
            if (chooseProduct == null) {
              Toast.show(context, '请选择充值的门票', 1500, 'info');
              return;
            }

            Result res = await HttpManager.get('systemVariable/get', data: {'name': "iosPayHide"});

            if (res.success && res.data != null && res.data == 'true' && Platform.isIOS) {
              MyDialog.showDialog(context, 'ios充值暂未开放');
            } else {
              Navigator.push(context, CupertinoPageRoute(builder: (context) => ChoosePay(widget.type, chooseProduct)));
            }

            // Toast.show(context, '加载中', -1, 'loading');
            // final Result res = await HttpManager.post('productInfo/buy', data: {
            //   'userId': StoreProvider.of<AppState>(context).state.userInfo.id,
            //   'typeFlag': widget.type,
            //   'money': chooseProduct.money,
            //   'id': chooseProduct.id
            // });
            // Toast.hide();
            // if (res.success) {
            //   Toast.show(context, '购买成功', 1500, 'success');
            //   getUserInfo();
            // } else {
            //   Toast.show(context, res.error, 1500, 'info');
            // }
          },
        ),
      ),
      floatingActionButtonLocation: FloatingActionButtonLocation.centerFloat,
    );
  }
}

typedef void OnTapMenu();

class ShoopingBtn extends StatelessWidget {
  final String icon;
  final String title;
  final OnTapMenu onTapHomeMenu;
  ShoopingBtn(
    this.icon,
    this.title, {
    this.onTapHomeMenu,
  });
  @override
  Widget build(BuildContext context) {
    return Container(
      height: 70,
      decoration: BoxDecoration(
        // gradient: LinearGradient(begin: Alignment.topCenter, end: Alignment.bottomCenter, stops: [0.0, 0.5], colors: [Color(0xFF464B6A), Color(0xFF35395E)])
        color: Color(0xFF3A3E61),
        borderRadius: BorderRadius.all(Radius.circular(4)),
      ),
      child: Material(
          color: Colors.transparent,
          child: InkWell(
            onTap: onTapHomeMenu,
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[
                Image.asset(
                  icon,
                  width: 20,
                  height: 20,
                ),
                Container(
                  height: 5,
                ),
                Text(
                  title,
                  style: TextStyle(
                    fontSize: 13,
                    fontWeight: FontWeight.w600,
                    color: Theme.of(context).primaryColor,
                  ),
                )
              ],
            ),
          )),
    );
  }
}
