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';

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 DefaultTabController(
      length: myTabs.length,
      child: Scaffold(
        appBar: AppBar(
          // backgroundColor: PRIMARY_COLOR,
          title: Padding(
            padding: EdgeInsets.only(right: 56),
            child: TabBar(
              tabs: myTabs,
              indicatorColor: Theme.of(context).primaryColor,
              labelColor: Theme.of(context).primaryColor,
              unselectedLabelColor: Colors.white,
              indicatorSize: TabBarIndicatorSize.label,
            ),
          ),
        ),
        body: TabBarView(
          children: <Widget>[
            Recharge(type: 0),
            Recharge(
              type: 1,
            )
          ],
        ),
      ),
    );
  }
}

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];
        });
      }
    }
  }

  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 == 0) {
                return Padding(
                  padding: EdgeInsets.fromLTRB(15, 15, 15, 10),
                  child: Row(
                    crossAxisAlignment: CrossAxisAlignment.center,
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: <Widget>[
                      Expanded(
                        flex: 1,
                        child: ShoopingBtn('images/icon_haoli.png', '更多好礼', onTapHomeMenu: () {
                          showDialog(2);
                        }),
                      ),
                      Container(
                        width: 15,
                      ),
                      Expanded(
                        flex: 1,
                        child: ShoopingBtn('images/icon_shangwu.png', '商务合作', onTapHomeMenu: () {
                          showDialog(3);
                        }),
                      ),
                    ],
                  ),
                );
              }
              bool isChoose = false;
              if (productInfoList[index - 1].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),
                  child: Container(
                    child: Stack(
                      children: <Widget>[
                        Center(
                          child: Row(
                            mainAxisAlignment: MainAxisAlignment.center,
                            children: <Widget>[
                              Text(productInfoList[index - 1].productName,
                                  style: TextStyle(color: Color(0xFFFFFFFF), fontWeight: FontWeight.w500, fontSize: 15)),
                              Container(
                                width: 10,
                              ),
                              Text(
                                '¥' + productInfoList[index - 1].money.toString(),
                                style: TextStyle(color: Color(0xFF727785), fontWeight: FontWeight.w400, fontSize: 14),
                              )
                            ],
                          ),
                        ),
                        Positioned(
                          right: 0,
                          bottom: 0,
                          child: isChoose ? Image.asset('images/icon_xuanzhong.png') : Container(),
                        )
                      ],
                    ),
                  ),
                  onPressed: isChoose
                      ? null
                      : () {
                          setState(() {
                            chooseProduct = productInfoList[index - 1];
                          });
                        },
                ),
              );
            }),
      ),
      floatingActionButton: Container(
        width: double.infinity,
        padding: EdgeInsets.symmetric(horizontal: 15),
        height: 48,
        child: FlatButton(
          color: PRIMARY_COLOR,
          textColor: Colors.white,
          child: Text('立即充值'),
          onPressed: () async {
            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,
                  ),
                )
              ],
            ),
          )),
    );
  }
}
