import 'dart:convert';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutterappfuyou/code/base/YSNetWorking.dart';
import 'package:flutterappfuyou/code/version3/YSCouponHelp.dart';
import 'package:flutterappfuyou/code/version3/YSInstitution.dart';
import 'package:flutterappfuyou/code/version3/YSWriteOff.dart';
import 'package:flutterappfuyou/code/version3/view/YSCommunityListItemView.dart';
import 'package:flutterappfuyou/code/version3/view/YSCouponCardView.dart';
import 'package:flutterappfuyou/code/version3/view/YSCouponChild.dart';
import 'package:flutterappfuyou/code/version3/view/YSCouponCommunity.dart';
import 'package:flutterappfuyou/code/version3/view/YSCouponMom.dart';
import 'package:shared_preferences/shared_preferences.dart';
import '../base/YSBase.dart';
import '../base/YSTools.dart';

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

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

class _YSCouponState extends State<YSCoupon> {
  List _titles = [];
  List _dataArray= [];
  List _imageArray = [];

  Future<void> _getCommunityData() async{
    Map request = {};
    request['idcard'] = User().idCard;
    request['pageSize'] = 10;
    request['pageNum'] = 1;
    Map dict = await ysRequestHttpNoLoading(context, requestType.post, 'transfer/coupon/getCommunityVouchers', request);
    if(dict!=null){
        if(dict['data'] is List){
          _getPicturesData();
          return;
        }
        _dataArray = dict['data']['data']['datas']??[];
        if(_dataArray.isEmpty){
          _getPicturesData();
          return;
        }
        _imageArray.clear();
        // LogUtil.d(dict['data']['show']);
        bool show = dict['data']['show']??false;
        _titles = [
          {'title':'母亲两筛电子券','type':1,'icon':'母亲信息备份'},
          {'title':'儿童两筛电子券','type':2,'icon':'婴儿票支持备份 3'},
          if(show){'title':'社区体检券','type':3,'icon':'我的体验卷'}
        ];
        _dataArray = dict['data']['datas']??[];
        setState(() {});
        _getKnowData();
    }
  }

  // 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){
  //       _getPicturesData();
  //       return;
  //     }
  //     _imageArray.clear();
  //     _titles = [
  //       {'title':'母亲两筛电子券','type':1,'icon':'母亲信息备份'},
  //       {'title':'儿童两筛电子券','type':2,'icon':'婴儿票支持备份 3'},
  //       {'title':'社区体检券','type':3,'icon':'我的体验卷'}
  //     ];
  //     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']??[];
  //         Map receivedCouponVoL = receivedCouponVoList.first;
  //         receivedCouponVoL['count'] = '${receivedCouponVoList.length}';
  //         array.add(receivedCouponVoL);
  //       }
  //       map['array'] = array;
  //       _dataArray.add(map);
  //     });
  //     setState(() {});
  //     LogUtil.d(_dataArray);
  //   }
  // }

  _getPicturesData() async{
    Map dict = await ysRequestHttpNoLoading(context, requestType.post, 'transfer/coupon/getPictures', {'idcard':User().idCard,'type':'PROPAGATE'});
    if(dict!=null){
      _imageArray = dict['data']??[];
      setState(() {});
    }
  }

  @override
  void initState() {
    Future.delayed(Duration(seconds: 0)).then((value) {
      // _getCouponData();
      _getCommunityData();
    });
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return YSBase(
      ystitle: '券包',
      isBack: false,
      yschild: Container(
        width: ysWidth(context),
        child: RefreshIndicator(
          onRefresh: _getCommunityData,
          child: _imageArray.isNotEmpty?ListView.builder(
            itemBuilder: (context,index){
              String url = _imageArray[index];
              return GestureDetector(
                onTap: (){

                },
                child: Image.network(url,fit: BoxFit.fill,),
              );
            },
            itemCount: _imageArray.length,
            padding: EdgeInsets.all(0),
          ):ListView.builder(
            itemBuilder: (context,index){
              Map item = _titles[index];
              return GestureDetector(
                onTap: (){
                  int type = item['type'];
                  Navigator.of(context,rootNavigator: true).push(
                      CupertinoPageRoute(builder: (context){
                        return type==1?YSCouponMom():type==2?YSCouponChild():YSCouponCommunity();
                      })
                  ).then((value) {
                    _getCommunityData();
                  });
                },
                behavior: HitTestBehavior.opaque,
                child: Container(
                  height: 50,
                  decoration: BoxDecoration(
                    border: Border(bottom: BorderSide(width: 1,color: Color(0xFFEBEDF0)))
                  ),
                  child: Row(
                    children: [
                      Image.asset('lib/images/${item['icon']}.png',height: 20,width: 20,),
                      Expanded(child: Text('  ${item['title']}',style: TextStyle(fontSize: 17,color: Color(0xFF323233)),)),
                      Icon(Icons.chevron_right,size: 20,color: Color(0xFF969799),)
                    ],
                  ),
                ),
              );
            },
            itemCount: _titles.length,
            padding: EdgeInsets.only(left: 15,right: 15,top: 10,bottom: 10),
          ),
        ),
      ),
    );
  }

