import 'package:flutter/material.dart';
import 'package:fake_push/fake_push.dart';
import 'package:liftmanager/net/api_service.dart';
import 'package:liftmanager/utils/toast.dart';
import 'package:liftmanager/widgets/app_bar.dart';
import 'package:provider/provider.dart';
import 'package:liftmanager/internal/account/provider/user_provider.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_swiper/flutter_swiper.dart';
import 'package:liftmanager/widgets/load_image.dart';
import 'package:liftmanager/widgets/bbs_content.dart';
import 'package:liftmanager/routers/fluro_navigator.dart';
import 'package:liftmanager/common/user_db.dart';
import 'package:liftmanager/internal/bbs/provide/websocket.dart';
import 'package:liftmanager/common/common.dart';
import 'package:liftmanager/internal/account/account_router.dart';
import 'package:liftmanager/internal/wode/wode_router.dart';
import 'package:flustars/flustars.dart' as flustars;
import 'package:liftmanager/internal/wode/model/privilege_model.dart';
import 'package:liftmanager/utils/theme_utils.dart';

class Vip extends StatefulWidget {
  Vip(this.id);

  final String id;
  @override
  State<StatefulWidget> createState() {
    return VipState();
  }
}

class VipState extends State<Vip> with AutomaticKeepAliveClientMixin {
  UserProvider provider = UserProvider();
  Push _push = Push();

  int currentIndex = -1;

  List<PrivilegeModel> vipList = [];

  void getMemberAllMenu() {
    NewApiService().getMemberAllMenu(onSuccess: (res) {
      vipList = res;
      currentIndex = res.length > 0 ? 0 : -1;
      setState(() {});
    }, onError: (code, msg) {
      vipList = [];
      toasts(msg);
    });
  }

  bool vip = false;
  Future isVipOrExpert() async{
    await NewApiService().getIsVipOrExpert(onSuccess: (res) {
      if(res != null){
        vip = true;
      }
    }, onError: (code, msg) {
      toasts(msg);
    });
  }

  Future becomeLowerMember() async{
    await NewApiService().getUserRebates(widget.id,
          onSuccess: (res) {
            toasts("你已成功接受${res!=null?res.toString():''}的邀请，立即成为会员！",timeInSecForIos:2);
            // toasts("您已成为${res!=null?res.toString():''}的下级用户");
            
      }, onError: (code, msg) {
        toasts(msg);
      });
  }

  void updateVip(userLevel) {
    NewApiService().updateVip(userLevel, onSuccess: (res) {
      toasts("充值成功，请重新登录");
      setState(() {});
      User().clearUser();
      Provider.of<WebSocketProvide>(context, listen: false).closeWebSocket();
      // removeSocket();
      _push.unbindAccount(account: flustars.SpUtil.getString(Constant.phone));
      NavigatorUtils.push(context, AccountRouter.loginPage, clearStack: true);
    }, onError: (code, msg) {
      toasts(msg);
    });
  }

  @override
  void initState() {
    getMemberAllMenu();
    super.initState();
    print(widget.id);
    print(66666);
    if(widget.id != null && widget.id != ""){
      print("触发绑定");
      becomeLowerMember();
    }
  }

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

  @override
  Widget build(BuildContext context) {
    double width = MediaQuery.of(context).size.width;
    double height = MediaQuery.of(context).size.height;

    return ChangeNotifierProvider<UserProvider>(
      create: (_) => provider,
      child: Container(
        child: Scaffold(
          resizeToAvoidBottomPadding: false,
          appBar: MyAppBar(
            centerTitle: "会员中心",
          ),
          body: Consumer<UserProvider>(
            builder: (_, provider, __) {
              return ListView(
                padding: EdgeInsets.all(0.0),
                children: <Widget>[
                  Container(
                    padding:
                        EdgeInsets.only(left: 20.0, right: 20.0, top: 10.0),
                    // height: ScreenUtil().setWidth(345),
                    child: Column(
                      children: <Widget>[
                        vipList.length > 0
                            ? SwipeWidget(
                                banners: vipList,
                                onClickItem: (index, item) {
                                  // showAlert(
                                  //   context,
                                  //   "提示",
                                  //   "您确定需要充值升级为Vip吗？",
                                  //   "确认",
                                  //   () {
                                  //     // updateVip(item.id);
                                  //     // NavigatorUtils.goBack(context);

                                  //   },
                                  //   txt2: "取消",
                                  //   onPre2: () {
                                  //     NavigatorUtils.goBack(context);
                                  //   },
                                  // );
                                  // print(333);
                                  // print(provider);
                                  NavigatorUtils.push(context,
                                        "${WodeRouter.vipService}?id=${item.id.toString()}");
                                  
                                },
                                onChangItem: (index, item) {
                                  currentIndex = index;
                                  setState(() {});
                                },
                              )
                            : Container()
                      ],
                    ),
                  ),
                  LableTitle(
                    title: "会员特权",
                    isMore: true,
                    userTap: () {
                      if (currentIndex != -1) {
                        NavigatorUtils.push(context,
                            "${WodeRouter.privilege}?id=${vipList[currentIndex].id.toString()}");
                      }
                    },
                  ),
                  Container(
                    color: ThemeUtils.getTabsBg(context),
                    height: ScreenUtil().setWidth(150),
                    padding: EdgeInsets.only(
                      top: ScreenUtil().setWidth(5),
                      left: ScreenUtil().setWidth(10),
                      right: ScreenUtil().setWidth(10),
                    ),
                    child: Privilege(
                        initList: currentIndex != -1
                            ? vipList[currentIndex].menuList
                            : []),
                  ),
                  LableTitle(
                    title: "邀请好友",
                    isMore: false,
                    userTap: () {},
                  ),
                  GestureDetector(
                    onTap: () async{
                      await isVipOrExpert();
                                  if (vip) {
                                    NavigatorUtils.push(context, "${WodeRouter.qrshare}");
                                    vip = false;
                                  } else {
                                    print(999);
                                    toasts("请开通会员或成为专家");
                                  }
                    },
                    child: Container(
                      color: ThemeUtils.getTabsBg(context),
                      height: ScreenUtil().setWidth(110),
                      padding: EdgeInsets.only(
                        top: ScreenUtil().setWidth(10),
                        left: ScreenUtil().setWidth(10),
                        right: ScreenUtil().setWidth(10),
                      ),
                      child: LoadAssetImage(
                        "wode/invite_friends",
                        width: ScreenUtil().setWidth(724),
                        height: ScreenUtil().setWidth(183),
                      ),
                    ),
                  )
                ],
              );
            },
          ),
        ),
      ),
    );
  }

