import 'dart:io';

import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_swiper/flutter_swiper.dart';
import 'package:liftmanager/internal/account/provider/user_provider.dart';
import 'package:liftmanager/internal/wode/model/privilege_model.dart';
import 'package:liftmanager/net/api_service.dart';
import 'package:liftmanager/res/resources.dart';
import 'package:liftmanager/utils/toast.dart';
import 'package:liftmanager/widgets/app_bar.dart';
import 'package:liftmanager/widgets/load_image.dart';
import 'package:provider/provider.dart';

class Privilege extends StatefulWidget {
  Privilege(this.id, this.index);

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

class PrivilegeState extends State<Privilege>
    with AutomaticKeepAliveClientMixin {
  UserProvider provider = UserProvider();

  List<MenuList> privilegeList = [];
  MenuList _currentModel = MenuList();
  ScrollController _scrollController = ScrollController();
  @override
  void initState() {
    // getAllMenu();
    super.initState();
  }

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

  void getAllMenu() {
    NewApiService().getAllMenu(widget.id, onSuccess: (res) {
      setState(() {
        privilegeList = res;
        if (widget.index != null) {
          for (MenuList item in privilegeList) {
            if (item.id == int.parse(widget.index)) {
              _currentModel = item;
              int index = privilegeList.indexOf(_currentModel);
              double width = MediaQuery.of(context).size.width;
              if (index * 80 > width - 60) {
                _scrollController.animateTo(
                    _scrollController.position.maxScrollExtent,
                    duration: const Duration(milliseconds: 500),
                    curve: Curves.easeOut);
              } else {
                _scrollController.animateTo(0,
                    duration: const Duration(milliseconds: 500),
                    curve: Curves.easeOut);
              }
            }
          }

          // _currentModel = privilegeList[0];
        } else {
          _currentModel = privilegeList[0];
        }
      });
    }, onError: (code, msg) {
      privilegeList = [];
      toasts(msg);
    });
  }

  List<Widget> listWidget(context) => privilegeList.map((item) {
        // double width = MediaQuery.of(context).size.width;
        double width = MediaQuery.of(context).size.width;
        return GestureDetector(
          child: Container(
            // margin: EdgeInsets.only(right: 10),
            padding: EdgeInsets.only(top: 20, bottom: 20),
            child: Row(
              children: <Widget>[
                // SizedBox(width: ScreenUtil().setWidth( 10)),
                Container(
                  width: 80,
                  // padding: EdgeInsets.only(top: 10, bottom: 10),
                  // 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: "Iconfont"),
                      //   size: 24.0,
                      //   color: Color.fromRGBO(51, 51, 51, 1),
                      // ),
                      Container(
                        // margin: EdgeInsets.only(bottom:0),
                        child: LoadNetworkImage(
                          item.image,
                          width: 55,
                          height: 55,
                          fit: BoxFit.fitHeight,
                        ),
                      ),
                      Text(
                        item.name ?? '',
                        textAlign: TextAlign.start,
                        style: TextStyle(
                          color: _currentModel.name == item.name
                              ? Color(0xffCC9E63)
                              : Colours.text_gray_c,
                          fontSize: ScreenUtil().setSp(12),
                        ),
                      ),
                      // Text(
                      //   item.descr ?? '',
                      //   textAlign: TextAlign.start,
                      //   style: TextStyle(
                      //     fontSize: ScreenUtil().setSp(14),
                      //     color: Color(0xff999999),
                      //   ),
                      //   overflow: TextOverflow.ellipsis,
                      // ),
                    ],
                  ),
                ),
              ],
            ),
          ),
          onTap: () {
            setState(() {
              _currentModel = item;
            });
          },
        );
      }).toList();

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

    return ChangeNotifierProvider<UserProvider>(
      create: (_) {
        getAllMenu();
        return provider;
      },
      child: Container(
        child: Scaffold(
          resizeToAvoidBottomPadding: false,
          appBar: MyAppBar(
            centerTitle: "会员特权",
          ),
          body: Consumer<UserProvider>(
            builder: (_, provider, __) {
              return Container(
                child: Column(
                  children: [
                    Container(
                        height: 120,
                        child: ScrollConfiguration(
                          behavior: CusBehavior(),
                          child: ListView(
                            controller: _scrollController,
                            scrollDirection: Axis.horizontal,
                            padding: EdgeInsets.all(0.0),
                            children: listWidget(context),
                          ),
                        )),
                    Container(
                      child: SwipeWidget(
                        // banners: privilegeList,
                        defultModel: _currentModel,

                        privilegeList: privilegeList,
                        onChangItem: (int index, MenuList model) {
                          setState(() {
                            _currentModel = model;
                          });

                          print(_scrollController.offset);
                          if (index * 80 > width - 60) {
                            _scrollController.animateTo(
                                _scrollController.position.maxScrollExtent,
                                duration: const Duration(milliseconds: 500),
                                curve: Curves.easeOut);
                          } else {
                            _scrollController.animateTo(0,
                                duration: const Duration(milliseconds: 500),
                                curve: Curves.easeOut);
                          }
                        },
                        onClickItem: (int index, MenuList model) {
                          setState(() {
                            _currentModel = model;
                          });
                        },
                      ),
                    )
                  ],
                ),
              );
            },
          ),
        ),
      ),
    );
  }

  @override
  bool get wantKeepAlive => true;
}

