import 'dart:io';

import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_html/flutter_html.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:flutter_swiper/flutter_swiper.dart';
import 'package:huixiang/generated/l10n.dart';
import 'package:huixiang/retrofit/data/base_data.dart';
import 'package:huixiang/retrofit/data/second_card_list.dart';
import 'package:huixiang/retrofit/data/vip_benefit_list.dart';
import 'package:huixiang/retrofit/retrofit_api.dart';
import 'package:huixiang/utils/flutter_utils.dart';
import 'package:huixiang/utils/font_weight.dart';
import 'package:huixiang/view_widget/border_text.dart';
import 'package:huixiang/view_widget/custom_image.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:huixiang/view_widget/my_appbar.dart';
import 'package:huixiang/view_widget/round_button.dart';
import 'package:shared_preferences/shared_preferences.dart';

class LegalRightDetails extends StatefulWidget {
  final Map<String, dynamic> arguments;

  LegalRightDetails({this.arguments});

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

class _LegalRightDetails extends State<LegalRightDetails> {
  ApiService apiService;
  List<VipBenefitList> vipBenefitList = [];
  final SwiperController controller = SwiperController();
  int checkIndex = 0;
  ScrollController _scrollController = ScrollController();
  List<SecondCardList> secondCardList = [];
  bool offsetOnEnd = false;

  @override
  void initState() {
    super.initState();
    SharedPreferences.getInstance().then((value) {
      apiService =
          ApiService(Dio(), context: context, token: value.getString("token"));
    });
    vipBenefitList.addAll(widget.arguments["vipBenefitList"]);
    querySecondCardList();
  }

  ///副卡列表
  querySecondCardList() async {
    if (apiService == null) {
      SharedPreferences value = await SharedPreferences.getInstance();
      apiService = ApiService(
        Dio(),
        context: context,
        token: value.getString("token"),
      );
    }
    BaseData<List<SecondCardList>> baseData =
        await apiService.secondCardList().catchError((onError) {});
    if (baseData != null && baseData.isSuccess) {
      setState(() {
        secondCardList.clear();
        secondCardList.addAll(baseData.data);
        if (secondCardList.length < 5) {
          var isSecondCard = SecondCardList();
          isSecondCard.isAdd = true;
          secondCardList.add(isSecondCard);
        }
      });
    }
    EasyLoading.dismiss();
  }

