import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutterappfuyou/YSPage.dart';
import 'package:flutterappfuyou/code/YSMeans.dart';
import 'package:flutterappfuyou/code/base/YSBase.dart';
import 'package:flutterappfuyou/code/base/YSTools.dart';
import 'package:flutterappfuyou/code/version3/view/YSChapterInputView.dart';
import 'package:shared_preferences/shared_preferences.dart';

import '../base/YSNetWorking.dart';

class YSPerfectChapterInfo extends StatefulWidget {
  final bool isFirst;
  const YSPerfectChapterInfo({Key key, this.isFirst = false}) : super(key: key);

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

class _YSPerfectChapterInfoState extends State<YSPerfectChapterInfo> {
  List _titleArray = [
    {'title':'备孕篇'},
    {'title':'孕产篇'},
    {'title':'儿童篇'}
  ];
  int _pageIndex = 1;
  List _showArray = [
    [{'title':'月经一般持续天数','type':1,'image':'母血补采'},{'title':'月经周期天数','type':1,'image':'时钟 2'}],
    [{'title':'预产期','type':2,'image':'日历 2'}],
    [{'title':'宝宝姓名','type':1,'image':'编组 9备份 6'},{'title':'宝宝生日','type':2,'image':'生日 2'},
      {'title':'宝宝性别','type':2,'image':'男女 2'},{'title':'保健册号','type':1,'image':'手册 2'}]
  ];
  SharedPreferences _prefs;
  @override
  void initState() {
    _getSharedPreferences();
    // Future.delayed(Duration(seconds: 0)).then((value) {
    //   _getInfoData();
    // });
    super.initState();
  }
  _getSharedPreferences() async{
    _prefs = await SharedPreferences.getInstance();
  }
  _getInfoData() async{
    Map dict1 = await ysRequestHttpNoLoading(context, requestType.get, 'chapter/info', {'category_id':1});
    if(dict1!=null){
      Map data = dict1['data']??{};
      List array1 = _showArray[0];
      array1.clear();
      array1.addAll([
        {'title':'月经一般持续天数','type':1,'image':'母血补采','value':'${data['duration']??''}'},{'title':'月经周期天数','type':1,'image':'时钟 2','value':'${data['duration']??''}'}
      ]);
      setState(() {});
    }
    Map dict2 = await ysRequestHttpNoLoading(context, requestType.get, 'chapter/info', {'category_id':2});
    if(dict2!=null){
      Map data = dict2['data']??{};
      List array2 = _showArray[1];
      array2.clear();
      array2.addAll([
        {'title':'预产期','type':2,'image':'日历 2','value':data['expected_time']}
      ]);
    }
    // Map dict3 = await ysRequestHttpNoLoading(context, requestType.get, 'chapter/info', {'category_id':3});
    // if(dict3!=null){
    //   Map data = dict3['data']??{};
    //   List array2 = _showArray[1];
    //   array2.clear();
    //   array2.addAll([
    //     {'title':'预产期','type':2,'image':'日历 2','value':data['expected_time']}
    //   ]);
    // }
  }