  _getKnowData() async{
    Map dict = await ysRequestHttpNoLoading(context, requestType.post, 'transfer/coupon/getClarionLetter', {'idcard':User().idCard});
    if(dict!=null){
      Map data = dict['data'];
      if(data['show']==true){
        showNegotiate3AlertDio(
            context,
            title: '告知书',
            content: data['data']??'',
            agree: () async{
              Map dict2 = await ysRequestHttpNoLoading(context, requestType.post, 'transfer/coupon/getClarionLetterAgree', {'idcard':User().idCard});
              if(dict2!=null){
                LogUtil.d(dict2);
                bool isAgree = dict2['data']??false;
                if(isAgree){}
              }
            },
        );
      }
    }
    // SharedPreferences preferences = await SharedPreferences.getInstance();
    // bool isKnow = preferences.getBool('isKnow')??false;
    // if(!isKnow){}
  }

}

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

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

class _YSCoupon3State extends State<YSCoupon3> with SingleTickerProviderStateMixin{
  List _titles = [
    {'title':'母亲两筛电子券','type':1},
    {'title':'儿童两筛电子券','type':2},
    {'title':'社区体检券','type':3}
  ];
  List _dataArray= [];
  List _imageArray = [];
  List _dataArray2= [
    {'status': 1,'depart':'郭杜卫生院','getDate':'2023-07-31  15:32','useDate':'2023-07-31  15:32','name':'社区免费体验券','tips':'19周进行胎儿的检查'},
    {'status': 2,'depart':'郭杜卫生院','getDate':'2023-07-31  15:32','useDate':'2023-07-31  15:32','name':'社区免费体验券','tips':'19周进行胎儿的检查'}
  ];