  ///解绑副卡
  queryUnbindSecondCard(phone) async {
    if (apiService == null) {
      SharedPreferences value = await SharedPreferences.getInstance();
      apiService = ApiService(
        Dio(),
        context: context,
        token: value.getString("token"),
      );
    }
    BaseData baseData = await apiService.unbindSecondCard(phone).catchError((onError) {});
    if (baseData != null && baseData.isSuccess) {
      querySecondCardList();
      SmartDialog.showToast("解绑成功", alignment: Alignment.center);
    } else {
      SmartDialog.showToast(baseData.msg, alignment: Alignment.center);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Color(0xFF131416),
      appBar: MyAppBar(
        title: S.of(context).quanyixiangqing,
        titleColor: Colors.white,
        titleSize: 18.sp,
        background: Colors.transparent,
        leadingColor: Colors.white,
      ),
      body: Column(
        children: [
          Container(
            height: 130,
            padding: EdgeInsets.only(top: 24),
            // margin: EdgeInsets.only(
            //     left: (MediaQuery.of(context).size.width / 2 -
            //                 48 -
            //                 checkIndex * 85) <
            //             0
            //         ? 0
            //         : (MediaQuery.of(context).size.width / 2 -
            //             48 -
            //             checkIndex * 85)),
            child: ListView.builder(
              scrollDirection: Axis.horizontal,
              physics: BouncingScrollPhysics(),
              controller: _scrollController,
              shrinkWrap: true,
              padding: EdgeInsets.symmetric(horizontal: 10),
              itemCount: vipBenefitList == null ? 0 : vipBenefitList.length,
              itemBuilder: (context, position) {
                return GestureDetector(
                  onTap: () {
                    setState(() {
                      if (checkIndex == position) return;
                      // offsetOnEnd = position - checkIndex < 0 && position != 0;
                      // int jumpIndex = (position - checkIndex).abs();
                      // int maxCountInWidth =
                      //     MediaQuery.of(context).size.width ~/ 80;
                      // int tempPosition = checkIndex;
                      // for (var i = 0; i < jumpIndex; i++) {
                      //   if (position - checkIndex < 0)
                      //     tempPosition -= 1;
                      //   else
                      //     tempPosition += 1;
                      //   checkIndex = tempPosition;
                      //   if (tempPosition <=
                      //       vipBenefitList.length - maxCountInWidth) {
                      //     if (tempPosition != 0)
                      //       _scrollController.jumpTo((_scrollController.offset +
                      //               (offsetOnEnd ? -85 : 85))
                      //           .toDouble());
                      //   } else {
                      //     _scrollController.jumpTo(
                      //         ((vipBenefitList.length - maxCountInWidth) * 85)
                      //             .toDouble());
                      //   }
                      // }
                      checkIndex = position;
                    });
                  },
                  child: legalRightItem(vipBenefitList[position], position),
                );
              },
            ),
          ),
          Expanded(
              child: Container(
            decoration: BoxDecoration(
              border: Border.all(
                width: 0,
                color: Color(0xFFFFF6E9),
              ),
              color: Color(0xFFFFF6E9),
              borderRadius: new BorderRadius.only(
                topLeft: Radius.circular(8.0),
                topRight: Radius.circular(8.0),
              ),
            ),
            child: SingleChildScrollView(
              physics: BouncingScrollPhysics(),
              child: Column(
                mainAxisAlignment: MainAxisAlignment.start,
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  SizedBox(
                    height: 20,
                  ),
                  Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    crossAxisAlignment: CrossAxisAlignment.center,
                    children: [
                      Column(
                        mainAxisAlignment: MainAxisAlignment.start,
                        crossAxisAlignment: CrossAxisAlignment.end,
                        children: [
                          Container(
                            width: 13.w,
                            height: 2.h,
                            color: Color(0xFF674119),
                          ),
                          SizedBox(height: 5.h),
                          Container(
                            width: 9.w,
                            height: 2.h,
                            color: Color(0xFF674119),
                          ),
                          SizedBox(height: 5.h),
                          Container(
                            width: 6.5.w,
                            height: 2.h,
                            color: Color(0xFF674119),
                          ),
                        ],
                      ),
                      SizedBox(width: 6.w),
                      Text(
                        vipBenefitList[checkIndex].name,
                        style: TextStyle(
                          fontSize: 17.sp,
                          fontWeight: FontWeight.bold,
                          color: Color(0xFF674119),
                        ),
                      ),
                      SizedBox(width: 6.w),
                      Column(
                        mainAxisAlignment: MainAxisAlignment.start,
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Container(
                            width: 13.w,
                            height: 2.h,
                            color: Color(0xFF674119),
                          ),
                          SizedBox(height: 5.h),
                          Container(
                            width: 9.w,
                            height: 2.h,
                            color: Color(0xFF674119),
                          ),
                          SizedBox(height: 5.h),
                          Container(
                            width: 6.5.w,
                            height: 2.h,
                            color: Color(0xFF674119),
                          ),
                        ],
                      ),
                    ],
                  ),
                  Container(
                    padding: EdgeInsets.only(left: 16, right: 49),
                    child: Column(
                      mainAxisAlignment: MainAxisAlignment.start,
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Text(
                          S.of(context).quanyijishao,
                          style: TextStyle(
                            fontWeight: MyFontWeight.semi_bold,
                            fontSize: 14.sp,
                            color: Color(0xFF674119),
                          ),
                        ),
                        SizedBox(
                          height: 8.h,
                        ),
                        if (vipBenefitList[checkIndex]?.introduce != null &&
                            vipBenefitList[checkIndex].introduce != "")
                          Container(
                            color: Color(0xFFFFF6E9),
                            child: Html(
                              data: vipBenefitList[checkIndex]?.introduce ?? "",
                              style: {
                                "html": Style(
                                  color: Color(0xFF674119),
                                ),
                              },
                              customImageRenders: {
                                networkSourceMatcher(): networkImageRender(
                                  loadingWidget: () {
                                    return Container();
                                  },
                                ),
                              },
                            ),
                          ),
                        SizedBox(
                          height: 20,
                        ),
                        Text(
                          S.of(context).quanyishuoming,
                          style: TextStyle(
                            fontWeight: MyFontWeight.semi_bold,
                            fontSize: 14.sp,
                            color: Color(0xFF674119),
                          ),
                        ),
                        SizedBox(
                          height: 8,
                        ),
                        if (vipBenefitList[checkIndex]?.describes != null &&
                            vipBenefitList[checkIndex].describes != "")
                          Container(
                            color: Color(0xFFFFF6E9),
                            child: Html(
                              data: vipBenefitList[checkIndex]?.describes ?? "",
                              style: {
                                "html": Style(
                                  color: Color(0xFF674119),
                                ),
                              },
                              customImageRenders: {
                                networkSourceMatcher(): networkImageRender(
                                  loadingWidget: () {
                                    return Container();
                                  },
                                ),
                              },
                            ),
                          ),
                        SizedBox(
                          height: 20,
                        ),
                        if (vipBenefitList[checkIndex].name == "副卡" &&
                            vipBenefitList[checkIndex].actived &&
                            vipBenefitList[checkIndex].have)
                          Container(
                            child: Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              mainAxisAlignment: MainAxisAlignment.start,
                              children: [
                                Text(
                                  "${S.of(context).yibangfuka}(${secondCardList.length - (secondCardList.length >= 5 && !(secondCardList.last.isAdd ?? false) ? 0 : 1)}/5)",
                                  style: TextStyle(
                                    fontWeight: MyFontWeight.semi_bold,
                                    fontSize: 14.sp,
                                    color: Color(0xFF674119),
                                  ),
                                ),
                                SizedBox(
                                  height: 8,
                                ),
                                assistant(),
                              ],
                            ),
                          ),
                      ],
                    ),
                  ),
                ],
              ),
            ),
          ))
        ],
      ),
    );
  }

  ///解除绑定弹窗
  unbindShowDeleteDialog(phone) {
    showDialog(
      context: context,
      builder: (context) {
        return AlertDialog(
          content: Container(
            width: MediaQuery.of(context).size.width - 84,
            height: 146.h,
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                Text(
                  "确认要跟当前用户解除绑定?",
                  style: TextStyle(
                    fontSize: 17.sp,
                    fontWeight: MyFontWeight.medium,
                    color: Color(0xFF353535),
                  ),
                ),
                SizedBox(
                  height: 6.h,
                ),
                Text(
                  "剩余解绑次数:3次",
                  style: TextStyle(
                    fontSize: 12.sp,
                    fontWeight: MyFontWeight.medium,
                    color: Color(0xFFA29E9E),
                  ),
                ),
                SizedBox(
                  height: 16.h,
                ),
                Row(
                  children: [
                    Expanded(
                      child: InkWell(
                        child: BorderText(
                          text: "取消",
                          textColor: Color(0xFF32A060),
                          fontSize: 16.sp,
                          fontWeight: FontWeight.bold,
                          borderColor: Color(0xFF32A060),
                          radius: 4,
                          padding: EdgeInsets.all(12),
                          borderWidth: 1,
                        ),
                        onTap: () {
                          Navigator.of(context).pop();
                        },
                      ),
                      flex: 1,
                    ),
                    SizedBox(
                      width: 16.w,
                    ),
                    Expanded(
                      child: InkWell(
                        child: RoundButton(
                          text: "确定",
                          textColor: Colors.white,
                          radius: 4,
                          padding: EdgeInsets.all(12),
                          backgroup: Color(0xFF32A060),
                          fontSize: 16.sp,
                          fontWeight: FontWeight.bold,
                        ),
                        onTap: () {
                          setState(() {
                            queryUnbindSecondCard(phone);
                            Navigator.of(context).pop();
                          });
                        },
                      ),
                      flex: 1,
                    ),
                  ],
                )
              ],
            ),
          ),
        );
      },
    );
  }

  ///权益列表
  Widget legalRightItem(VipBenefitList vipBenefitList, index) {
    return Column(
      children: [
        Expanded(
            child: Opacity(
          opacity: index == checkIndex ? 1 : 0.6,
          child: Container(
            width: 80,
            alignment: Alignment.center,
            child: Column(
              children: [
                Stack(
                  alignment: Alignment.bottomCenter,
                  children: [
                    MImage(
                      vipBenefitList?.icon ?? "",
                      width:51,
                      height: 51,
                      isCircle: true,
                      errorSrc: "assets/image/default_1.webp",
                      fadeSrc: "assets/image/default_1.webp",
                    ),
                    if (!vipBenefitList.actived || !vipBenefitList.actived && !vipBenefitList.have)
                      Container(
                        decoration: new BoxDecoration(
                          color: Color(0xFFA29E9E),
                          borderRadius: BorderRadius.circular(7.0),
                        ),
                        width: 52.w,
                        height: 15.h,
                        child: Row(
                          crossAxisAlignment: CrossAxisAlignment.center,
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: [
                            Icon(
                              Icons.lock,
                              color: Color(0xFFFFDCA1),
                              size: 10,
                            ),
                            Text(
                              "暂未开放",
                              style: TextStyle(
                                color: Color(0xFFFFDCA1),
                                fontWeight: MyFontWeight.regular,
                                fontSize: 9.sp,
                              ),
                            ),
                          ],
                        ),
                      ),
                    if ( vipBenefitList.actived && !vipBenefitList.have)
                      Container(
                        decoration: new BoxDecoration(
                          color: Color(0xFFA29E9E),
                          borderRadius: BorderRadius.circular(7.0),
                        ),
                        width: 52.w,
                        height: 15.h,
                        child: Row(
                          crossAxisAlignment: CrossAxisAlignment.center,
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: [
                            Icon(
                              Icons.lock,
                              color: Color(0xFFFFDCA1),
                              size: 10,
                            ),
                            Text(
                              "暂未解锁",
                              style: TextStyle(
                                color: Color(0xFFFFDCA1),
                                fontWeight: MyFontWeight.regular,
                                fontSize: 9.sp,
                              ),
                            ),
                          ],
                        ),
                      ),
                  ],
                ),
                SizedBox(
                  height: 8.h,
                ),
                Text(
                  vipBenefitList.name,
                  maxLines: 2,
                  overflow: TextOverflow.ellipsis,
                  textAlign: TextAlign.center,
                  style: TextStyle(
                    color: Colors.white,
                    fontWeight: MyFontWeight.regular,
                    fontSize: 12.sp,
                  ),
                ),
              ],
            ),
          ),
        )),
        if (index == checkIndex)
          Container(
            width: 33,
            height: 16,
            decoration: BoxDecoration(
              border: Border(
                bottom: BorderSide(
                  width: 0,
                  color: Color(0xFFFFF6E9),
                ),
              ),
            ),
            child: Image.asset(
              "assets/image/jian_j.webp",
              width: 33,
              height: 16,
              color: Color(0xFFFFF6E9),
              fit: BoxFit.fill,
            ),
          ),
      ],
    );
  }

  ///副卡列表
  Widget assistant() {
    return Column(
      children: [
        GridView.builder(
          itemCount: secondCardList == null ? 0 : secondCardList.length,
          shrinkWrap: true,
          physics: NeverScrollableScrollPhysics(),
          gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
            //一行的Widget数量
            crossAxisCount: 3,
            //水平子Widget之间间距
            crossAxisSpacing: 12,
            //垂直子Widget之间间距
            mainAxisSpacing: 5,
            //子Widget宽高比例
            childAspectRatio: 1.2,
          ),
          itemBuilder: (context, index) {
            return GestureDetector(
              onTap: () {},
              child: assistantItem(secondCardList[index]),
            );
          },
        ),
      ],
    );
  }

  Widget assistantItem(SecondCardList secondCardList) {
    return Container(
      alignment: Alignment.center,
      child: !(secondCardList.isAdd ?? false)
          ? Column(
              children: [
                Stack(
                  alignment: Alignment.bottomRight,
                  children: [
                    MImage(
                      secondCardList?.headimg ?? "",
                      width: 50,
                      height: 50,
                      isCircle: true,
                      fit: BoxFit.cover,
                      errorSrc: "assets/image/default_1.webp",
                      fadeSrc: "assets/image/default_1.webp",
                    ),
                    GestureDetector(
                      onTap: () {
                        setState(() {
                          unbindShowDeleteDialog(secondCardList.phone);
                        });
                      },
                      child: Image.asset(
                        "assets/image/fuka_j.webp",
                        width: 24,
                        height: 24,
                        fit: BoxFit.cover,
                      ),
                    ),
                  ],
                ),
                SizedBox(
                  height: 5.h,
                ),
                Text(
                  AppUtils.phoneEncode(secondCardList?.phone ?? ""),
                  style: TextStyle(
                    color: Color(0xFF79572D),
                    fontWeight: MyFontWeight.regular,
                    fontSize: 12.sp,
                  ),
                ),
              ],
            )
          : GestureDetector(
              onTap: () {
                Navigator.of(context)
                    .pushNamed('/router/binding_assistant_card')
                    .then((value) => {querySecondCardList()});
              },
              child: Column(
                children: [
                  Image.asset(
                    "assets/image/fuka_zj.webp",
                    width: 50,
                    height: 50,
                    fit: BoxFit.cover,
                  ),
                  Text(
                    "添加新副卡",
                    style: TextStyle(
                      color: Color(0xFF79572D),
                      fontWeight: MyFontWeight.regular,
                      fontSize: 12.sp,
                    ),
                  ),
                ],
              ),
            ),
    );
  }
}