import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:huixiang/generated/l10n.dart';
import 'package:huixiang/retrofit/data/base_data.dart';
import 'package:huixiang/retrofit/data/coupon.dart';
import 'package:huixiang/retrofit/data/page.dart';
import 'package:huixiang/retrofit/retrofit_api.dart';
import 'package:huixiang/utils/font_weight.dart';
import 'package:huixiang/view_widget/item_title.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:huixiang/view_widget/receive_success.dart';
import 'package:huixiang/view_widget/round_button.dart';
import 'package:huixiang/view_widget/separator.dart';
import 'package:shared_preferences/shared_preferences.dart';

class CouponView extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return _CouponView();
  }
}

class _CouponView extends State<CouponView> {
  ApiService apiService;
  List<Coupon> coupons = [];


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

    SharedPreferences.getInstance().then((value) => {
      apiService = ApiService(
        Dio(),
        context: context,
        token: value.getString('token'),
      ),
      queryCoupon(),
    });
  }

  queryCoupon() async {
    BaseData<PageInfo<Coupon>> baseData = await apiService.queryCoupon({
      "centre": true,
      "pageNum": 1,
      "pageSize": 10,
      "searchKey": "",
      "state": 0
    }).catchError((onError) {
    });
    coupons.clear();
    if (baseData != null && baseData.isSuccess) {
      coupons.addAll(baseData.data.list);
      setState(() {});
    }
  }

  @override
  Widget build(BuildContext context) {
    return (coupons == null || coupons.length == 0) ? Container(height: 20,) : Column(
      children: [
        SizedBox(
          height: 20.h,
        ),
        ItemTitle(
          text: S.of(context).chaojiyouhuiquan,
          imgPath: "assets/image/icon_points_mall.webp",
        ),
        Container(
          height: 132,
          margin: EdgeInsets.only(top: 10),
          child: ListView.builder(
            scrollDirection: Axis.horizontal,
            physics: BouncingScrollPhysics(),
            padding: EdgeInsets.symmetric(horizontal: 10),
            itemBuilder: (context, position) {
              return couponItem(coupons[position]);
            },
            itemCount:coupons == null ? 0 : coupons.length,
          ),
        ),
      ],
    );
  }

  Widget couponItem(Coupon coupon) {
    return Container(
      width: 0.9,
      height: 122.h,
      child: Stack(
        children: [
          Container(
            width: 0.9,
            height: 122.h,
            child: SvgPicture.asset(
              "assets/svg/youhuiquan_bg.svg",
              width: double.infinity,
              height: 122.h,
              fit: BoxFit.fill,
            ),
          ),
          Container(
            width: 0.9,
            height: 122.h,
            child: Row(
              children: [
                Expanded(
                  child: Container(
                    alignment: Alignment.center,
                    child: Container(
                      width: 74,
                      height: 74,
                      decoration: BoxDecoration(
                        borderRadius: BorderRadius.circular(6),
                        gradient: LinearGradient(
                          begin: Alignment.topLeft,
                          end: Alignment.bottomRight,
                          colors: [
                            Color(0xFFACDD60),
                            Color(0xFF32A060),
                          ],
                        ),
                      ),
                      child: Column(
                        mainAxisAlignment: MainAxisAlignment.center,
                        crossAxisAlignment: CrossAxisAlignment.center,
                        children: [
                          Text.rich(
                            TextSpan(
                              children: [
                                TextSpan(
                                  text: "¥",
                                  style: TextStyle(
                                    fontSize: 16.sp,
                                    fontWeight: MyFontWeight.regular,
                                    color: Colors.white,
                                  ),
                                ),
                                TextSpan(
                                  text:  coupon != null
                                      ? double.tryParse("${coupon.discountAmount}" ?? "0")
                                      .toInt()
                                      .toString()
                                      : "",
                                  style: TextStyle(
                                    fontSize: 25.sp,
                                    fontWeight: MyFontWeight.regular,
                                    color: Colors.white,
                                  ),
                                ),
                              ],
                            ),
                          ),
                          Text(
                            S.of(context).manyuankeyong(coupon != null
                                ? double.tryParse("${coupon.fullAmount}" ?? "0")
                                .toInt()
                                .toString()
                                : ""),
                            style: TextStyle(
                              fontWeight: MyFontWeight.regular,
                              fontSize: 14.sp,
                              color: Colors.white,
                            ),
                          ),
                        ],
                      ),
                    ),
                  ),
                  flex: 37,
                ),
                Container(
                  margin: EdgeInsets.only(
                    top: 24.h,
                    bottom: 24.h,
                  ),
                  child: MySeparator(
                    height: 5.h,
                    width: 1,
                    color: Color(0xFFD8D8D8),
                  ),
                ),
                Expanded(
                  child: Container(
                    margin:
                        EdgeInsets.symmetric(vertical: 10.h, horizontal: 15.w),
                    child: Column(
                      mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Text(
                          (coupon != null && coupon.storeList != null && coupon.storeList.length > 0) ? coupon.storeList[0].storeName ?? "" : "",
                          overflow: TextOverflow.ellipsis,
                          style: TextStyle(
                            color: Color(0xFF181818),
                            fontWeight: MyFontWeight.medium,
                            fontSize: 14.sp,
                          ),
                        ),
                        Row(
                          children: [
                            // Text(
                            //   "1张",
                            //   style: TextStyle(
                            //     color: Color(0xFF868686),
                            //     fontWeight: MyFontWeight.regular,
                            //     fontSize: 12.sp,
                            //   ),
                            // ),
                            // SizedBox(
                            //   width: 4.w,
                            // ),
                            Text(
                              coupon != null ? coupon.couponName ?? "" : "",
                              style: TextStyle(
                                color: Color(0xFF868686),
                                fontWeight: MyFontWeight.regular,
                                fontSize: 12.sp,
                              ),
                            ),
                          ],
                        ),
                        SizedBox(
                          width: 12.w,
                        ),
                        Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          crossAxisAlignment: CrossAxisAlignment.end,
                          children: [
                            Expanded(
                              child: Text(
                                (coupon.useStartTime == null &&
                                    coupon.useEndTime == null)
                                    ? S.of(context).quantian
                                    : "${coupon.useStartTime.replaceAll("-", ".").split(" ")[0]} - ${coupon.useEndTime.replaceAll("-", ".").split(" ")[0]}",
                                overflow: TextOverflow.ellipsis,
                                maxLines: 1,
                                style: TextStyle(
                                  color: Color(0xFF868686),
                                  fontWeight: MyFontWeight.semi_bold,
                                  fontSize: 10.sp,
                                ),
                              ),
                              flex: 1,
                            ),
                            GestureDetector(
                              onTap: (){
                                if((coupon?.status??0) == 0)
                                  receiveCoupon(coupon?.id??"");
                              },
                              child: RoundButton(
                                text: ((coupon?.status??0) == 0) ? S.of(context).lingqu : S.of(context).yilingqu,
                                textColor: Colors.white,
                                backgroup: ((coupon?.status??0) == 0)?Color(0xFF32A060):Colors.grey,
                                radius: 100,
                                padding: EdgeInsets.symmetric(vertical: 3.h, horizontal: 14.w),
                              ),
                            ),
                            SizedBox(
                              width: 10.w,
                            ),
                          ],
                        ),
                      ],
                    ),
                  ),
                  flex: 63,
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  receiveCoupon(couponId) async {
    BaseData baseData = await apiService.receiveCoupon(couponId).catchError((onError) {});
    if (baseData != null && baseData.isSuccess) {
      queryCoupon();
      showAlertDialog();
    }
  }

  showAlertDialog() {
    //显示对话框
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return ReceiveSuccess();
      },
    );
  }
}