  @override
  Widget build(BuildContext context) {
    List array = _showArray[_pageIndex];
    return YSBase(
      ystitle: '选择篇章',
      isBack: widget.isFirst==false,
      yschild: Container(
        margin: EdgeInsets.only(left: 30,right: 30),
        child: SingleChildScrollView(
          child: Column(
            children: [
              Container(
                margin: EdgeInsets.only(top: 30,bottom: 30),
                height: 120,
                child: GridView.builder(gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                  crossAxisCount: _titleArray.length,
                  childAspectRatio: (ysWidth(context)-60)/3/120
                ), itemBuilder: (context,index){
                  Map item = _titleArray[index];
                  return GestureDetector(
                    onTap: (){
                      _pageIndex = index;
                      setState(() {});
                    },
                    behavior: HitTestBehavior.opaque,
                    child: Container(
                      child: LayoutBuilder(builder: (context,conSize){
                        return Column(
                          children: [
                            Image.asset('lib/images/fy_chapter${index+1}_${_pageIndex==index?'2':'1'}.png',height: 90,width: 90,),
                            Container(
                              height: 30,
                              child: Text(item['title'],style: TextStyle(fontSize: 18,color: Color(0xFF444444)),),
                            )
                          ],
                        );
                      }),
                    ),
                  );
                },itemCount: _titleArray.length,padding: EdgeInsets.all(0),physics: NeverScrollableScrollPhysics(),),
              ),
              DashLine(width: 5,color: Color(0xFF979797),height: 1,),
              Container(
                height: ysHeight(context)-ysTOP(context)-261,
                key: Key('$_pageIndex'),
                margin: EdgeInsets.all(15),
                child: SingleChildScrollView(
                  child: Column(
                    children: [
                      if(_pageIndex==1)Container(
                        child: Text('请输入产检时医生告知的预产期，如尚未产检可以使用“计算预产期”',style: TextStyle(fontSize: 12,color: Color(0xFF8A8A8A)),),
                        padding: EdgeInsets.only(top: 20),
                      ),
                      array.isNotEmpty?ListView.separated(
                        itemBuilder: (context,indexSub){
                          Map item = array[indexSub];
                          int type = item['type'];
                          return type==1?YSChapterInputView(
                            item: item,
                          ):YSChapterChooseView(
                            item: item,
                          );
                        },
                        separatorBuilder: (context,index){
                          return Container(height: 30,);
                        },
                        itemCount: array.length,
                        shrinkWrap: true,
                        physics: NeverScrollableScrollPhysics(),
                        padding: EdgeInsets.only(top: 20),
                      ):Container(height: 100,),
                      if (_pageIndex==1) GestureDetector(
                        onTap: (){
                          ysShowCenterAlertView(context, YSCountDateView(postDate: (value){
                            array[0]['value'] = value;
                            setState(() {});
                          },));
                        },
                        child: Container(
                          margin: EdgeInsets.only(top: 10,bottom: 60),
                          height: 20,
                          alignment: Alignment.centerRight,
                          child: Row(
                            mainAxisSize: MainAxisSize.min,
                            children: [
                              Text('计算预产期  ',style: TextStyle(fontSize: 12,color: Color(0xFF808080),decoration: TextDecoration.none,fontWeight: FontWeight.normal),),
                              Image(height: 15,width: 15,image: AssetImage('lib/images/calculte.png'),),
                            ],
                          ),
                        ),
                      ) else Container(height: 60,),
                      YSSubmitView(callback: (){
                        if(_pageIndex==0){
                          _postPeriodData();
                        }else if(_pageIndex==1){
                          _postDueData();
                        }else if(_pageIndex==2){
                          _postChildData();
                        }
                      },title: _pageIndex==1?'下一步':'完成',)
                    ],
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  _postPeriodData() async{
    List array0 = _showArray[0];
    if(array0.isEmpty)return;
    Map cxMap = array0[0];
    Map zqdMap = array0[1];
    if(zqdMap['value']==null){
      ysFlutterToast(context, '请输入周期时间');
      return;
    }
    if(int.parse(zqdMap['value'])>51){
      ysFlutterToast(context, '周期时间过长');
      return;
    }
    if(cxMap['value']==null){
      ysFlutterToast(context, '请输入持续时间');
      return;
    }
    if(int.parse(cxMap['value'])>51){
      ysFlutterToast(context, '持续时间过长');
      return;
    }
    Map dict = await ysRequestHttp(context,requestType.put, 'motherhood/period', {'cycle':zqdMap['value'],'duration':cxMap['value']});
    if(dict!=null){
      _jumpPage();
    }
  }

  _postDueData() async{
    List array1 = _showArray[1];
    if(array1.isEmpty)return;
    Map ycMap = array1[0];
    if(ycMap['value']==null){
      ysFlutterToast(context, '请选择预产期');
      return;
    }
    Map dict = await ysRequestHttpNoLoading(context, requestType.post, 'phase/dueDate', {'expected_time':ycMap['value']});
    if(dict!=null){
      _jumpPage();
    }
  }

  _postChildData() async{
    List array2 = _showArray[2];
    if(array2.isEmpty)return;
    Map xmMap = array2[0];
    Map srMap = array2[1];
    Map xbMap = array2[2];
    Map bjMap = array2[3];
    if(xmMap['value']==null){
      ysFlutterToast(context, '请完善宝宝姓名');
      return;
    }
    if(srMap['value']==null){
      ysFlutterToast(context, '请完善宝宝生日');
      return;
    }
    if(xbMap['value']==null){
      ysFlutterToast(context, '请完善宝宝性别');
      return;
    }
    if(bjMap['value']==null){
      ysFlutterToast(context, '请完善保健册号');
      return;
    }
    DateTime now = DateTime.now();
    DateTime expected = DateTime.parse('${srMap['value']} ${now.hour.toString().padLeft(2,'0')}:${now.minute.toString().padLeft(2,'0')}:${now.second.toString().padLeft(2,'0')}');
    bool isBefore = now.isBefore(expected);
    if(isBefore){
      ysFlutterToast(context, '宝宝生日不能大于当前日期');
      return;
    }
    Map pragma = Map();
    pragma['name'] = xmMap['value'];
    pragma['health_book'] = bjMap['value'];
    pragma['birthday'] = srMap['value'];
    if(xbMap['value']=='男'){
      pragma['gender'] = 1;
    }else{
      pragma['gender'] = 2;
    }
    Map dict = await ysRequestHttp(context,requestType.post, 'child/chapter/addOrUp', pragma);
    if(dict!=null){
      _prefs.setInt('childId', dict['data']['child_id']);
      _jumpPage();
    }
  }

  _jumpPage() {
    if(true){//widget.isFirst
      _prefs.setInt('chapters', _pageIndex);
      if(true){//_pageIndex==1
        Navigator.of(context).pushAndRemoveUntil(CupertinoPageRoute(builder: (context){
          return YSMeans(isFirst: true,);
        }), (route) => false);
      }else{
        Navigator.of(context).pushAndRemoveUntil(CupertinoPageRoute(builder: (context){
          return YSPage();
        }), (route) => false);
      }
    }else{
      Navigator.of(context).pop('完成');
    }
  }

}

class YSCountDateView extends StatefulWidget {
  final ValueSetter postDate;
  const YSCountDateView({Key key, this.postDate}) : super(key: key);

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

class _YSCountDateViewState extends State<YSCountDateView> {
  String _dateStr = '';
  @override
  Widget build(BuildContext context) {
    return Center(
      child: Container(
        width: MediaQuery.of(context).size.width-60,
        padding: EdgeInsets.all(15),
        height: 150,
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.all(Radius.circular(10))
        ),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            Text('计算预产期',style: TextStyle(fontSize: 14,color: Color(0xFF292929),decoration: TextDecoration.none,fontWeight: FontWeight.w600),),
            CupertinoButton(
              padding: EdgeInsets.all(0),
              child: Container(
                height: 30,
                width: MediaQuery.of(context).size.width-30,
                child: Text(_dateStr.isNotEmpty?_dateStr:'请选择末次月经时间进行计算',style: TextStyle(fontSize: 13,color: Color(0xFF808080),decoration: TextDecoration.none,fontWeight: FontWeight.normal),),
                decoration: BoxDecoration(
                    border: Border(bottom: BorderSide(width: 0.5,color: Color(0xFFD7D7D7)))
                ),
              ),
              onPressed: (){
                ysDatePicker(context, (value){
                  setState(() {
                    _dateStr = value;
                  });
                },lastDate: DateTime.now().subtract(Duration(days: 1)),initDate: DateTime.now().subtract(Duration(days: 1)));
              },
            ),
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Container(),
                Row(
                  children: [
                    CupertinoButton(
                      padding: EdgeInsets.all(0),
                      child: Text('取消',style: TextStyle(fontSize: 13,color: Color(0xFF8E1B3C),decoration: TextDecoration.none,fontWeight: FontWeight.w600),),
                      onPressed: (){
                        Navigator.pop(context);
                      },
                    ),
                    CupertinoButton(
                      padding: EdgeInsets.all(0),
                      child: Text('计算',style: TextStyle(fontSize: 13,color: Color(0xFF8E1B3C),decoration: TextDecoration.none,fontWeight: FontWeight.w600),),
                      onPressed: () async{
                        if(_dateStr.isEmpty){
                          ysFlutterToast(context, '请选择时间后进行计算');
                          return;
                        }
                        Map dict = await ysRequestHttpNoLoading(context, requestType.post, 'phase/dueDateQuery', {'date':_dateStr});
                        if(dict!=null){
                          Navigator.pop(context);
                          String dueDate = dict['data']['data'];
                          widget.postDate(dueDate);
                        }
                      },
                    )
                  ],
                )
              ],
            )
          ],
        ),
      ),
    );
  }
}
