import 'dart:io';

import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';

import 'package:flutter_swiper/flutter_swiper.dart';
import 'package:liftmanager/common/common.dart';
import 'package:liftmanager/internal/account/provider/user_provider.dart';
import 'package:liftmanager/internal/means/page/means_pdf.dart';
import 'package:liftmanager/internal/wode/model/privilege_model.dart';
import 'package:liftmanager/internal/wode/model/user_xieyi_model.dart';
import 'package:liftmanager/internal/work/work_router.dart';
import 'package:liftmanager/net/api_service.dart';
import 'package:liftmanager/res/resources.dart';
import 'package:liftmanager/routers/fluro_navigator.dart';
import 'package:liftmanager/utils/toast.dart';
import 'package:liftmanager/widgets/app_bar.dart';
import 'package:liftmanager/widgets/click_item.dart';
import 'package:liftmanager/widgets/load_image.dart';
import 'package:path_provider/path_provider.dart';
import 'package:provider/provider.dart';
import 'package:flustars/flustars.dart' as FlutterStars;

class UserXieyiPage extends StatefulWidget {
  UserXieyiPage();

  @override
  State<StatefulWidget> createState() {
    return UserXieyiPageState();
  }
}

class UserXieyiPageState extends State<UserXieyiPage>
    with AutomaticKeepAliveClientMixin {
  UserProvider provider = UserProvider();

  List<UserXieyi> datas = [];

  // UserXieyi datamodel = UserXieyi();
  @override
  void initState() {
    // getAllMenu();
    super.initState();
  }

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

  void getDataList() {
    NewApiService().getUserXieYi(FlutterStars.SpUtil.getString(Constant.userId),
        onSuccess: (res) {
      setState(() {
        datas = res ?? UserXieyi();
      });
    }, onError: (code, msg) {
      toasts(msg);
    });
  }

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

    return ChangeNotifierProvider<UserProvider>(
      create: (_) {
        getDataList();
        return provider;
      },
      child: Container(
        child: Scaffold(
          resizeToAvoidBottomPadding: false,
          appBar: MyAppBar(
            centerTitle: "用户协议",
          ),
          body: Consumer<UserProvider>(
            builder: (_, provider, __) {
              return ListView.builder(
                itemCount: datas.length,
                itemBuilder: (BuildContext context, int index) {
                  return ClickItem(
                      title: "${datas[index].name}",
                      content: "",
                      onTap: () {
                        createFileOfPdfUrl("${datas[index].url}").then((f) {
                          Navigator.push(
                              context,
                              MaterialPageRoute(
                                  builder: (context) =>
                                      PDFScreen(f.path, "null", "null")));
                          // });
                        });
                        // NavigatorUtils.push(
                        //   context,
                        //   "${WorkRouter.webview}?title=" +
                        //       Uri.encodeComponent("${datas[index].name}") +
                        //       "&url=" +
                        //       Uri.encodeComponent("${datas[index].url}"),
                        // );
                      });
                },
              );
            },
          ),
        ),
      ),
    );
  }

  @override
  bool get wantKeepAlive => true;

  Future<File> createFileOfPdfUrl(url) async {
    final filename = url.substring(url.lastIndexOf("/") + 1);
    var request = await HttpClient().getUrl(Uri.parse(url));
    var response = await request.close();
    var bytes = await consolidateHttpClientResponseBytes(response);
    String dir = (await getApplicationDocumentsDirectory()).path;
    File file = new File('$dir/$filename');
    await file.writeAsBytes(bytes);
    return file;
  }
}

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: Container(
                          height: 40,
                          width: 328,
                          alignment: Alignment.center,
                          child: GestureDetector(
                            onTap: () {
                              Navigator.pop(context);
                            },
                            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);
  }
}
