import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/services.dart';
import 'package:flutterappfuyou/code/YSAddChapter.dart';
import 'package:flutterappfuyou/code/YSAskQuestion.dart';
import 'package:flutterappfuyou/code/base/YSNetWorking.dart';
import 'package:flutterappfuyou/code/base/YSTools.dart';
import 'package:flutterappfuyou/code/version2/YSUrlPage.dart';
import 'package:flutterappfuyou/code/version2/YSVersionView.dart';
import 'package:flutterappfuyou/code/version2/view/YSDoctorListView.dart';
import 'package:flutterappfuyou/code/version2/view/YSWikiListView.dart';
import 'package:package_info/package_info.dart';
import 'YSChapters.dart';
import 'YSChildBody.dart';
import 'YSDiary.dart';
import 'YSDoctor.dart';
import 'YSDueDate.dart';
import 'YSInformation.dart';
import 'YSMore.dart';
import 'YSPeriod.dart';
import 'YSQuestion.dart';
import 'YSRecord.dart';
import 'YSWomanBody.dart';
import 'package:shared_preferences/shared_preferences.dart';

class YSHome extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => _YSHomeState();
}
class _YSHomeState extends State<YSHome> {
  int chapter;
  bool isBoy = true;
  ScrollController _scroll = ScrollController();
  int selectedIndex = 0;
  int pageIndex = 0;
  String message = '';
  PageController _page = PageController();
  Map _info;
  List _function = [];
  List _doctors = [];
  List _wiki = [];
  bool _isPeriod = false;
  bool _isRoom = false;
  ScrollController _pageScroll = ScrollController();
  bool _isScroll = true;
  @override
  void initState() {
    Future.delayed(Duration(seconds: 0)).then((value) {
      _getUserData();
      getVersionData(context);
      toPage2(context);
    });
    Future<SharedPreferences> _prefer = SharedPreferences.getInstance();
    _prefer.then((value){
      chapter = value.getInt('chapters')??0;
      _getChapterData(chapter+1, value.getInt('childId')??0);
    });
    super.initState();
  }
  @override
  Widget build(BuildContext context){
    return AnnotatedRegion<SystemUiOverlayStyle>(
      value: SystemUiOverlayStyle.light,
      child: Scaffold(
        backgroundColor: Color(0xFFF5F3F0),
        body: chapter==null?Container(
          height: ysHeight(context),
          width: ysWidth(context),
          color: Colors.white,
        ):RefreshIndicator(
          onRefresh: _refresh,
          child: SingleChildScrollView(
            controller: _pageScroll,
            child: Container(
              color: Color(0xFFF5F3F0),
                child: Stack(
                  children: [
                    Container(
                      width: MediaQuery.of(context).size.width,
                      height: 204,
                      color: Colors.white,
                      child: Image(
                        image: AssetImage(chapter==0?'lib/images/beiyunbg.png':chapter==1?'lib/images/yunchanbg.png':isBoy?'lib/images/babybg.png':'lib/images/babybg2.png'),
                        fit: BoxFit.fill,
                      )
                    ),
                    Container(
                      width: 100,
                      height: 20,
                      margin: EdgeInsets.only(top: MediaQuery.of(context).padding.top+10,left: MediaQuery.of(context).size.width/2-50),
                      child: Text(chapter==0?'备孕篇':chapter==1?'孕产篇':'儿童篇',style: TextStyle(color: Colors.white,fontSize: 16,decoration: TextDecoration.none,fontWeight: FontWeight.normal),textAlign: TextAlign.center,),
                    ),
                    Container(
                      margin: EdgeInsets.only(top: MediaQuery.of(context).padding.top+10,left: MediaQuery.of(context).size.width-80),
                      width: 70,
                      height: 20,
                      child: CupertinoButton(
                        padding: EdgeInsets.all(0),
                        child: Text('选择篇章',style: TextStyle(color: Colors.white,fontSize: 13,decoration: TextDecoration.none,fontWeight: FontWeight.normal),textAlign: TextAlign.center,),
                        onPressed: (){
                          Navigator.of(context,rootNavigator: true).push(
                            CupertinoPageRoute(
                              builder: (context){
                                return YSChapters();
                              }
                            )
                          ).then((value){
                            if(value!=null){//
                              _getChapterData(value['chapters'], value['child']);
                              // _postChapterChooseData(value['chapters'],childId: value['child']);
                            }
                          });
                        },
                      ),
                    ),
                    Container(
                      margin: EdgeInsets.only(left: chapter==0?10:chapter==1?0:35,top: chapter==0?MediaQuery.of(context).padding.top+50:chapter==1?
                      MediaQuery.of(context).padding.top+35:MediaQuery.of(context).padding.top+75),
                      height: chapter==0?120:chapter==1?150:66,
                      width: chapter==0?120:chapter==1?150:66,
                      decoration: BoxDecoration(
                        color: chapter==0?Colors.transparent:chapter==1?Colors.transparent:Colors.white,
                        borderRadius: BorderRadius.all(Radius.circular(33))
                      ),
                      child: GestureDetector(
                        child: Image.asset(chapter==0?'lib/images/calendar.png':chapter==1?'lib/images/woman.png':'lib/images/baby.png'),
                        onTap: (){
                          if(chapter==0){
                            Navigator.of(context,rootNavigator: true).push(
                              CupertinoPageRoute(
                                builder: (context){
                                  return YSRecord();
                                }
                              )
                            );
                          }
                        },
                      ),
                    ),
                    if (chapter==0) Container(
                      margin: EdgeInsets.only(top: MediaQuery.of(context).padding.top+70,left: 130),
                      height: 80,
                      width: MediaQuery.of(context).size.width-140,
                      child: Column(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Text('快来记录经期吧',style: TextStyle(color: Colors.white,fontSize: 12,decoration: TextDecoration.none,fontWeight: FontWeight.normal),textAlign: TextAlign.left,),
                          Text(_isPeriod?'例假中':'未在经期',style: TextStyle(color: Colors.white,fontSize: 22,decoration: TextDecoration.none,fontWeight: FontWeight.normal),textAlign: TextAlign.left),
                          Container(
                            height: 20,
                            child: Row(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                Container(height: 20,child: Text('周期：${_info==null?0:_info['cycle']}天',style: TextStyle(color: Colors.white,fontSize: 12,decoration: TextDecoration.none,fontWeight: FontWeight.normal)),alignment: Alignment.centerLeft,),
                                CupertinoButton(
                                    padding: EdgeInsets.all(0),
                                    child: Image(height: 20,width: 20,image: AssetImage('lib/images/edit.png'),),
                                    onPressed: (){
                                      Navigator.of(context,rootNavigator: true).push(
                                        CupertinoPageRoute(
                                            builder: (context){
                                              return YSPeriod();
                                            }
                                        )
                                    ).then((value){
                                      if(value!=null){
                                        _getChapterData(1, 0);
                                      }
                                    });
                                  },

                                ),
                              ],
                            ),
                          )
                        ],
                      ),
                    ) else chapter==1?Container(
                      margin: EdgeInsets.only(top: MediaQuery.of(context).padding.top+70,left: 130),
                      height: 80,
                      width: MediaQuery.of(context).size.width-140,
                      child: Column(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          if(_info!=null)Text('距离宝宝出生还有',style: TextStyle(color: Colors.white,fontSize: 12,decoration: TextDecoration.none,fontWeight: FontWeight.normal),textAlign: TextAlign.left,),
                          RichText(
                            text: TextSpan(
                              style: TextStyle(color: Colors.white,fontSize: 22,decoration: TextDecoration.none,fontWeight: FontWeight.normal),
                              children: [
                                if(_info!=null)TextSpan(text:'${_info==null||_info['diff_in_day']>-1?0:(_info['diff_in_day']).abs()}'),
                                TextSpan(text:'天',style: TextStyle(fontSize: 12)),
                              ]
                            ),
                          ),
                          //Text('100天',style: TextStyle(color: Colors.white,fontSize: 22,decoration: TextDecoration.none,fontWeight: FontWeight.normal),textAlign: TextAlign.left),
                          Container(
                            height: 20,
                            child: Row(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                Container(height: 20, child: Text('设置预产期',style: TextStyle(color: Colors.white,fontSize: 12,decoration: TextDecoration.none,fontWeight: FontWeight.normal)),alignment: Alignment.centerLeft,),
                                CupertinoButton(
                                    padding: EdgeInsets.all(0),
                                    child: Image(height: 20,width: 20,image: AssetImage('lib/images/edit.png'),),
                                    onPressed: (){
                                      Navigator.of(context,rootNavigator: true).push(
                                        CupertinoPageRoute(
                                            builder: (context){
                                              return YSDueDate(dueDate: _info['expected_time'],);
                                            }
                                        )
                                    ).then((value) {
                                      if(value!=null){
                                        _getChapterData(chapter+1, null);
                                      }
                                    });
                                  },
                                )
                              ],
                            ),
                          ),
                          //Text('记录于${_info==null?0:_info['pregnancy_time']}',style: TextStyle(color: Colors.white,fontSize: 12,decoration: TextDecoration.none,fontWeight: FontWeight.normal),textAlign: TextAlign.left),
                        ],
                      ),
                    ):Container(
                      margin: EdgeInsets.only(top: MediaQuery.of(context).padding.top+65,left: 130),
                      height: 80,
                      width: MediaQuery.of(context).size.width-140,
                      child: Column(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Text('${_info==null?0:_info['name']}',style: TextStyle(color: Colors.white,fontSize: 18,decoration: TextDecoration.none,fontWeight: FontWeight.normal),textAlign: TextAlign.left,),
                          Container(
                            height: 20,
                            child: Row(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                Container(height: 20, child: Text('体重：${(_info!=null&&_info['weight']!=null)?_info['weight']:''}kg   身高：${(_info!=null&&_info['height']!=null)?_info['height']:''}cm ',
                                    style: TextStyle(color: Colors.white,fontSize: 12,decoration: TextDecoration.none,fontWeight: FontWeight.normal),textAlign: TextAlign.left),alignment: Alignment.centerLeft,),
                                CupertinoButton(
                                  padding: EdgeInsets.all(0),
                                  child: Image(
                                    height: 20,
                                    width: 20,
                                    image: AssetImage('lib/images/edit.png'),
                                  ),
                                  onPressed: (){
                                    Navigator.of(context,rootNavigator: true).push(
                                      MaterialPageRoute(
                                        builder: (context){
                                          return YSChildBody();
                                        }
                                      )
                                    ).then((value) async{
                                      SharedPreferences _prefer = await SharedPreferences.getInstance();
                                      _getChapterData(chapter+1, _prefer.getInt('childId')??0);
                                    });
                                  },
                                )
                              ],
                            ),
                          ),
                          Text('出生日期：${_info==null?0:_info['birthday']}',style: TextStyle(color: Colors.white,fontSize: 12,decoration: TextDecoration.none,fontWeight: FontWeight.normal),textAlign: TextAlign.left),
                        ],
                      ),
                    ),
                    Container(
                      margin: EdgeInsets.only(top: 200),
                      child: Column(
                        children: [
                          Container(
                            decoration: BoxDecoration(
                              borderRadius: BorderRadius.only(topLeft: Radius.circular(10),topRight: Radius.circular(10)),
                              color: Colors.white,
                            ),
                            height: 50,
                            child: chapter==0?Row(
                              children: [
                                Container(
                                  width: MediaQuery.of(context).size.width/2-0.25,
                                  child: Row(
                                    mainAxisAlignment: MainAxisAlignment.center,
                                    children: [
                                      Text('大姨妈来了',style: TextStyle(color: Color(0xFF7F3344),fontSize: 13,decoration: TextDecoration.none,fontWeight: FontWeight.normal),),
                                      CupertinoButton(
                                        padding: EdgeInsets.all(0),
                                        onPressed: (){
                                          _isPeriod==false?_postPeriodData(1):_deletePeriodData(1);
                                        },
                                        child: Container(
                                          height: 18,
                                          width: 30,
                                          margin: EdgeInsets.only(left: 10),
                                          child: Image.asset(_isPeriod==true?'lib/images/sliderOn.png':'lib/images/sliderOff.png'),
                                        ),
                                      )
                                    ],
                                  ),
                                ),
                                Container(
                                  height: 30,
                                  color: Color(0xFFE5E1E1),
                                  width: 0.5,
                                ),
                                Container(
                                  width: MediaQuery.of(context).size.width/2-0.25,
                                  child: Row(
                                    mainAxisAlignment: MainAxisAlignment.center,
                                    children: [
                                      Text('房事',style: TextStyle(color: Color(0xFF7F3344),fontSize: 13,decoration: TextDecoration.none,fontWeight: FontWeight.normal),),
                                      CupertinoButton(
                                        padding: EdgeInsets.all(0),
                                        onPressed: (){
                                          if(_isPeriod&&_isRoom==false){
                                            ysFlutterToast(context, '月经中不能同房');
                                            return;
                                          }
                                          _isRoom==false?_postPeriodData(2):_deletePeriodData(2);
                                        },
                                        child: Container(
                                          height: 18,
                                          width: 30,
                                          margin: EdgeInsets.only(left: 10),
                                          child: Image.asset(_isRoom==true?'lib/images/sliderOn.png':'lib/images/sliderOff.png'),
                                        ),
                                      )
                                    ],
                                  ),
                                ),
                              ],
                            ):chapter==1?Row(
                              mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                              children: [
                                // CupertinoButton(
                                //   padding: EdgeInsets.all(0),
                                //   child: Icon(Icons.keyboard_arrow_left,size: 20,color: Color(0xFFDDBBC5),),
                                //   onPressed: (){
                                //     _scroll.jumpTo(_scroll.offset-60);
                                //     selectedIndex = (_scroll.offset+(MediaQuery.of(context).size.width)/2)~/60;
                                //     _getMessageData(chapter+1, selectedIndex,false);
                                //   },
                                // ),
                                Container(
                                  height: 35,
                                  width: MediaQuery.of(context).size.width-150,
                                  child: NotificationListener(
                                    onNotification: (value){
                                      if(value.runtimeType==ScrollEndNotification){
                                        if(_isScroll==false){
                                          int value = (_scroll.offset+(MediaQuery.of(context).size.width-150)/2)~/60;
                                          _getMessageData(chapter+1, value,false);
                                        }
                                      }
                                      return true;
                                    },
                                    child: ListView.builder(
                                      itemBuilder: (context,index){
                                        return GestureDetector(
                                          onTap: (){
                                            _getMessageData(chapter+1, index+1,false);
                                          },
                                          child: Container(
                                            color: Colors.white,
                                            width: 60,
                                            alignment: Alignment.center,
                                            child: Column(
                                              children: [
                                                Container(
                                                  // child: index==5?Image.asset('lib/images/today.png'):null,
                                                  width: 20,
                                                  height: 10,
                                                  margin: EdgeInsets.only(left: 35),//+1
                                                ),
                                                Text((index~/7).toInt().toString()+'周+'+(index%7+1).toString(),style: TextStyle(color: selectedIndex==index?Color(0xFF8E1B3C):Color(0xFFDDBBC5),
                                                    fontSize: selectedIndex==index?16:12,decoration: TextDecoration.none,fontWeight: FontWeight.normal),),
                                              ],
                                            )
                                          ),
                                        );
                                      },
                                      itemCount: 280,
                                      scrollDirection: Axis.horizontal,
                                      controller: _scroll,
                                    ),
                                  ),
                                ),
                                // CupertinoButton(
                                //   padding: EdgeInsets.all(0),
                                //   child: Icon(Icons.keyboard_arrow_right,size: 20,color: Color(0xFFDDBBC5),),
                                //   onPressed: (){
                                //     _scroll.jumpTo(_scroll.offset+60);
                                //     selectedIndex = (_scroll.offset+(MediaQuery.of(context).size.width)/2)~/60;
                                //     _getMessageData(chapter+1, selectedIndex,false);
                                //   },
                                // ),
                              ],
                            ):Row(
                              children: [
                                if(_info!=null)Container(
                                  width: MediaQuery.of(context).size.width/2-0.25,
                                  child: Text('今天是${_info['name']}出生的第${_info['diff_in_day']}天',style: TextStyle(color: Color(0xFF7F3344),fontSize: 12,decoration: TextDecoration.none,fontWeight: FontWeight.normal),textAlign: TextAlign.center,),
                                ),
                                Container(
                                  height: 30,
                                  color: Color(0xFFE5E1E1),
                                  width: 0.5,
                                ),
                                Container(
                                  width: MediaQuery.of(context).size.width/2-0.25,
                                  child: CupertinoButton(
                                    padding: EdgeInsets.all(0),
                                    child: Container(
                                      width: 120,
                                      child: Row(
                                        crossAxisAlignment: CrossAxisAlignment.center,
                                        children: [
                                          Image(height: 20,width: 20,image: AssetImage('lib/images/babyInfo.png'),),
                                          Text('  查看宝宝资料',style: TextStyle(color: Color(0xFF7F3344),fontSize: 12,decoration: TextDecoration.none,fontWeight: FontWeight.normal),),
                                        ],
                                      ),
                                    ),
                                    onPressed: (){
                                      Navigator.of(context,rootNavigator: true).push(
                                        CupertinoPageRoute(
                                          builder: (context){
                                            return YSAddChapter(isEdit: true,);
                                          }
                                        )
                                      ).then((value) async{
                                        if(value!=null){
                                          SharedPreferences _prefer = await SharedPreferences.getInstance();
                                          _getChapterData(chapter+1, _prefer.getInt('childId')??0);
                                        }
                                      });
                                    },
                                  ),
                                ),
                              ],
                            ),
                          ),
                          chapter==0?Container():Container(
                            width: MediaQuery.of(context).size.width-10,
                            padding: EdgeInsets.all(10),
                            decoration: BoxDecoration(color: Colors.white,borderRadius: BorderRadius.all(Radius.circular(6))),
                            margin: EdgeInsets.only(top: 5),
                            child: message.isEmpty?Row(
                              children: [
                                Container(
                                  margin: EdgeInsets.only(left: 30,right: 30),
                                  height: 50,
                                  width: 80,
                                  child: Image.asset('lib/images/noMsg.png'),
                                ),
                                Text('您的消息会在这里展示',style: TextStyle(color: Color(0xFFBCBCBC),fontSize: 12,decoration: TextDecoration.none,fontWeight: FontWeight.normal),),
                              ],
                            ):Text(message,style: TextStyle(color: Color(0xFFBCBCBC),fontSize: 12,decoration: TextDecoration.none,fontWeight: FontWeight.normal),),
                          ),
                          chapter>1?Container():Container(
                            width: MediaQuery.of(context).size.width-10,
                            height: 100,
                            decoration: BoxDecoration(color: Colors.white,borderRadius: BorderRadius.all(Radius.circular(6))),
                            margin: EdgeInsets.only(top: 5),
                            child: Container(
                              height: 82,
                              child: ListView.builder(
                                  scrollDirection: Axis.horizontal,
                                  itemCount: _function.length>4?4:_function.length,
                                  itemBuilder: (context,index){
                                    return GestureDetector(
                                      onTap: (){
                                        Navigator.of(context,rootNavigator: true).push(
                                          CupertinoPageRoute(
                                            builder: (context){
                                              if(_function.length>4&&index==3){
                                                return YSMore();
                                              }else if(_function[index]['value']=='PregnancyDiary'){
                                                return YSDiary();
                                              }else if(_function[index]['value']=='PregnancyBody'){
                                                return YSWomanBody();
                                              }else if(_function[index]['value']=='MotherhoodDiary'){
                                                return YSDiary();
                                              }else if(_function[index]['value']=='ChildBody'){
                                                return YSChildBody();
                                              }else if(_function[index]['value']=='ChildDiary'){
                                                return YSDiary();
                                              }else if('${_function[index]['value']}'.contains('http')==true){
                                                return YSUrlPage(url: _function[index]['value'],title: _function[index]['name']);
                                              }else{
                                                return YSMore();
                                              }
                                            }
                                          )
                                        );
                                      },
                                      child: Container(
                                        height: 82,
                                        padding: EdgeInsets.only(top: 10,bottom: 10),
                                        width: (MediaQuery.of(context).size.width-10)/4,
                                        child: Column(
                                          mainAxisAlignment: MainAxisAlignment.spaceAround,
                                          children: [
                                            Image(image:_function.length>4&&index==3?AssetImage('lib/images/more.png'):NetworkImage('${_function[index]['img']}'),height: 36,width: 36,),
                                            Text(_function.length>4&&index==3?'更多':'${_function[index]['name']}',style: TextStyle(color: Color(0xFF7F3344),fontSize: 11,decoration: TextDecoration.none,fontWeight: FontWeight.normal),),
                                          ],
                                        ),
                                      ),
                                    );
                                  }
                              ),
                            ),
                          ),
                          Container(
                            width: MediaQuery.of(context).size.width-10,
                            height: 70+90.5*2,
                            decoration: BoxDecoration(color: Colors.white,borderRadius: BorderRadius.all(Radius.circular(6))),
                            margin: EdgeInsets.only(top: 5),
                            padding: EdgeInsets.only(left: 10,right: 10,top: 10,bottom: 5),
                            child: Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                Container(
                                  height: 25,
                                  child: Row(
                                    children: [
                                      Image(image:AssetImage('lib/images/zhaunjia.png'),width: 20,height: 20,),
                                      GestureDetector(
                                        onTap: (){
                                          _getDoctorData(chapter+1);
                                        },
                                        child: Container(
                                          margin: EdgeInsets.only(left: 5,right: 5),
                                          child: Text(' 问专家',style: TextStyle(color: Color(0xFF7F3344),fontSize: 13,decoration: TextDecoration.none,fontWeight: FontWeight.w600),),
                                        ),
                                      ),
                                      GestureDetector(
                                        onTap: (){
                                          _getPolicyData();
                                        },
                                        child: Text(' 问政策',style: TextStyle(color: Color(0xFF7F3344),fontSize: 13,decoration: TextDecoration.none,fontWeight: FontWeight.w600),)
                                      ),
                                      Container(width: MediaQuery.of(context).size.width-198,),
                                      CupertinoButton(
                                        padding: EdgeInsets.all(0),
                                        child: Text('大厅',style: TextStyle(color: Color(0xFF7F3344),fontSize: 13,decoration: TextDecoration.none,fontWeight: FontWeight.w600),),
                                        onPressed: (){
                                          Navigator.of(context,rootNavigator: true).push(
                                            CupertinoPageRoute(
                                              builder: (context){
                                                return YSQuestion();
                                              }
                                            )
                                          );
                                        },
                                      )
                                    ],
                                  ),
                                ),
                                Container(height: 2,width: 30,color: Color(0xFF7F3344),margin: EdgeInsets.only(left: pageIndex==0?35:82,bottom: 5),),
                                Container(
                                  height: 90.0*2,
                                  child: PageView(
                                    controller: _page,
                                    onPageChanged: (index){
                                      index==0?_getDoctorData(chapter+1):_getPolicyData();
                                    },
                                    children: [
                                      Container(
                                        height: 90.0*2,
                                        child: ListView.separated(
                                          itemBuilder: (context,index){
                                            Map item = _doctors[index];
                                            return YSDoctorListView(doctorItem: item,);
                                          },
                                          separatorBuilder: (context,index){
                                            return Divider(height: 0.5,thickness: 0.5,color: Color(0xFFE6E1E1),);
                                          },
                                          itemCount: _doctors.length>2?2:_doctors.length,
                                          physics: NeverScrollableScrollPhysics(),
                                          padding: EdgeInsets.all(0),
                                        ),
                                      ),
                                      Container(
                                        height: 90.0*2,
                                        child: ListView.separated(
                                          itemBuilder: (context,index){
                                            return GestureDetector(
                                              behavior: HitTestBehavior.opaque,
                                              onTap: (){
                                                Navigator.of(context,rootNavigator: true).push(
                                                  CupertinoPageRoute(
                                                    builder: (context){
                                                      return YSAskQuestion(info: _doctors[index],isPolicy: true,);
                                                    }
                                                  )
                                                );
                                              },
                                              child: Container(
                                                height: 90,
                                                child: Row(
                                                  children: [
                                                    Container(
                                                      height: 70,
                                                      width: 70,
                                                      decoration: BoxDecoration(
                                                        borderRadius: BorderRadius.all(Radius.circular(35)),
                                                        color: Color(0xFFD1D1D1),
                                                        image: DecorationImage(
                                                          fit: BoxFit.cover,
                                                          image: NetworkImage('${_doctors[index]['avatar']}'),
                                                        )
                                                      ),
                                                    ),
                                                    Container(
                                                      margin: EdgeInsets.only(left: 10),
                                                      height: 60,
                                                      width: MediaQuery.of(context).size.width-140,
                                                      child: Column(
                                                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                                        crossAxisAlignment: CrossAxisAlignment.start,
                                                        children: [
                                                          Text('${_doctors[index]['name']}',style: TextStyle(color: Color(0xFF0F0F0F),fontSize: 14,decoration: TextDecoration.none,fontWeight: FontWeight.w600),
                                                            maxLines: 1,overflow: TextOverflow.ellipsis,textAlign: TextAlign.left,),
                                                          Text('${_doctors[index]['introduction']}',style: TextStyle(color: Color(0xFF0F0F0F),fontSize: 11,
                                                              decoration: TextDecoration.none,fontWeight: FontWeight.normal),maxLines: 2,overflow: TextOverflow.ellipsis,),
                                                        ],
                                                      ),
                                                    )
                                                  ],
                                                ),
                                              ),
                                            );
                                          },
                                          separatorBuilder: (context,index){
                                            return Divider(height: 0.5,thickness: 0.5,color: Color(0xFFE6E1E1),);
                                          },
                                          itemCount: _doctors.length>2?2:_doctors.length,
                                          physics: NeverScrollableScrollPhysics(),
                                          padding: EdgeInsets.all(0),
                                        ),
                                      )
                                    ],
                                  ),
                                ),
                                Container(
                                  height: 20,
                                  width: MediaQuery.of(context).size.width-30,
                                  child: CupertinoButton(
                                    padding: EdgeInsets.all(0),
                                    child: Text('更多',style: TextStyle(color: Color(0xFF7F3344),fontSize: 13,decoration: TextDecoration.none,fontWeight: FontWeight.w600),),
                                    onPressed: (){
                                      Navigator.of(context,rootNavigator: true).push(
                                        CupertinoPageRoute(
                                          builder: (context){
                                            return YSDoctor(isPolicy: pageIndex==0?false:true,);
                                          }
                                        )
                                      );
                                    },
                                  ),
                                  alignment: Alignment.center,
                                )
                              ],
                            ),
                          ),
                          chapter>1?Container(
                            width: MediaQuery.of(context).size.width-10,
                            height: 100,
                            decoration: BoxDecoration(color: Colors.white,borderRadius: BorderRadius.all(Radius.circular(6))),
                            margin: EdgeInsets.only(top: 5),
                            child: Container(
                              height: 82,
                              child: ListView.builder(
                                  scrollDirection: Axis.horizontal,
                                  itemCount: _function.length>4?4:_function.length,
                                  itemBuilder: (context,index){
                                    return GestureDetector(
                                      onTap: (){
                                        Navigator.of(context,rootNavigator: true).push(
                                            CupertinoPageRoute(
                                                builder: (context){
                                                  if(_function.length>4&&index==3){
                                                    return YSMore();
                                                  }else if(_function[index]['value']=='PregnancyDiary'){
                                                    return YSDiary();
                                                  }else if(_function[index]['value']=='PregnancyBody'){
                                                    return YSWomanBody();
                                                  }else if(_function[index]['value']=='MotherhoodDiary'){
                                                    return YSDiary();
                                                  }else if(_function[index]['value']=='ChildBody'){
                                                    return YSChildBody();
                                                  }else if(_function[index]['value']=='ChildDiary'){
                                                    return YSDiary();
                                                  }else if('${_function[index]['value']}'.contains('http')==true){
                                                    return YSUrlPage(url: _function[index]['value'],title: _function[index]['name']??'',);
                                                  }else{
                                                    return YSMore();
                                                  }
                                                }
                                            )
                                        );
                                      },
                                      child: Container(
                                        height: 82,
                                        padding: EdgeInsets.only(top: 10,bottom: 10),
                                        width: (MediaQuery.of(context).size.width-10)/4,
                                        child: Column(
                                          mainAxisAlignment: MainAxisAlignment.spaceAround,
                                          children: [
                                            Image(image:_function.length>4&&index==3?AssetImage('lib/images/more.png'):NetworkImage('${_function[index]['img']}'),height: 36,width: 36,),
                                            Text(_function.length>4&&index==3?'更多':'${_function[index]['name']}',style: TextStyle(color: Color(0xFF7F3344),fontSize: 11,decoration: TextDecoration.none,fontWeight: FontWeight.normal),),
                                          ],
                                        ),
                                      ),
                                    );
                                  }
                              ),
                            ),
                          ):Container(),
                          Container(
                            width: MediaQuery.of(context).size.width-10,
                            decoration: BoxDecoration(color: Colors.white,borderRadius: BorderRadius.all(Radius.circular(6))),
                            margin: EdgeInsets.only(top: 5,bottom: 60),
                            padding: EdgeInsets.all(10),
                            child: Column(
                              children: [
                                Container(
                                  margin:EdgeInsets.only(bottom: 5),
                                  height: 20,
                                  child: Row(
                                    children: [
                                      Image(image:AssetImage('lib/images/babyCar.png'),width: 20,height: 20,),
                                      Text(' ${chapter==0?'备孕':chapter==1?'孕产':'育儿'}百科',style: TextStyle(color: Color(0xFF7F3344),fontSize: 13,decoration: TextDecoration.none,fontWeight: FontWeight.w600),),
                                      Container(width: MediaQuery.of(context).size.width-154,),
                                      CupertinoButton(
                                        padding: EdgeInsets.all(0),
                                        child: Text('更多',style: TextStyle(color: Color(0xFF7F3344),fontSize: 13,decoration: TextDecoration.none,fontWeight: FontWeight.w600),),
                                        onPressed: (){
                                          Navigator.of(context,rootNavigator: true).push(
                                            CupertinoPageRoute(
                                              builder: (context){
                                                return YSInformation();
                                              }
                                            )
                                          );
                                        },
                                      )
                                    ],
                                  ),
                                ),
                                Container(
                                  child: ListView.separated(
                                    shrinkWrap: true,
                                    itemBuilder: (context,index){
                                      Map item = _wiki[index];
                                      return YSWikiListView(
                                        wikiItem: item,
                                        callback: () async{
                                          SharedPreferences _prefer = await SharedPreferences.getInstance();
                                          _getChapterData(chapter+1, _prefer.getInt('childId')??0);
                                        },
                                      );
                                    },
                                    separatorBuilder: (context,index){
                                      return Divider(height: 0.5,thickness: 0.5,color: Color(0xFFE6E1E1),);
                                    },
                                    itemCount: _wiki.length>5?5:_wiki.length,
                                    physics: NeverScrollableScrollPhysics(),
                                    padding: EdgeInsets.all(0),
                                  ),
                                ),
                              ],
                            ),
                          ),
                        ],
                      ),
                    )
                  ],
              ),
            ),
          ),
        ),
      ),
    );
  }

   Future<void> _refresh() async{
    SharedPreferences _prefer = await SharedPreferences.getInstance();
    _getChapterData(chapter+1, _prefer.getInt('childId')??0);
  }
  
  // _postChapterChooseData(chapter,{childId}) async{
  //   LogUtil.d(chapter);
  //   Map request = {};
  //   request['period'] = chapter;
  //   if(childId!=0){
  //     request['child_id'] = childId;
  //   }
  //   Map dict = await ysRequestHttpNoLoading(context, requestType.post, 'userPeriodState/period', request);
  //   if(dict!=null){}
  // }

  _getChapterData(int chap,int childId) async{
    _getFunctionData(chap,childId);
    _getDoctorData(chap);
    _getWikiData(chap);
    Map param = Map();
    param['category_id'] = chap;
    if(childId!=0){
      param['child_id'] = childId;
    }
    Map dict = await ysRequestHttpNoLoading(context, requestType.get, 'chapter/info', param);
    if(dict!=null){
      if(chap!=1){
        if(chap==2){
          _isScroll = true;
          int week = dict['data']['pregnancy_week'];
          // if(week>0){
          //   week = week-1;
          // }
          int day = dict['data']['pregnancy_day'];
          if(day>0){
            // day = day-1;
          }
          _getMessageData(chap, (week*7+day),true);
        }else{
          _getMessageData(chap, dict['data']['diff_in_day'],true);
        }
      }
      setState(() {
        chapter = chap-1;
        User().chapter = chapter;
        _info = dict['data'];
        if(chapter==2){
          if(dict['data']['gender']==1){
            isBoy = true;
          }else{
            isBoy = false;
          }
        }
      });
    }
  }

  _getMessageData(int chap,int number,bool isGet) async{
    number = number.abs();
    Map param = Map();
    LogUtil.d('chap=========$chap');
    param['category_id'] = chap;
    int day = number>280?280:number;
    if(chap==3){
      day = number>360?360:number;
    }
    param['day'] = day;
    Map dict = await ysRequestHttpNoLoading(context, requestType.get, 'chapter/tips', param);
    if(dict!=null){
      setState(() {
        if(chap==2){
          if(isGet==true){
            _scroll.jumpTo((day-1)*60.0);
            selectedIndex = day-1;
          }else{
            selectedIndex = day-1;
          }
        }else{
          selectedIndex = number;
        }
        Future.delayed(Duration(seconds: 1)).then((value) {
          _isScroll=false;
        });
        message = dict['data']['value'];
      });
    }
  }

  _getFunctionData(int chap,int childId) async{
    Map param = Map();
    param['category_id'] = chap;
    param['type'] = 'ios';
    if(childId!=0)param['child_id'] = childId;
    _function = await ysRequestHttpNoLoading(context, requestType.post, 'tool/list', param)??[];
    if(_function.length>0){
      setState(() {});
    }
  }

  _getDoctorData(int chap) async{
    Map dict = await ysRequestHttpNoLoading(context, requestType.post, 'doctor/list', {'category_id':chap});
    if(dict!=null){
      setState(() {
        pageIndex = 0;
        _page.jumpToPage(0);
        _doctors = dict['data']??[];
      });
    }
  }

  _getPolicyData() async{
    var dict = await ysRequestHttpNoLoading(context, requestType.get, 'policy/doctor', {});
    if(dict!=null){
      setState(() {
        pageIndex = 1;
        _page.jumpToPage(1);
        _doctors = dict;
      });
    }
  }

  _getWikiData(int chap) async{
    Map dict = await ysRequestHttpNoLoading(context, requestType.get, 'wike/list', {'category_id':chap});
    if(dict!=null){
      setState(() {
        _wiki = dict['data']??[];
      });
    }
  }

  _postPeriodData(int type) async{
    String date = DateTime.now().year.toString()+'-'+DateTime.now().month.toString()+'-'+DateTime.now().day.toString();
    Map dict = await ysRequestHttpNoLoading(context, requestType.post, 'motherhood/periodDate/add', {'type':type.toString(),'date':date});
    if(dict!=null){
      setState(() {
        if(type==1){
          _isPeriod = true;
        }else{
          _isRoom = true;
        }
      });
    }
  }

  _deletePeriodData(int type) async{
    String date = DateTime.now().year.toString()+'-'+DateTime.now().month.toString()+'-'+DateTime.now().day.toString();
    Map dict = await ysRequestHttpNoLoading(context, requestType.delete, 'motherhood/periodDate/delete', {'type':type.toString(),'date':date});
    if(dict!=null){
      setState(() {
        if(type==1){
          _isPeriod = false;
        }else{
          _isRoom = false;
        }
      });
    }
  }

  _getUserData() async{
    Map dict = await ysRequestHttpNoLoading(context, requestType.get, 'user/info', {});
    if(dict!=null){
      User().userId = '${dict['id']}';
      User().avatar = '${dict['avatar']}';
      User().name = dict['simple_name']??dict['username']??'';
      User().idCard = dict['id_card']??'';
    }
  }

}