import 'package:fl_chart/fl_chart.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutterappfuyou/code/base/YSNetWorking.dart';
import 'package:flutterappfuyou/code/base/YSTools.dart';
import 'package:shared_preferences/shared_preferences.dart';

import 'YSAddChildBody.dart';
import 'base/YSBase.dart';

class YSChildBody extends StatefulWidget {
  @override
  _YSChildBodyState createState() => _YSChildBodyState();
}

class _YSChildBodyState extends State<YSChildBody> {
  int _selected = 0;
  PageController _page = PageController();
  List _dataArray = [];
  List heightMin = <FlSpot>[];
  List heightMax = <FlSpot>[];
  List weightMin = <FlSpot>[];
  List weightMax = <FlSpot>[];
  List hAxis = [];
  List wAxis = [];
  @override
  void initState() {
    Future.delayed(Duration(seconds: 0)).then((value){
      _getChildBodyData();
      _getChildData();
    });
    super.initState();
  }
  @override
  Widget build(BuildContext context) {
    return YSBase(
      ystitle: '身高体重',
      ysright: CupertinoButton(
        padding: EdgeInsets.all(0),
        child: Container(
          height: 30,
          width: 55,
          decoration: BoxDecoration(
              color: Color(0xFFFFEB3B),
              border: Border.all(color: Color(0xFF292929),width: 1),
              borderRadius: BorderRadius.all(Radius.circular(20))
          ),
          alignment: Alignment.center,
          child: Text('添加',style: TextStyle(fontSize: 14,color: Color(0xFF292929),decoration: TextDecoration.none),),
        ),
        onPressed: (){
          Navigator.of(context).push(
            CupertinoPageRoute(
              builder: (context){
                return YSAddChildBody();
              }
            )
          ).then((value){
            if(value!=null){
              _getChildBodyData();
            }
          });
        },
      ),
      yschild: SingleChildScrollView(
        child: Column(
          children: [
            Container(
              height: 50,
              decoration: BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.only(topRight: Radius.circular(20),topLeft: Radius.circular(20)),
              ),
              padding: EdgeInsets.only(left: 20,right: 20,top: 15),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      GestureDetector(
                        // child: Text('身高体重',style: TextStyle(fontSize: 14,color: _selected==0?Color(0xFFDB5279):Color(0xFF808080)),),
                        onTap: (){
                          _page.jumpToPage(0);
                          setState(() {
                            _selected = 0;
                          });
                        },
                        child: Column(
                          children: [
                            Text('身高体重',style: TextStyle(fontSize: 14,color: _selected==0?Color(0xFFDB5279):Color(0xFF808080)),),
                            Container(
                              margin: EdgeInsets.only(top: 10),
                              height: 2,width: 30,color: _selected==0?Color(0xFFDB5279):Colors.transparent
                            )
                          ],
                        ),
                      ),
                      GestureDetector(
                        // child: Text('身高曲线',style: TextStyle(fontSize: 14,color: _selected==1?Color(0xFFDB5279):Color(0xFF808080)),),
                        onTap: (){
                          _page.jumpToPage(1);
                          setState(() {
                            _selected = 1;
                          });
                        },
                        child: Column(
                          children: [
                            Text('身高曲线',style: TextStyle(fontSize: 14,color: _selected==1?Color(0xFFDB5279):Color(0xFF808080)),),
                            Container(
                              margin: EdgeInsets.only(top: 10),
                              height: 2,width: 30,color: _selected==1?Color(0xFFDB5279):Colors.transparent
                            )
                          ],
                        ),
                      ),
                      GestureDetector(
                        // child: Text('体重曲线',style: TextStyle(fontSize: 14,color: _selected==2?Color(0xFFDB5279):Color(0xFF808080)),),
                        onTap: (){
                          _page.jumpToPage(2);
                          setState(() {
                            _selected = 2;
                          });
                        },
                        child: Column(
                          children: [
                            Text('体重曲线',style: TextStyle(fontSize: 14,color: _selected==2?Color(0xFFDB5279):Color(0xFF808080)),),
                            Container(
                              margin: EdgeInsets.only(top: 10),
                              height: 2,width: 30,color: _selected==2?Color(0xFFDB5279):Colors.transparent
                            )
                          ],
                        ),
                      ),
                    ],
                  ),
                  // Container(height: 2,width: 30,color: Color(0xFFDB5279),
                  //   margin: EdgeInsets.only(left: _selected==0?15:_selected==1?MediaQuery.of(context).size.width/3+25:MediaQuery.of(context).size.width/3*2+40),)
                ],
              ),
            ),
            Container(
              height: MediaQuery.of(context).size.height-125,
              child: PageView(
                controller: _page,
                onPageChanged: (index){
                  setState(() {
                    _selected = index;
                  });
                },
                children: [
                  Container(
                    height: MediaQuery.of(context).size.height-125,
                    child: RefreshIndicator(
                      onRefresh: _getChildBodyData,
                      child: ListView.separated(
                        itemBuilder: (context,index){
                          return GestureDetector(
                            onTap: (){
                              Navigator.of(context).push(
                                  CupertinoPageRoute(
                                      builder: (context){
                                        return YSAddChildBody(infoDict: _dataArray[index],);
                                      }
                                  )
                              ).then((value){
                                if(value!=null){
                                  _getChildBodyData();
                                }
                              });
                            },
                            child: Container(
                              height: 110,
                              padding: EdgeInsets.all(15),
                              decoration: BoxDecoration(
                                color: Colors.white,
                                borderRadius: BorderRadius.all(Radius.circular(6))
                              ),
                              child: Column(
                                crossAxisAlignment: CrossAxisAlignment.start,
                                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                children: [
                                  Text('${_dataArray[index]['created_at']}',style: TextStyle(fontSize: 14,color: Color(0xFF292929)),overflow: TextOverflow.ellipsis,),
                                  Text('宝宝出生的第${_dataArray[index]['month_age']}月',style: TextStyle(fontSize: 14,color: Color(0xFF808080)),overflow: TextOverflow.ellipsis,),
                                  Container(
                                    width: MediaQuery.of(context).size.width,
                                    height: 1.5,
                                    child: Image.asset('lib/images/line.png'),
                                  ),
                                  Container(
                                    child: Row(
                                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                      children: [
                                        RichText(
                                          text: TextSpan(
                                            style: TextStyle(fontSize: 14,color: Color(0xFF292929)),
                                            children: [
                                              TextSpan(text: '身高'),
                                              TextSpan(text: '        ${_dataArray[index]['height']}        ',style: TextStyle(color: Color(0xFFDB5279))),
                                              TextSpan(text: 'CM'),
                                            ]
                                          ),
                                        ),
                                        RichText(
                                          text: TextSpan(
                                              style: TextStyle(fontSize: 14,color: Color(0xFF292929)),
                                              children: [
                                                TextSpan(text: '体重'),
                                                TextSpan(text: '        ${_dataArray[index]['weight']}        ',style: TextStyle(color: Color(0xFFDB5279))),
                                                TextSpan(text: 'KG'),
                                              ]
                                          ),
                                        )
                                      ],
                                    ),
                                  )
                                ],
                              ),
                            ),
                          );
                        },
                        separatorBuilder: (context,index){
                          return Divider(height: 5,thickness: 5,color: Color(0xFFF5F3F0),);
                        },
                        itemCount: _dataArray.length,
                        padding: EdgeInsets.all(5),
                      ),
                    ),
                  ),
                  Container(
                    height: MediaQuery.of(context).size.height-115,
                    margin: EdgeInsets.all(5),
                    padding: EdgeInsets.only(top: 10,bottom: 10,left: 15,right: 15),
                    color: Colors.white,
                    child: Column(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        // Text('宝宝今日正常身高范围: $heightMin~$heightMax cm',style: TextStyle(fontSize: 16,color: Color(0xFF292929)),overflow: TextOverflow.ellipsis,),
                        Text('彩色区域为正常范围',style: TextStyle(fontSize: 12,color: Color(0xFFDB5279)),overflow: TextOverflow.ellipsis,),
                        Container(
                          width: MediaQuery.of(context).size.width,
                          height: 1.5,
                          child: Image.asset('lib/images/line.png'),
                        ),
                        Text('身高(cm)',style: TextStyle(fontSize: 11,color: Color(0xFF808080)),overflow: TextOverflow.ellipsis,),
                        Container(
                          height: MediaQuery.of(context).size.height-230,
                          child: _dataArray.length==0||hAxis.length==0?Container():LineChartSample7(axis: hAxis,min: heightMin,max: heightMax,data: _dataArray,type: 1,),
                        )
                      ],
                    ),
                  ),
                  Container(
                    height: MediaQuery.of(context).size.height-115,
                    margin: EdgeInsets.all(5),
                    padding: EdgeInsets.only(top: 10,bottom: 10,left: 15,right: 15),
                    color: Colors.white,
                    child: Column(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        // Text('宝宝今日正常体重范围: $weightMin~$weightMax kg',style: TextStyle(fontSize: 16,color: Color(0xFF292929)),overflow: TextOverflow.ellipsis,),
                        Text('彩色区域为正常范围',style: TextStyle(fontSize: 12,color: Color(0xFFDB5279)),overflow: TextOverflow.ellipsis,),
                        Container(
                          width: MediaQuery.of(context).size.width,
                          height: 1.5,
                          child: Image.asset('lib/images/line.png'),
                        ),
                        Text('体重(kg)',style: TextStyle(fontSize: 11,color: Color(0xFF808080)),overflow: TextOverflow.ellipsis,),
                        Container(
                          height: MediaQuery.of(context).size.height-230,
                          child: _dataArray.length==0||wAxis.length==0?Container():LineChartSample7(axis: wAxis,min: weightMin,max: weightMax,data: _dataArray,type: 2,),
                        )
                      ],
                    ),
                  ),
                ],
              ),
            )
          ],
        ),
      ),
    );
  }

 Future<void> _getChildBodyData() async{
    SharedPreferences prefer = await SharedPreferences.getInstance();
    Map dict = await ysRequestHttp(context, requestType.get, 'child/body/list', {'child_id':prefer.getInt('childId')});
    if(dict!=null){
      setState(() {
        _dataArray = dict['data'];
      });
    }
  }

  _getChildData() async{
    SharedPreferences prefer = await SharedPreferences.getInstance();
    var dict = await ysRequestHttpNoLoading(context, requestType.get, 'chapter/info', {'category_id':prefer.getInt('chapters')+1,'child_id':prefer.getInt('childId')});
    if(dict!=null){
      _getHeightStandardData(dict['data']['gender']=='男'?1:2);
    }
  }

  _getHeightStandardData(int type) async{
    var dict = await ysRequestHttpNoLoading(context, requestType.get, 'basic/BodyStandard', {'body_type':'child','type':'height','gender':type});
    if(dict!=null){
      hAxis = dict['name'];
      heightMin = dict['min'];
      heightMax = dict['max'];
      LogUtil.d(hAxis);
      _getWeightStandardData(type);
    }
  }
  _getWeightStandardData(int type) async{
    var dict = await ysRequestHttpNoLoading(context, requestType.get, 'basic/BodyStandard', {'body_type':'child','type':'weight','gender':type});
    if(dict!=null){
      wAxis = dict['name'];
      weightMin = dict['min'];
      weightMax = dict['max'];
    }
  }
}


