import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:huixiang/generated/l10n.dart';
import 'package:huixiang/data/base_data.dart';
import 'package:huixiang/data/vip_benefit.dart';
import 'package:huixiang/retrofit/retrofit_api.dart';
import 'package:huixiang/utils/font_weight.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:shared_preferences/shared_preferences.dart';

import 'custom_image.dart';

class VipDialog extends StatefulWidget {
  final String vipName;

  VipDialog(this.vipName);

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

class _VipDialog extends State<VipDialog> {
  ApiService? apiService;
  List<VipBenefit> vipBenefitList = [];

  @override
  void initState() {
    super.initState();

    SharedPreferences.getInstance().then((value) {
      apiService = ApiService(Dio(),
        context: context,
        token: value.getString("token") ?? "",
      );
      queryBenefitList();
    });
  }

  ///会员权益列表
  queryBenefitList() async {
    BaseData<List<VipBenefit>>? baseData = await apiService?.benefitList().catchError((onError) {});
    if (baseData?.isSuccess ?? false) {
      setState(() {
        if (baseData!.data?.isNotEmpty ?? false) {
          vipBenefitList.clear();
          vipBenefitList.addAll(baseData.data!);
          vipBenefitList.sort((a, b) => ((a.sort ?? 0)).compareTo((b.sort ?? 0)));
        }
      });
    }
    EasyLoading.dismiss();
  }

  @override
  Widget build(BuildContext context) {
    return SimpleDialog(
      titlePadding: EdgeInsets.all(10),
      backgroundColor: Colors.transparent,
      elevation: 0,
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.circular(6),
      ),
      children: <Widget>[
        Stack(
          alignment: Alignment.topCenter,
          children: [
            Container(
              margin: EdgeInsets.only(top:50.h),
              decoration: BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.circular(8),
              ),
              child: Column(
                children: [
                  Container(
                    alignment: Alignment.center,
                    width: double.infinity,
                    height: 92,
                    padding: EdgeInsets.only(top: 40.h, bottom: 19.h),
                    decoration: BoxDecoration(
                      color: Colors.black,
                      borderRadius: BorderRadius.only(
                        topLeft: Radius.circular(8),
                        topRight: Radius.circular(8),
                      ),
                    ),
                    child: Text(
                      "${S.of(context).gongxinchengwei}${widget.vipName}",
                      style: TextStyle(
                        color: Colors.white,
                        fontSize: 18.sp,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                  ),
                  Padding(
                    padding: EdgeInsets.only(top: 16.h, bottom: 19.h),
                    child: Text(
                      S.of(context).huodequanyi,
                      style: TextStyle(
                        color: Colors.black,
                        fontSize: 14.sp,
                        fontWeight: MyFontWeight.medium,
                      ),
                    ),
                  ),
                  Container(
                      width: MediaQuery.of(context).size.width,
                      height: ((((vipBenefitList == null
                                                  ? 0
                                                  : vipBenefitList.length) ~/
                                              3 +
                                          ((vipBenefitList == null
                                                          ? 0
                                                          : vipBenefitList
                                                              .length) %
                                                      3 >
                                                  0
                                              ? 1
                                              : 0)) *
                                      90.h) >
                                  MediaQuery.of(context).size.height / 2
                              ? MediaQuery.of(context).size.height / 2
                              : (((vipBenefitList == null
                                              ? 0
                                              : vipBenefitList.length) ~/
                                          3 +
                                      ((vipBenefitList == null
                                                      ? 0
                                                      : vipBenefitList.length) %
                                                  3 >
                                              0
                                          ? 1
                                          : 0)) *
                                  90.h))
                          .toDouble(),
                      child: vipUpgrade()),
                  GestureDetector(
                    onTap: () {
                      Navigator.of(context)
                          .popAndPushNamed('/router/legal_right_details', arguments: {
                        "vipBenefitList": vipBenefitList,
                      });
                    },
                    child: Container(
                      margin: EdgeInsets.only(left: 32, right: 32, bottom: 20),
                      decoration: BoxDecoration(
                        gradient: new LinearGradient(
                            begin: Alignment.centerLeft,
                            end: Alignment.centerRight,
                            colors: [
                              Color(0xFFFFDCA1),
                              Color(0xFFFAE4C0),
                            ]),
                        borderRadius: BorderRadius.circular(22.5),
                      ),
                      width: MediaQuery.of(context).size.width,
                      height: 40,
                      alignment: Alignment.center,
                      child: Text(
                        S.of(context).chakanquanyi,
                        style: TextStyle(
                          fontWeight: FontWeight.bold,
                          fontSize: 16.sp,
                          color: Color(0xFF4A4748),
                        ),
                      ),
                    ),
                  ),
                ],
              ),
            ),
            Image.asset(
              "assets/image/vip_yk.webp",
              fit: BoxFit.cover,
              width: 76,
              height: 76,
            ),
          ],
        ),
      ],
    );
  }

  ///会员升级权益列表
  Widget vipUpgrade() {
    return GridView.builder(
      itemCount: vipBenefitList == null ? 0 : vipBenefitList.length,
      shrinkWrap: true,
      physics: BouncingScrollPhysics(),
      gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
        //一行的Widget数量
        crossAxisCount: 3,
        //水平子Widget之间间距
        crossAxisSpacing: 0,
        //垂直子Widget之间间距
        mainAxisSpacing: 0,
        childAspectRatio: 1.5,
      ),
      itemBuilder: (context, index) {
        return GestureDetector(
          onTap: () {},
          child: vipUpgradeItem(vipBenefitList[index]),
        );
      },
    );
  }

  Widget vipUpgradeItem(VipBenefit vipBenefit) {
    return Container(
      alignment: Alignment.center,
      child: Column(
        children: [
          Stack(
            alignment: Alignment.bottomCenter,
            children: [
              MImage(
                (!(vipBenefit.actived ?? false) ||  (!(vipBenefit.actived ?? false) && !(vipBenefit.have ?? false))
                    || ((vipBenefit.actived ?? false) && !(vipBenefit.have ?? false)))?
                (vipBenefit.iconGrey ?? ""):(vipBenefit.icon ?? ""),
                width: 36,
                height: 36,
                // fit: BoxFit.cover,
                errorSrc: "assets/image/default_1.webp",
                fadeSrc: "assets/image/default_1.webp",
              ),
              if (!(vipBenefit.actived ?? false) || !(vipBenefit.actived ?? false) && !(vipBenefit.have ?? false))
                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(
                        S.of(context).zanweikaifang,
                        style: TextStyle(
                          color: Color(0xFFFFDCA1),
                          fontWeight: MyFontWeight.regular,
                          fontSize: 9.sp,
                        ),
                      ),
                    ],
                  ),
                ),
              if ((vipBenefit.actived ?? false) && !(vipBenefit.have ?? false))
                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(
                        S.of(context).zanweijiesuo,
                        style: TextStyle(
                          color: Color(0xFFFFDCA1),
                          fontWeight: MyFontWeight.regular,
                          fontSize: 9.sp,
                        ),
                      ),
                    ],
                  ),
                ),
            ],
          ),
          SizedBox(
            height: 5.h,
          ),
          Text(
            vipBenefit.name ?? "",
            maxLines: 2,
            overflow: TextOverflow.ellipsis,
            textAlign: TextAlign.center,
            style: TextStyle(
              color: Color(0xFF181818),
              fontWeight: MyFontWeight.regular,
              fontSize: 12.sp,
            ),
          ),
        ],
      ),
    );
  }
}