  @override
  bool get wantKeepAlive => true;
}

class SwipeWidget extends StatelessWidget {
  const SwipeWidget({Key key, this.banners, this.onClickItem, this.onChangItem})
      : super(key: key);
  final List<dynamic> banners;
  final Function onClickItem;
  final Function onChangItem;
  @override
  Widget build(BuildContext context) {
    double width = MediaQuery.of(context).size.width;
    double height = ScreenUtil().setWidth(180);
    return Container(
      width: width,
      height: height,
      child: Swiper(
        itemBuilder: (BuildContext context, index) {
          return Container(
            width: width,
            height: height,
            child: LoadNetworkImage(
              banners[index].image,
              width: width,
              height: height,
              // fit: BoxFit.none
            ),
          );
        },
        pagination: SwiperPagination(
          builder: DotSwiperPaginationBuilder(
            color: Colors.grey,
            activeColor: Colors.white,
            size: 6,
            activeSize: 6,
          ),
        ),
        itemCount: banners.length,
        scrollDirection: Axis.horizontal,
        autoplay: false,
        onTap: (index) {
          onClickItem(index, banners[index]);
        },
        onIndexChanged: (index) {
          onChangItem(index, banners[index]);
        },
      ),
    );
  }
}

class Privilege extends StatelessWidget {
  const Privilege({Key key, this.initList}) : super(key: key);
  final List<dynamic> initList;

  List<Widget> listWidget(context) => initList.asMap().keys.map((i) {
        double width = MediaQuery.of(context).size.width;
        return GestureDetector(
          child: Container(
            margin: EdgeInsets.only(right: 10),
            padding: EdgeInsets.only(top: 10, bottom: 10),
            child: Row(
              children: <Widget>[
                SizedBox(width: ScreenUtil().setWidth(i == 0 ? 10 : 10)),
                Container(
                  width: ScreenUtil().setWidth(120),
                  padding: EdgeInsets.only(top: 20, bottom: 20),
                  decoration: BoxDecoration(
                    color: ThemeUtils.getTabsBg(context),
                    borderRadius: BorderRadius.circular(5),
                    boxShadow: [
                      BoxShadow(
                        offset: Offset(0, 0), //x,y轴
                        color: Colors.grey[300], //投影颜色
                        blurRadius: 5, //投影距离
                      )
                    ],
                  ),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.center,
                    children: <Widget>[
                      // Icon(
                      //   IconData(initList[i]['icon'], fontFamily: "myfont"),
                      //   size: 24.0,
                      //   color: Color.fromRGBO(51, 51, 51, 1),
                      // ),
                      Container(
                        margin: EdgeInsets.only(bottom: 8),
                        child: LoadNetworkImage(
                          initList[i].image,
                          width: 30,
                          height: 30,
                        ),
                      ),
                      Text(
                        initList[i].name ?? '',
                        textAlign: TextAlign.start,
                        style: TextStyle(
                          fontSize: ScreenUtil().setSp(14),
                        ),
                      ),
                      Text(
                        initList[i].descr ?? '',
                        textAlign: TextAlign.start,
                        style: TextStyle(
                          fontSize: ScreenUtil().setSp(14),
                          color: Color(0xff999999),
                        ),
                        overflow: TextOverflow.ellipsis,
                      ),
                    ],
                  ),
                ),
              ],
            ),
          ),
          onTap: () {
            // print(i);
          },
        );
      }).toList();

  @override
  Widget build(BuildContext context) {
    return ListView(
      scrollDirection: Axis.horizontal,
      padding: EdgeInsets.all(0),
      children: listWidget(context),
    );
  }
}
