import 'dart:io';

import 'package:flutter/material.dart';
import 'package:redux/redux.dart';
import 'package:flutter_redux/flutter_redux.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/cupertino.dart';
import '../redux/AppState.dart';
import '../model/UserInfo.dart';
import '../pages/MyWallet.dart';
import '../pages/BindGame.dart';
import '../pages/RecordList.dart';
import '../net/HttpManager.dart';
import '../net/Result.dart';
import '../redux/UserRedux.dart';
import '../pages/UserChange.dart';
import '../pages/MyTeam.dart';
import '../pages/MyCode.dart';
import '../widget/LinearButton.dart';
import 'Setting.dart';
import 'ShoppingMall.dart';
import '../model/CustomerService.dart';

class UserPage extends StatefulWidget {
  @override
  _UserPageState createState() => _UserPageState();
}

class _UserPageState extends State<UserPage> with WidgetsBindingObserver {
  CustomerService customerService;
  bool isManage = false;
  String iosPayHide = '';
  bool showPay = false;

  Future<void> getUserInfo() async {
    Result res3 = await HttpManager.get('systemVariable/get', data: {'name': "iosPayHide"});
    print('iospayHiden:');
    print(res3.data);
    setState(() {
      iosPayHide = res3.data;
      showPay = true;
    });
    Result res = await HttpManager.get('userInfo/getUserInfo');
    if (res.success) {
      print(res.data);
      StoreProvider.of<AppState>(context).dispatch(UpdateUserAction(UserInfo.fromJson(res.data)));

      if (res.data['channel'] != null) {
        Result res2 = await HttpManager.get('channelInfo/getChannelInfo', data: {"id": res.data['channel']});
        print(res2.data);
        if (res2.success) {
          if (res2.data['channelManager'] != null && res2.data['channelManager'] == res.data['id']) {
            setState(() {
              isManage = true;
            });
          } else {
            setState(() {
              isManage = false;
            });
          }
        }
      }
    } else {}

    Result res2 = await HttpManager.get('customerService/random');
    if (res2.success) {
      setState(() {
        customerService = CustomerService.fromJson(res2.data);
      });
    }
  }

  @override
  void initState() {
    super.initState();
    Future.delayed(Duration.zero, () => getUserInfo());
  }