  TabController _tabController;
  @override
  void initState() {
    _tabController = TabController(
      vsync: this,
      length: _titles.length,
    );
    Future.delayed(Duration(seconds: 0)).then((value) {
      _getCouponData();
    });
    super.initState();
  }
  _getCouponData() async{
    Map dict = await ysRequestHttpNoLoading(context, requestType.post, 'transfer/coupon/getUserCouponList', {'idcard':User().idCard});
    if(dict!=null){
      if(dict['data'] is List){
        _getPicturesData();
        return;
      }
      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']??[];
          Map receivedCouponVoL = receivedCouponVoList.first;
          receivedCouponVoL['count'] = '${receivedCouponVoList.length}';
          array.add(receivedCouponVoL);
        }
        map['array'] = array;
        _dataArray.add(map);
      });
      setState(() {});
    }
  }
  _getPicturesData() async{
    Map dict = await ysRequestHttpNoLoading(context, requestType.post, 'transfer/coupon/getPictures', {'idcard':User().idCard,'type':'PROPAGATE'});
    if(dict!=null){
      _imageArray = dict['data']??[];
      setState(() {});
    }
  }
  @override
  Widget build(BuildContext context) {
    return YSBase(
      ystitle: '券包',
      isBack: false,
      yschild: DefaultTabController(
        length: _titles.length,
        child: SingleChildScrollView(
          child: Column(
            children: [
              Container(
                height: 50,
                child: TabBar(
                  controller: _tabController,
                  indicatorColor: Color(0xFFEE6B8F),
                  labelColor: Color(0xFFEE6B8F),
                  indicatorWeight: 3,
                  indicatorSize: TabBarIndicatorSize.label,
                  labelStyle: TextStyle(fontSize: 14),
                  unselectedLabelColor: Color(0xFFC8C9CC),
                  // onTap: (value){
                  //   Navigator.of(context,rootNavigator: true).push(
                  //       CupertinoPageRoute(builder: (context){
                  //         return YSCouponHelp();
                  //       })
                  //   );
                  // },
                  tabs: _titles.map((f) {
                    return Tab(
                      child: Row(
                        mainAxisSize: MainAxisSize.min,
                        children: [
                          Text(f['title'])
                        ],
                      ),
                    );
                  }).toList(),
                ),
              ),
              Container(
                height: ysHeight(context)-ysTOP(context)-142,
                child: TabBarView(
                  controller: _tabController,
                  children: _titles.map((f) {
                    return f['type']==2?ListView.separated(
                      itemBuilder: (context,index){
                        Map item = _dataArray2[index];
                        return YSCommunityListItemView(item: item);
                      },
                      separatorBuilder: (context,index){
                        return Container(height: 10,);
                      },
                      itemCount: _dataArray2.length,
                      padding: EdgeInsets.only(top: 15,bottom: 15),
                    ):(_imageArray.isNotEmpty?ListView.builder(
                      itemBuilder: (context,index){
                        String url = _imageArray[index];
                        return Image.network(url,fit: BoxFit.fill,);
                      },
                      itemCount: _imageArray.length,
                      padding: EdgeInsets.all(0),
                    ):ListView.builder(itemBuilder: (context,index){
                      Map item = _dataArray[index];
                      List array = item['array']??[];
                      return Column(
                        children: [
                          Container(
                            alignment: Alignment.centerLeft,
                            height: 42,
                            child: Row(
                              children: [
                                SizedBox(
                                  child: Text(item['title'],style: TextStyle(fontSize: 14,color: Color(0xFF515050)),),
                                  width: ysWidth(context)-160,
                                ),
                                if(item['isHelp']==true)SizedBox(
                                  child: Row(
                                    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,)
                                    ],
                                  ),
                                  width: 120,
                                ),
                              ],
                            ),
                            padding: EdgeInsets.only(left: 15,right: 15),
                          ),
                          ListView.separated(itemBuilder: (context,indexSub){
                            Map itemSub = array[indexSub];
                            if(index==0){
                              itemSub['type'] = '1';
                            }else{
                              itemSub['type'] = '2';
                            }
                            return YSCouponCardNewView(item: itemSub,array: array,);
                          },
                            separatorBuilder: (context,indexSub){
                              return Container(height: 15,);
                            },
                            itemCount: array.length,
                            padding: EdgeInsets.only(left: 15,right: 15),
                            shrinkWrap: true,
                            physics: NeverScrollableScrollPhysics(),
                          )
                        ],
                      );
                    },
                      itemCount: _dataArray.length,
                      padding: EdgeInsets.only(bottom: 15),
                    ));
                  }).toList(),
                ),
              )
            ],
          ),
        ),
      ),
    );
  }
}


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

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

