import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutterappfuyou/code/base/YSBase.dart';
import 'package:flutterappfuyou/code/base/YSTools.dart';

import '../../base/YSNetWorking.dart';
import '../YSCouponHelp.dart';
import '../YSInstitution.dart';
import '../YSWriteOff.dart';
import 'YSCouponCardView.dart';

class YSCouponMom extends StatefulWidget {
  const YSCouponMom({Key key}) : super(key: key);

  @override
  _YSCouponMomState createState() => _YSCouponMomState();
}

class _YSCouponMomState extends State<YSCouponMom> {
  List _enumArray = [
    {'image':'医院列表','title':'医疗机构'},
    {'image':'核销记录','title':'核销记录'},
    {'image':'使用帮助 (1)','title':'使用帮助'}
  ];
  List _array = [];
  Future<void> _getCouponData() async{
    Map dict = await ysRequestHttpNoLoading(context, requestType.post, 'transfer/coupon/getUserCouponList', {'idcard':User().idCard});
    if(dict!=null){
      if(dict['data'] is List){
        _array.clear();
        setState(() {});
        return;
      }
      List dataArray = [];
      Map data = dict['data']??{};
      data.forEach((key, value) {
        String title = '';
        bool isHelp = false;
        if(key=='pregnantWoman'){
          title = '母亲筛查服务券';
          isHelp = true;
        }else if(key=='infant'){
          title = '新生儿筛查服务券';
          isHelp = false;
        }
        List keyArray = data[key]??[];
        Map map = {'title':title,'isHelp':isHelp};
        List array = [];
        for(Map element in keyArray){
          List receivedCouponVoList = element['receivedCouponVoList']??[];
          for(Map elementSub in receivedCouponVoList){
            elementSub['count'] = '${receivedCouponVoList.length}';
            elementSub['typeId'] = int.parse(element['typeId']);
            array.add(elementSub);
          }
        }
        map['array'] = array;
        dataArray.add(map);
      });
      Map item = dataArray.firstWhere((element) => element['title']=='母亲筛查服务券',orElse: ()=>{});
      if(item.isNotEmpty){
        _array = item['array']??[];
        setState(() {});
      }else{
        _array.clear();
        setState(() {});
      }
    }
  }
  @override
  void initState() {
    Future.delayed(Duration(seconds: 0)).then((value) {
      _getCouponData();
    });
    super.initState();
  }
  @override
  Widget build(BuildContext context) {
    return YSBase(
      ystitle: '母亲两筛电子券',
      ysBgColor: Color(0xFFF1F1F1),
      yschild: NotificationListener<CustomerNotification>(
        onNotification: (value){
          _getCouponData();
          return true;
        },
        child: Stack(
          children: [
            Container(
              height: 30,
              color: Color(0xFFDB5278),
            ),
            Column(
              children: [
                Container(
                  height: 120,
                  margin: EdgeInsets.only(left: 15,right: 15,bottom: 20),
                  decoration: BoxDecoration(
                    color: Colors.white,
                    borderRadius: BorderRadius.all(Radius.circular(10))
                  ),
                  child: GridView.builder(gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                    crossAxisCount: 3
                  ), itemBuilder: (context,index){
                    Map item = _enumArray[index];
                    return GestureDetector(
                      onTap: (){
                        Navigator.of(context,rootNavigator: true).push(
                            CupertinoPageRoute(builder: (context){
                              return index==0?YSInstitution():index==1?YSWriteOff():YSCouponHelp();
                            })
                        );
                      },
                      behavior: HitTestBehavior.opaque,
                      child: Container(
                        alignment: Alignment.center,
                        child: LayoutBuilder(
                          builder: (context,conSize) {
                            return Column(
                              mainAxisSize: MainAxisSize.min,
                              children: [
                                Image.asset('lib/images/${item['image']}.png',height: conSize.maxWidth/4,width: conSize.maxWidth/4,),
                                Container(
                                  child: Text(item['title'],style: TextStyle(fontSize: 14,color: Color(0xFF323233)),),
                                  margin: EdgeInsets.only(top: 10),
                                )
                              ],
                            );
                          },
                        ),
                      ),
                    );
                  },itemCount: _enumArray.length,padding: EdgeInsets.all(0),),
                  // alignment: Alignment.centerRight,
                  // child: Row(
                  //   mainAxisSize: MainAxisSize.min,
                  //   children: [
                  //     GestureDetector(
                  //       child: SizedBox(
                  //         child: Text('使用帮助',style: TextStyle(fontSize: 12,color: Color(0xFF515050)),),
                  //         width: 60,
                  //       ),
                  //       onTap: (){
                  //         Navigator.of(context,rootNavigator: true).push(
                  //             CupertinoPageRoute(builder: (context){
                  //               return YSCouponHelp();
                  //             })
                  //         );
                  //       },
                  //       behavior: HitTestBehavior.opaque,
                  //     ),
                  //     PopupMenuButton(
                  //       itemBuilder: (BuildContext context){
                  //         return [
                  //           PopupMenuItem(child: Text("核销记录",style: TextStyle(fontSize: 12,color: Color(0xFF444444)),),value: "1",),
                  //           PopupMenuItem(child: Text("机构列表",style: TextStyle(fontSize: 12,color: Color(0xFF444444)),),value: "2",),
                  //         ];
                  //       },
                  //       icon: Container(
                  //         child: Text('更多',style: TextStyle(fontSize: 12,color: Color(0xFFE78CA9)),),
                  //         alignment: Alignment.centerRight,
                  //         width: 40,
                  //       ),
                  //       onSelected: (value){
                  //         if(value=='1'){
                  //           Navigator.of(context,rootNavigator: true).push(
                  //               CupertinoPageRoute(builder: (context){
                  //                 return YSWriteOff();
                  //               })
                  //           );
                  //         }else{
                  //           Navigator.of(context,rootNavigator: true).push(
                  //               CupertinoPageRoute(builder: (context){
                  //                 return YSInstitution();
                  //               })
                  //           );
                  //         }
                  //       },
                  //     )
                  //     // Image.asset('lib/images/fy_help.png',height: 20,width: 20,)
                  //   ],
                  // ),
                ),
                Container(
                  height: ysHeight(context)-ysTOP(context)-190,
                  width: ysWidth(context),
                  child: RefreshIndicator(
                    onRefresh: _getCouponData,
                    child: _array.isEmpty?Center(
                      child: Image.asset('lib/images/none.png',height: 200,width: 200,),
                    ):ListView.separated(itemBuilder: (context,indexSub){
                      Map itemSub = _array[indexSub];
                      itemSub['type'] = '1';
                      return YSCouponCardNewView(item: itemSub,array: _array,);
                    },
                      separatorBuilder: (context,indexSub){
                        return Container(height: 15,);
                      },
                      itemCount: _array.length,
                      padding: EdgeInsets.only(left: 15,right: 15,bottom: 15),
                    ),
                  ),
                )
              ],
            )
          ],
        ),
      ),
    );
  }
}