class LineChartSample7 extends StatelessWidget {
  final List axis,min,max,data;
  final int type;
  const LineChartSample7({Key key, this.axis, this.min, this.max,this.data,this.type}) : super(key: key);
  @override
  Widget build(BuildContext context) {
    LogUtil.d(data);
    return SingleChildScrollView(
      padding: EdgeInsets.only(top: 5),
      scrollDirection: Axis.horizontal,
      child: SizedBox(
        width: (MediaQuery.of(context).size.width-40)*4,
        child: LineChart(
          LineChartData(
            lineTouchData: LineTouchData(enabled: false),
            lineBarsData: [
              LineChartBarData(
                spots: [
                  for(int i = 0;i<axis.length;i++)FlSpot(double.parse('${axis[i]}'),double.parse('${min[i]}'))
                ],
                isCurved: true,
                barWidth: 2,
                colors: [
                  Colors.transparent,
                ],
                dotData: FlDotData(
                  show: false,
                ),
              ),
              LineChartBarData(
                spots: [
                  for(int i = 0;i<axis.length;i++)FlSpot(double.parse('${axis[i]}'),double.parse('${max[i]}'))
                ],
                isCurved: true,
                barWidth: 2,
                colors: [
                  Colors.transparent,
                ],
                dotData: FlDotData(
                  show: false,
                ),
              ),
              LineChartBarData(
                spots: [
                  for(int i = 0;i<data.length;i++)FlSpot(double.parse('${data[i]['month_age']}'),double.parse('${type==1?data[i]['height']:data[i]['weight']}'))
                ],
                isCurved: true,
                barWidth: 2,
                colors: [
                  Colors.lightGreen,
                ],
                dotData: FlDotData(
                  show: true,
                ),
              ),
            ],
            betweenBarsData: [
              BetweenBarsData(
                fromIndex: 0,
                toIndex: 1,
                colors: [Colors.red.withOpacity(0.3)],
              )
            ],
            minY: 0,
            titlesData: FlTitlesData(
              bottomTitles: SideTitles(
                interval: 3,
                showTitles: true,
                getTitles: (value) {
                  return value.toInt().toString()+'月';
                },
              ),
              leftTitles: SideTitles(
                showTitles: true,
                getTitles: (value) {
                  return value%3==0?value.toInt().toString():'';
                },
              ),
              rightTitles: SideTitles(
                showTitles: true,
                getTitles: (value) {
                  return value%3==0?value.toInt().toString():'';
                },
              ),
            ),
            gridData: FlGridData(
              show: true,
              checkToShowHorizontalLine: (double value) {
                return value%3==0;
              },
              checkToShowVerticalLine: (double value) {
                return value%3==0;
              },
              drawVerticalLine: true,
              drawHorizontalLine: true,
              verticalInterval: 1,
              horizontalInterval: 1,
              // drawVerticalLine: true
            ),
          ),
        ),
      ),
    );
  }
}