class _YSCoupon2State extends State<YSCoupon2> {
  List _dataArray= [
    {'title':'母亲筛查服务券','array':[
      {'name':'产前血清学筛查','count':2,'no':'131354654646132','month':'孕30-34周','date':'2024-10-05','color':0xFFE290F9,'index':0},
      {'name':'产前常规超声检查','count':1,'no':'131354654646132','month':'孕30-34周','date':'2024-10-05','color':0xFFF4DF59,'index':1},
      {'name':'产前常规超声检查','count':1,'no':'131354654646132','month':'孕30-34周','date':'2024-10-05','color':0xFFACED62,'index':2},
    ]},
    {'title':'新生儿筛查服务券','array':[
      {'name':'新生儿先天性听力障碍筛查','count':2,'no':'131354654646132','month':'孕30-34周红','date':'2024-10-05','color':0xFFFF6D96,'index':0},
      {'name':'新生儿遗传代谢病筛查','count':1,'no':'131354654646132','month':'孕30-34周紫','date':'2024-10-05','color':0xFFB9A0FF,'index':1},
      {'name':'新生儿先天性心脏病筛查','count':1,'no':'131354654646132','month':'孕30-34周蓝色','date':'2024-10-05','color':0xFF72D2FF,'index':2},
    ]}
  ];
  List _dataArray2= [
    {'title':'母亲筛查服务券','array':[
      {'name':'产前血清学筛查','count':2,'no':'131354654646132','month':'孕30-34周','date':'2024-10-05','color':0xFFE290F9,'index':0},
      {'name':'产前常规超声检查','count':1,'no':'131354654646132','month':'孕30-34周','date':'2024-10-05','color':0xFFF4DF59,'index':1},
      {'name':'产前常规超声检查','count':1,'no':'131354654646132','month':'孕30-34周','date':'2024-10-05','color':0xFFACED62,'index':2},
    ]},
    {'title':'新生儿筛查服务券','array':[
      {'name':'新生儿先天性听力障碍筛查','count':2,'no':'131354654646132','month':'孕30-34周红','date':'2024-10-05','color':0xFFFF6D96,'index':0},
      {'name':'新生儿遗传代谢病筛查','count':1,'no':'131354654646132','month':'孕30-34周紫','date':'2024-10-05','color':0xFFB9A0FF,'index':1},
      {'name':'新生儿先天性心脏病筛查','count':1,'no':'131354654646132','month':'孕30-34周蓝色','date':'2024-10-05','color':0xFF72D2FF,'index':2},
    ]}
  ];
  @override
  Widget build(BuildContext context) {
    return YSBase(
      ystitle: '两筛电子劵',
      isBack: false,
      yschild: Column(
        children: [
          Container(
            height: ysHeight(context)-ysTOP(context)-94,
            child: SingleChildScrollView(
              child: Column(
                children: [
                  ListView.builder(
                    itemBuilder: (context,index){
                      Map item = _dataArray[index];
                      List array = item['array']??[];
                      return Column(
                        children: [
                          Container(
                            alignment: Alignment.centerLeft,
                            height: 42,
                            child: Row(
                              children: [
                                SizedBox(
                                  child: Text(item['title'],style: TextStyle(fontSize: 14,color: Color(0xFF515050)),),
                                  width: ysWidth(context)-110,
                                ),
                                GestureDetector(//if(index==0)
                                  child: SizedBox(
                                    child: Row(
                                      children: [
                                        SizedBox(
                                          child: Text('使用帮助',style: TextStyle(fontSize: 14,color: Color(0xFF515050)),),
                                          width: 60,
                                        ),
                                        Image.asset('lib/images/fy_help.png',height: 20,width: 20,)
                                      ],
                                    ),
                                    width: 80,
                                  ),
                                  onTap: (){
                                    if(index==0){
                                      Navigator.of(context,rootNavigator: true).push(
                                          CupertinoPageRoute(builder: (context){
                                            return YSInstitution();
                                          })
                                      );
                                    }else{
                                      Navigator.of(context,rootNavigator: true).push(
                                          CupertinoPageRoute(builder: (context){
                                            return YSWriteOff();
                                          })
                                      );
                                    }

                                  },
                                ),
                              ],
                            ),
                            padding: EdgeInsets.only(left: 15,right: 15),
                          ),
                          Stack(
                            children: [
                              for (int i =0;i<array.length;i++ )GestureDetector(
                                child: YSCouponCardView(item: array[i],isShow: i==array.length-1,array: _dataArray2[index]['array'],),
                                onTap: (){
                                  int endIndex = array.length-1;
                                  if(i==endIndex)return;
                                  Map map = array[i];
                                  List array1 = _dataArray2[index]['array'];
                                  item['array'] = jsonDecode(jsonEncode(array1));
                                  List array2 = item['array'];
                                  Map itemC = array2.firstWhere((element) => element['index']==map['index']);
                                  int cIndex = array2.indexOf(itemC);
                                  Map itemE = array2[endIndex];
                                  array2[endIndex] = itemC;
                                  array2[cIndex] = itemE;
                                  setState(() {});
                                },
                                // behavior: HitTestBehavior.opaque,
                              )
                            ],
                            // alignment: AlignmentDirectional.bottomStart,
                          )
                        ],
                      );
                    },
                    itemCount: _dataArray.length,
                    shrinkWrap: true,
                    physics: NeverScrollableScrollPhysics(),
                    padding: EdgeInsets.all(0),
                  )
                ],
              ),
            ),
          )
        ],
      ),
    );
  }
}

