import 'dart:collection';
import 'dart:convert';

import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:huixiang/retrofit/data/base_data.dart';
import 'package:huixiang/retrofit/data/coupon.dart';
import 'package:huixiang/retrofit/retrofit_api.dart';
import 'package:huixiang/utils/font_weight.dart';
import 'package:shared_preferences/shared_preferences.dart';

class ActivityCoupons extends StatefulWidget {
  final String result;

  ActivityCoupons(this.result);

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

class _ActivityCoupons extends State<ActivityCoupons> {
  var resultData;
  int pageNum = 1;
  List<Coupon> coupons = [];
  ApiService apiService;
  var receiveCou = new Queue();

  @override
  void initState() {
    super.initState();
    resultData = jsonDecode(widget.result);
  }

  receiveCoupon() async {
    var id = receiveCou.removeFirst();
    if (apiService == null) {
      SharedPreferences value = await SharedPreferences.getInstance();
      apiService = ApiService(
        Dio(),
        context: context,
        token: value.getString("token"),
      );
    }
    BaseData baseData = await apiService.receiveCoupon(id).catchError((onError) {});
    if (baseData != null && baseData.isSuccess) {
      if (receiveCou.length > 0) {
        receiveCoupon();
      } else {
        Navigator.of(context).pop();
        SmartDialog.showToast("领取成功", alignment: Alignment.center);
      }
    }
    else{
      SmartDialog.showToast(baseData.msg, alignment: Alignment.center);
      Navigator.of(context).pop();
    }
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      margin: EdgeInsets.only(top: 150.h),
      height: MediaQuery.of(context).size.height / 2,
      child: Column(
        children: [
          Container(
            width: double.infinity,
            height: MediaQuery.of(context).size.height / 2,
            padding: EdgeInsets.only(top: 210.h),
            margin: EdgeInsets.only(top: 20.h, left: 20, right: 20),
            decoration: BoxDecoration(
              image: DecorationImage(
                fit: BoxFit.fill,
                image: AssetImage("assets/image/activity_q.png"),
              ),
            ),
            child: Column(
              children: [
                Expanded(
                  child: couponsActivity(),
                ),
                GestureDetector(
                  onTap: () {
                    (resultData["list"] as List).forEach((element) {
                      receiveCou..add(element["id"]);
                    });
                    receiveCoupon();
                  },
                  child: Container(
                    margin: EdgeInsets.only(
                        left: 60.w, right: 60.w, top: 20.h, bottom: 20.h),
                    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(
                      "立即领取",
                      style: TextStyle(
                        fontWeight: FontWeight.bold,
                        fontSize: 14.sp,
                        color: Color(0xFF4A4748),
                      ),
                    ),
                  ),
                ),
              ],
            ),
          ),
          SizedBox(height: 35),
          GestureDetector(
            onTap: () {
              setState(() {
                Navigator.of(context).pop();
              });
            },
            child: Image.asset(
              "assets/image/yq_qx.png",
              width: 34,
              height: 34,
            ),
          )
        ],
      ),
    );
  }

  Widget couponsActivity() {
    return ListView.builder(
      padding: EdgeInsets.zero,
      itemCount: (resultData == null || resultData["list"] == null)
          ? 0
          : (resultData["list"] as List).length,
      scrollDirection: Axis.vertical,
      shrinkWrap: true,
      physics: BouncingScrollPhysics(),
      itemBuilder: (context, position) {
        return GestureDetector(
          onTap: () {},
          child: couponsItem(resultData["list"][position]),
        );
      },
    );
  }

  Widget couponsItem(listData) {
    return Container(
      height: 69.h,
      width: double.infinity,
      decoration: BoxDecoration(
        image: DecorationImage(
          fit: BoxFit.fill,
          image: AssetImage("assets/image/xin_rq.png"),
        ),
      ),
      margin: EdgeInsets.symmetric(horizontal: 60, vertical: 5),
      padding: EdgeInsets.only(left: 16.w, right: 10.w),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.center,
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          if (listData["type"] == 1)
            Text.rich(
              TextSpan(
                children: [
                  TextSpan(
                    text: "¥",
                    style: TextStyle(
                      fontSize: 14.sp,
                      fontWeight: MyFontWeight.semi_bold,
                      color: Color(0xFFDE5F3B),
                    ),
                  ),
                  TextSpan(
                    text: listData["discount"] ?? "",
                    style: TextStyle(
                      fontSize: 20.sp,
                      fontWeight: MyFontWeight.semi_bold,
                      color: Color(0xFFDE5F3B),
                    ),
                  ),
                ],
              ),
            ),
          if (listData["type"] == 3)
            Text(
              "兑换券",
              overflow: TextOverflow.ellipsis,
              maxLines: 2,
              style: TextStyle(
                fontSize: 16.sp,
                fontWeight: MyFontWeight.semi_bold,
                color: Color(0xFFDE5F3B),
              ),
            ),
          if (listData["type"] == 2)
            Padding(
                padding: EdgeInsets.only(right: 20),
                child: Text.rich(
                  TextSpan(
                    children: [
                      TextSpan(
                        text: (listData["percent"] / 10).toString() ?? "",
                        style: TextStyle(
                          fontSize: 25.sp,
                          fontWeight: MyFontWeight.semi_bold,
                          color: Color(0xFFDE5F3B),
                        ),
                      ),
                      TextSpan(
                        text: "折",
                        style: TextStyle(
                          fontSize: 14.sp,
                          fontWeight: MyFontWeight.semi_bold,
                          color: Color(0xFFDE5F3B),
                        ),
                      ),
                    ],
                  ),
                )),
          Expanded(
              child: Padding(
                  padding: EdgeInsets.only(top: 4, bottom: 4, left: 10),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.center,
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      Text(
                        listData["name"] ?? "",
                        overflow: TextOverflow.ellipsis,
                        maxLines: 2,
                        style: TextStyle(
                          fontSize: 16.sp,
                          fontWeight: MyFontWeight.semi_bold,
                          color: Color(0xFF181818),
                        ),
                      ),
                    ],
                  ))),
        ],
      ),
    );
  }
}