import 'dart:ffi';

import 'package:dotted_border/dotted_border.dart';
import 'package:flutter/material.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutterappfuyou/code/base/YSNetWorking.dart';
import 'package:flutterappfuyou/code/base/YSTools.dart';
import 'package:flutterappfuyou/code/version3/view/YSSearchView.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'YSHospitalDetail.dart';
import 'base/YSBase.dart';

class YSHospital extends StatefulWidget {
  final int healthId;
  final int areaId;
  const YSHospital({Key key, @required this.healthId, @required this.areaId}) : super(key: key);
  @override
  _YSHospitalState createState() => _YSHospitalState();
}

class _YSHospitalState extends State<YSHospital> {
  int selectedIndex = 0;
  ScrollController _scroll = ScrollController();
  List areas = [];
  List healths = [];
  bool _isStop = false;
  String _nameField = '';
  ScrollController _scrollController = ScrollController();
  RefreshController _refreshController = RefreshController(initialRefresh: false);
  @override
  void initState() {
    _getAreaData();
    super.initState();
  }
  @override
  void dispose() {
    super.dispose();
  }
  @override
  Widget build(BuildContext context) {
    LogUtil.d(widget.areaId);
    return YSBase(
      ystitle: '区域卫生院',
      yschild: SingleChildScrollView(
        child: Column(
          children: [
            Container(
              height: 50,
              width: MediaQuery.of(context).size.width,
              padding: EdgeInsets.only(left: 15),
              decoration: BoxDecoration(
                borderRadius: BorderRadius.only(topLeft: Radius.circular(20),topRight: Radius.circular(20)),
                color: Colors.white,
              ),
              child: Row(
                children: [
                  Container(
                    width: 130,
                    child: RichText(
                      text: TextSpan(
                        text: '当前区域:  ',
                        style: TextStyle(fontSize: 14,color: Color(0xFF202329),decoration: TextDecoration.none),
                        children: [
                          if(areas.isNotEmpty)TextSpan(
                            text: '${areas[selectedIndex]['name']}',
                            style: TextStyle(color: Color(0xFFEE6B8F),fontWeight: FontWeight.bold)
                          )
                        ]
                      ),
                    ),
                    // child: Text('当前区域：',style: TextStyle(fontSize: 14,color: Color(0xFF202329),decoration: TextDecoration.none),),
                  ),
                  Container(
                    width: ysWidth(context)-160,
                    padding: EdgeInsets.only(left: 10,right: 10),
                    decoration: BoxDecoration(
                      color: Color(0xFFF1F1F1),
                      borderRadius: BorderRadius.all(Radius.circular(50))
                    ),
                    height: 30,
                    child: YSSearchView2(postSearch: (value){
                      _nameField = value;
                      _refreshData();
                    },),
                  )
                  // Container(
                  //   height: 35,
                  //   width: MediaQuery.of(context).size.width-100,
                  //   child: NotificationListener(
                  //     onNotification: (value){
                  //       if(value.runtimeType==ScrollEndNotification){
                  //         if(_isStop==false){
                  //           selectedIndex = (_scroll.offset+130)~/65;
                  //           _getHealthData(areas[selectedIndex]);
                  //         }
                  //       }
                  //       return true;
                  //     },
                  //     child: ListView.builder(
                  //       itemBuilder: (context,index){
                  //         return GestureDetector(
                  //           onTap: (){
                  //             selectedIndex = index;
                  //             _getHealthData(areas[index]);
                  //           },
                  //           child: Container(
                  //               color: Colors.white,
                  //               width: 65,
                  //               alignment: Alignment.center,
                  //               child: Text('${areas[index]['name']}',style: TextStyle(color: selectedIndex==index?Color(0xFF8E1B3C):Color(0xFFDDBBC5),
                  //                   fontSize: selectedIndex==index?16:12,decoration: TextDecoration.none,fontWeight: FontWeight.normal),),
                  //           ),
                  //         );
                  //       },
                  //       itemCount: areas.length,
                  //       scrollDirection: Axis.horizontal,
                  //       controller: _scroll,
                  //     ),
                  //   ),
                  // )
                ],
              ),
            ),
            Container(
              height: MediaQuery.of(context).size.height-140,
              color: Color(0xFFF5F3F0),
              child: SmartRefresher(
                onRefresh: _refreshData,
                onLoading: _loadData,
                controller: _refreshController,
                enablePullUp: healths.length<_totalNum,
                child: ListView.separated(
                  controller: _scrollController,
                  itemBuilder: (context,index){
                    Map item = healths[index];
                    bool isChoose = item['isChoose']??false;
                    return GestureDetector(
                      onTap: (){
                        Navigator.of(context).push(
                          CupertinoPageRoute(
                            builder: (context){
                              return YSHospitalDetail(healthId: healths[index]['id'],isEdit: false,);
                            }
                          )
                        );
                      },
                      child: Padding(
                        padding: EdgeInsets.only(left: 44,right: 44),
                        child: DottedBorder(
                          color: isChoose?Color(0xFF979797):Color(0xFFF07196),
                          borderType: BorderType.RRect,
                          radius: Radius.circular(9),
                          strokeWidth: 1,
                          child: Container(
                            height: 63,
                            padding: EdgeInsets.all(15),
                            decoration: BoxDecoration(
                              color: isChoose?Colors.white:Color(0xFFF07196).withOpacity(0.05),
                              borderRadius: BorderRadius.all(Radius.circular(9))
                            ),
                            alignment: Alignment.center,
                            child: Row(
                              mainAxisAlignment: MainAxisAlignment.spaceBetween,
                              children: [
                                Container(
                                  width: MediaQuery.of(context).size.width-200,
                                  child: Text('${item['name']}',style: TextStyle(fontSize: 14,color: Color(0xFF202329),decoration: TextDecoration.none),overflow: TextOverflow.ellipsis,),
                                ),
                                CupertinoButton(
                                  padding: EdgeInsets.all(0),
                                  child: Text(isChoose==true?'已绑定':'绑定卫生院',
                                    style: TextStyle(
                                      fontSize: 14,
                                      color: isChoose==true?Color(0xFFC8C9CC):Color(0xFFEE6B8F),
                                      decoration: TextDecoration.none),
                                  ),
                                  onPressed: () async{
                                    if(isChoose==true)return;
                                    bool isCheck = await checkValue(context,tips: '您已经领取两筛免费券，如需更换卫生院请联系发券机构');
                                    if(isCheck){
                                      Map dict = await ysRequestHttpNoLoading(context, requestType.post, 'i/upHealth', {'health_id':healths[index]['id']});
                                      if(dict!=null){
                                        ysFlutterToast(context, '卫生院绑定成功');
                                        Navigator.of(context).pop('');
                                        return;
                                      }else{
                                        return;
                                      }
                                    }
                                    return;
                                    if(User().idCard==null){
                                      Map dict = await ysRequestHttpNoLoading(context, requestType.post, 'i/upHealth', {'health_id':healths[index]['id']});
                                      if(dict!=null){
                                        ysFlutterToast(context, '卫生院绑定成功');
                                        Navigator.of(context).pop('');
                                        return;
                                      }else{
                                        return;
                                      }
                                    }
                                    Map dict1 = await ysRequestHttpNoLoading(context, requestType.post, 'transfer/coupon/getCommunityVouchers',
                                        {'idcard':User().idCard,'pageSize':1,'pageNum':10});
                                    if(dict1!=null){
                                      Map dict2 = await ysRequestHttpNoLoading(context, requestType.post, 'transfer/coupon/getUserCouponList',
                                          {'idcard':User().idCard,'pageSize':1,'pageNum':10});
                                      if(dict2!=null){
                                        // List array1 = dict1['data']['datas']??[];
                                        //array1.isEmpty&&
                                        var data = dict2['data'];
                                        bool isArray = data is List;
                                        // return;
                                        if(isArray){
                                          Map dict = await ysRequestHttpNoLoading(context, requestType.post, 'i/upHealth', {'health_id':healths[index]['id']});
                                          if(dict!=null){
                                            ysFlutterToast(context, '卫生院绑定成功');
                                            Navigator.of(context).pop('');
                                            // Navigator.of(context).pop({'id':healths[index]['id'],'name':healths[index]['name']});
                                          }
                                        }else{
                                          ysShowCenterAlertView(context, YSTipsAlertView2(
                                            tipsStr: '您已经领取两筛免费券，如需更换卫生院请联系发券机构',
                                            valueSetter: (value){
                                              // if(User().routeStr.isNotEmpty){
                                              //   Navigator.popUntil(context, ModalRoute.withName(User().routeStr));
                                              // }
                                            },
                                          ));
                                        }
                                      }
                                    }
                                  },
                                )
                              ],
                            )
                          ),
                        ),
                      ),
                    );
                  },
                  separatorBuilder: (context,index){
                    return Divider(height: 20,thickness: 20,color: Color(0xFFF5F3F0),);
                  },
                  itemCount: healths.length,
                  padding: EdgeInsets.only(top: 20,bottom: 20),
                ),
              ),
            )
          ],
        ),
      ),
    );
  }