class SwipeWidget extends StatelessWidget {
  SwipeWidget({
    Key key,
    this.privilegeList,
    this.banners,
    this.onClickItem,
    this.onChangItem,
    this.defultModel,
  }) : super(key: key);
  final List<dynamic> banners;
  final List<MenuList> privilegeList;
  final Function onClickItem;
  final Function onChangItem;
  final MenuList defultModel;

  @override
  Widget build(BuildContext context) {
    double width = MediaQuery.of(context).size.width;
    double height = 420;
    return Container(
      width: width,
      height: height,
      child: Swiper(
        itemBuilder: (BuildContext context, index) {
          return Container(
              width: width,
              height: height,
              child: Stack(
                children: [
                  Container(
                    //  alignment: Alignment.center,
                    width: 328,
                    height: height,
                    child: LoadAssetImage('img_viptag_bigbg', fit: BoxFit.fill),
                  ),
                  Container(
                    height: 40,
                    alignment: Alignment.center,
                    child: Text(
                      privilegeList[index].name,
                      style: TextStyle(color: Color(0xffFEEFE5), fontSize: 18),
                    ),
                  ),
                  Positioned(
                      left: 23,
                      top: 84,
                      right: 23,
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        // mainAxisAlignment: MainAxisAlignment.start,
                        children: [
                          Row(
                            children: [
                              Container(
                                height: 11,
                                width: 2,
                                color: Color(0xffDAB47E),
                                margin: EdgeInsets.only(right: 10),
                              ),
                              Text(
                                '权益介绍',
                                style: TextStyle(
                                    color: Color(0xff222222), fontSize: 14),
                              )
                            ],
                          ),
                          SizedBox(
                            height: 15,
                          ),
                          Row(
                            // mainAxisAlignment: MainAxisAlignment.start,
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              Container(
                                height: 6,
                                width: 6,
                                margin: EdgeInsets.only(right: 7, top: 6),
                                decoration: BoxDecoration(
                                  //背景
                                  color: Colours.text_gray,
                                  //设置四周圆角 角度
                                  borderRadius:
                                      BorderRadius.all(Radius.circular(3.0)),
                                  //设置四周边框
                                ),
                              ),
                              Container(
                                width: 240,
                                child: Text(
                                  privilegeList[index].descr,
                                  style: TextStyle(
                                      color: Colours.text_gray, fontSize: 14),
                                ),
                              )
                            ],
                          ),
                          SizedBox(
                            height: 15,
                          ),
                          // Row(
                          //   crossAxisAlignment: CrossAxisAlignment.start,
                          //   // mainAxisAlignment: MainAxisAlignment.start,
                          //   children: [
                          //     Container(
                          //       height: 6,
                          //       width: 6,
                          //       margin: EdgeInsets.only(right: 7, top: 6),
                          //       decoration: BoxDecoration(
                          //         //背景
                          //         color: Colours.text_gray,
                          //         //设置四周圆角 角度
                          //         borderRadius:
                          //             BorderRadius.all(Radius.circular(3.0)),
                          //         //设置四周边框
                          //       ),
                          //     ),
                          //     Container(
                          //       width: 240,
                          //       child: Text(
                          //         '其他权益描述文本',
                          //         maxLines: 5,
                          //         style: TextStyle(
                          //             color: Colours.text_gray, fontSize: 14),
                          //       ),
                          //     )
                          //   ],
                          // )
                        ],
                      )),
                  Positioned(
                      bottom: 35,
                      left: -10,
                      child: GestureDetector(
                          onTap: () {
                            Navigator.pop(context);
                          },
                          child: Container(
                            height: 40,
                            width: 328,
                            // color: Colors.red,
                            alignment: Alignment.center,
                            child: Text(
                              '立即开通',
                              style: TextStyle(
                                  color: Color(0xffFEEFE5), fontSize: 16),
                            ),

                            //  InkWell(
                            //   child: Text('data'),
                            // ),
                          )))
                ],
              ));
        },
        // pagination: SwiperPagination(
        //   builder: DotSwiperPaginationBuilder(
        //     color: Colors.grey,
        //     activeColor: Colors.white,
        //     size: 6,
        //     activeSize: 6,
        //   ),
        // ),
        key: UniqueKey(),
        viewportFraction: 0.8, //
        scale: 0.9,
        itemCount: privilegeList.length,
        scrollDirection: Axis.horizontal,
        loop: false,
        autoplay: false,
        index: privilegeList.indexOf(defultModel),
        //
        // autoplayDisableOnInteraction: false,
        // onTap: (index) {
        //   onClickItem(index, privilegeList[index]);
        // },
        onIndexChanged: (index) {
          onChangItem(index, privilegeList[index]);
        },
      ),
    );
  }
}

class CusBehavior extends ScrollBehavior {
  @override
  Widget buildViewportChrome(
      BuildContext context, Widget child, AxisDirection axisDirection) {
    return child;
    // if (Platform.isAndroid || Platform.isIOS) return child;
    // return super.buildViewportChrome(context, child, axisDirection);
  }
}