  @override
  Widget build(BuildContext context) {
    return StoreConnector<AppState, UserInfo>(
        converter: (Store store) => store.state.userInfo,
        builder: (context, userInfo) {
          return Scaffold(
            body: Container(
              color: Color(0xFF2E3049),
              height: double.infinity,
              width: double.infinity,
              child: SingleChildScrollView(
                child: Column(
                  children: <Widget>[
                    Container(
                      height: 250,
                      decoration: BoxDecoration(image: DecorationImage(image: AssetImage('images/info_img_bg.png'), fit: BoxFit.cover)),
                      child: SafeArea(
                        child: Column(
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: <Widget>[
                            InkWell(
                              child: ClipOval(
                                  child: CachedNetworkImage(
                                imageUrl: userInfo.icon,
                                width: 76,
                                height: 76,
                                fit: BoxFit.cover,
                              )),
                              onTap: () {
                                Navigator.push(context, CupertinoPageRoute(builder: (context) => UserChange()));
                              },
                            ),
                            Container(
                              height: 2,
                            ),
                            Text(
                              userInfo.nickname + (isManage ? '(代理)' : ''),
                              style: TextStyle(fontSize: 20, color: Colors.white, fontWeight: FontWeight.w700),
                            ),
                            Container(
                              height: 5,
                            ),
                            Row(
                              mainAxisAlignment: MainAxisAlignment.center,
                              children: <Widget>[
                                Text(
                                  '我的积分',
                                  style: TextStyle(fontSize: 14, color: Color(0xFFFFB726), fontWeight: FontWeight.w700),
                                ),
                                Container(
                                  width: 5,
                                ),
                                Image.asset('images/icon_jifen.png'),
                                Text(
                                  'x${userInfo.moneyCoin}',
                                  style: TextStyle(fontSize: 14, color: Color(0xFFFFB726), fontWeight: FontWeight.w700),
                                ),
                                Container(
                                  width: 10,
                                ),
                                customerService != null
                                    ? Text(
                                        '客服QQ:${customerService.qq}',
                                        style: TextStyle(fontSize: 14, color: Colors.white, fontWeight: FontWeight.w600),
                                      )
                                    : Container(),
                              ],
                            ),
                            Container(
                              height: 20,
                            ),
                            Row(
                              mainAxisAlignment: MainAxisAlignment.spaceAround,
                              children: <Widget>[
                                // Container(
                                //   width: 165,
                                //   child: LinearButton(
                                //     btntext: '发起比赛',
                                //     btnHeight: 38.0,
                                //     colorList: [Colors.white, Colors.white],
                                //     textColor: Color(0xFF252532),
                                //     textSize: 13.0,
                                //     onTapHomeMenu: () {
                                //       Navigator.push(context, CupertinoPageRoute(builder: (context) => OpenRoom(roomFlag: '0')));
                                //     },
                                //   ),
                                // ),
                                !showPay
                                    ? Container()
                                    : (Platform.isIOS && iosPayHide == 'true'
                                        ? Container()
                                        : Container(
                                            width: 250,
                                            child: LinearButton(
                                              btntext: '充值参赛券',
                                              btnHeight: 38.0,
                                              textSize: 13.0,
                                              onTapHomeMenu: () {
                                                Navigator.push(context, CupertinoPageRoute(builder: (context) => ShoppingMall()));
                                              },
                                            )))
                              ],
                            )
                          ],
                        ),
                      ),
                    ),
                    DrawerMenu(
                      'images/info1.png',
                      '我的参赛券',
                      tipValue: userInfo.moneyTicket,
                      onTap: () {
                        Navigator.push(context, CupertinoPageRoute(builder: (context) => MyWallet()));
                      },
                    ),
                    // Divder(),
                    // DrawerMenu(
                    //   'images/icon_fangka.png',
                    //   '房卡人数',
                    //   tipValue: userInfo.houseCard,
                    //   onTap: () {
                    //     Navigator.push(context, CupertinoPageRoute(builder: (context) => RoomCardList()));
                    //   },
                    // ),
                    Divder(),
                    DrawerMenu('images/icon_zhanji.png', '我的战绩', onTap: () {
                      Navigator.push(context, CupertinoPageRoute(builder: (context) => RecordList()));
                    }),
                    !showPay ? Container() : (Platform.isIOS && iosPayHide == 'true' ? Container() : Divder()),
                    // DrawerMenu(
                    //   'images/icon_bangding.png',
                    //   '游戏绑定',
                    //   onTap: () {
                    //     Navigator.push(context, CupertinoPageRoute(builder: (context) => BindGame()));
                    //   },
                    // ),
                    // Divder(),
                    !showPay
                        ? Container()
                        : (Platform.isIOS && iosPayHide == 'true'
                            ? Container()
                            : DrawerMenu(
                                'images/icon_tuandui.png',
                                '我的团队',
                                onTap: () {
                                  Navigator.push(context, CupertinoPageRoute(builder: (context) => MyTeam()));
                                },
                              )),
                    !showPay ? Container() : (Platform.isIOS && iosPayHide == 'true' ? Container() : Divder()),
                    !showPay
                        ? Container()
                        : (Platform.isIOS && iosPayHide == 'true'
                            ? Container()
                            : DrawerMenu(
                                'images/icon_tuiguangma.png',
                                '我的推广码',
                                onTap: () {
                                  Navigator.push(context, CupertinoPageRoute(builder: (context) => MyCode()));
                                },
                              )),
                  ],
                ),
              ),
            ),
            floatingActionButton: Container(
                width: 53,
                height: 130,
                // color: Colors.white,
                padding: EdgeInsets.fromLTRB(0, 90, 10, 0),
                child: GestureDetector(
                    onTap: () {
                      Navigator.push(context, CupertinoPageRoute(builder: (context) => Setting()));
                    },
                    child: Image.asset('images/info_icon_shezhi.png'))),
            floatingActionButtonLocation: FloatingActionButtonLocation.endTop,
          );
        });
  }
}

typedef void OnDrawerMenuTap();

class Divder extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Container(
      height: 1,
      padding: EdgeInsets.fromLTRB(55, 0, 15, 0),
      child: Container(
        decoration: BoxDecoration(color: Color(0x2E000000)),
      ),
    );
  }
}

class DrawerMenu extends StatelessWidget {
  final String icon;
  final String title;
  final OnDrawerMenuTap onTap;
  final num tipValue;
  DrawerMenu(this.icon, this.title, {this.onTap, this.tipValue});
  @override
  Widget build(BuildContext context) {
    return Container(
      height: 60,
      padding: EdgeInsets.fromLTRB(15, 0, 15, 0),
      child: GestureDetector(
        onTap: onTap,
        child: Row(
          children: <Widget>[
            Image.asset(icon),
            Expanded(
              flex: 1,
              child: Container(
                margin: EdgeInsets.only(left: 16),
                child: Text(
                  title,
                  style: TextStyle(color: Colors.white, fontSize: 15, fontWeight: FontWeight.w400),
                ),
              ),
            ),
            tipValue != null
                ? Text(
                    tipValue.toString(),
                    style: TextStyle(fontSize: 13, color: Theme.of(context).primaryColor, fontWeight: FontWeight.w600),
                  )
                : Container(),
            Image.asset('images/icon_inter.png')
          ],
        ),
      ),
    );
  }
}