  _getAreaData() async{
    Map dict = await ysRequestHttpNoLoading(context, requestType.post, 'common/county', {});
    if(dict!=null){
      areas = dict['data'];
      if(widget.areaId!=null){
        _isStop = true;
        selectedIndex = areas.indexWhere((element) => element['id']==widget.areaId);
      }
      setState(() {});
      _refreshData();
      // _scroll.jumpTo(selectedIndex*65*1.0);
      // Future.delayed(Duration(seconds: 1)).then((value) {
      //   _isStop = false;
      // });
      // _getHealthData(areas[selectedIndex]);
    }
  }
  int current = 1;
  int _totalNum = 0;
  _refreshData() async{//Map area
    current = 1;
    Map request = {'region_id':areas[selectedIndex]['id']};
    request['page'] = current;
    request['pageSize'] = 10;
    if(_nameField.isNotEmpty)request['name'] = _nameField;
    Map dict = await ysRequestHttpNoLoading(context, requestType.post, 'common/countyHealth', request);
    if(dict!=null){
      _refreshController.refreshCompleted();
      healths = dict['data']['datas'];
      _totalNum = dict['data']['pages']['total'];
      if(widget.healthId!=null){
        Map health = healths.firstWhere((element) => element['id']==widget.healthId,orElse: ()=>{});
        if(health.isNotEmpty){
          health['isChoose'] = true;
          healths.insert(0, health);
          healths = healths.toSet().toList();
        }
      }
      setState(() {});
    }
  }

  _loadData() async{
    current++;
    Map request = {'region_id':areas[selectedIndex]['id']};
    request['page'] = current;
    request['pageSize'] = 10;
    if(_nameField.isNotEmpty)request['name'] = _nameField;
    Map dict = await ysRequestHttpNoLoading(context, requestType.post, 'common/countyHealth', request);
    if(dict!=null){
      _refreshController.loadComplete();
      healths.addAll(dict['data']['datas']);
      if(widget.healthId!=null){
        Map health = healths.firstWhere((element) => element['id']==widget.healthId,orElse: ()=>{});
        if(health.isNotEmpty){
          health['isChoose'] = true;
          healths.insert(0, health);
          healths = healths.toSet().toList();
        }
      }
      setState(() {});
    }
  }

}
