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 'YSAddBodyData.dart';
import 'YSInputWidgetInfo.dart';

class YSWomanBody extends StatefulWidget {
  @override
  _YSWomanBodyState createState() => _YSWomanBodyState();
}

class _YSWomanBodyState extends State<YSWomanBody> {
  List weights = [];
  List weightArray = [];
  PageController _page = PageController();
  int index = 0;
  @override
  void initState() {
    for(int i =0;i<60;i++){
      weightArray.add({'week':i+1});
    }
   Future.delayed(Duration(seconds: 0)).then((value){
     _getWomanBodyData();
   });
    super.initState();
  }
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: SingleChildScrollView(
        child: Column(
          children: [
            Container(
              height: MediaQuery.of(context).padding.top+44,
              padding: EdgeInsets.only(left: 5,top: 20,right: 15),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  CupertinoButton(
                    padding: EdgeInsets.all(0),
                    child: Icon(Icons.keyboard_arrow_left,size: 30,color: Color(0xFF292929),),
                    onPressed: (){
                      Navigator.pop(context);
                    },
                  ),
                  Text('体重管理',style: TextStyle(fontSize: 16,color: Color(0xFF292929),fontWeight: FontWeight.w600),),
                  CupertinoButton(
                    padding: EdgeInsets.all(0),
                    child: Text('',style: TextStyle(fontSize: 14,color: Color(0xFFDB5278)),),//增重建议
                    onPressed: (){
                      return;
                      Navigator.of(context).push(
                        CupertinoPageRoute(
                          builder: (context){
                            return YSInputWidgetInfo();
                          }
                        )
                      );
                    },
                  ),
                ],
              ),
            ),
            Stack(
              children: [
                Container(
                  height: 150,
                  width: MediaQuery.of(context).size.width,
                  child: PageView(
                    controller: _page,
                    onPageChanged: (value){
                      index = value;
                    },
                    children: weightArray.map((e) {
                      return Stack(
                        children: [
                          GestureDetector(
                            onTap: (){
                              Navigator.of(context).push(
                                  CupertinoPageRoute(
                                      builder: (context){
                                        return YSAddBodyData(index: e['week'],);
                                      }
                                  )
                              ).then((value){
                                if(value!=null){
                                  _getWomanBodyData();
                                }
                              });
                            },
                            child: Container(
                              margin: EdgeInsets.only(top: 13,bottom: 13,left: 75,right: 75),
                              height: 124,
                              width: MediaQuery.of(context).size.width-150,
                              padding: EdgeInsets.all(15),
                              decoration: BoxDecoration(
                                borderRadius: BorderRadius.all(Radius.circular(20)),
                                color: Color(0xFFEB6E91),
                              ),
                              child: e['weight']!=null?Column(
                                crossAxisAlignment: CrossAxisAlignment.start,
                                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                children: [
                                  Text('孕 ${e['week']} 周',style: TextStyle(fontSize: 12,color: Colors.white),),
                                  RichText(
                                    text: TextSpan(
                                        style: TextStyle(fontSize: 34,color: Colors.white,fontWeight: FontWeight.w600),
                                        children: [
                                          TextSpan(text: '${e['weight']}'),
                                          TextSpan(text: 'kg',style: TextStyle(fontSize: 12,fontWeight: FontWeight.normal))
                                        ]
                                    ),
                                  ),
                                  Row(
                                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                    children: [
                                      Text('',style: TextStyle(fontSize: 12,color: Colors.white),),//已增重: 50.0kg
                                      Image(height: 20,width: 20,image: AssetImage('lib/images/update.png'),)
                                    ],
                                  )
                                ],
                              ):Column(
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children: [
                                  Text('孕 ${e['week']} 周',style: TextStyle(fontSize: 12,color: Colors.white),),
                                  Container(
                                    height: 70,
                                    alignment: Alignment.center,
                                    child: Icon(Icons.add,size: 60,color: Colors.white,),
                                  )
                                ],
                              ),
                            ),
                          ),
                        ],
                      );
                    }).toList(),
                  ),
                ),
                Container(
                  height: 150,
                  padding: EdgeInsets.only(left: 15,right: 15),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      GestureDetector(
                        child: Icon(Icons.keyboard_arrow_left,size: 30,color: Color(0xFF808080),),
                        onTap: (){
                          _page.jumpToPage(index-1);
                        },
                      ),
                      GestureDetector(
                        child: Icon(Icons.keyboard_arrow_right,size: 30,color: Color(0xFF808080),),
                        onTap: (){
                          _page.jumpToPage(index+1);
                        },
                      ),
                    ],
                  ),
                )
              ],
            ),
            Text('',style: TextStyle(fontSize: 11,color: Color(0xFF808080)),),//孕前体重: 0.0kg
            Container(
              margin: EdgeInsets.only(top: 5,bottom: 15),
              child: Text('',style: TextStyle(fontSize: 11,color: Color(0xFF4D4D4D)),),//本周体重范围: 0.0kg
            ),
            Container(
              width: MediaQuery.of(context).size.width,
              height: 1.5,
              child: Image.asset('lib/images/line.png'),
            ),
            Container(
              child: Text('孕期体重增长曲线',style: TextStyle(fontSize: 14,color: Color(0xFF292929),fontWeight: FontWeight.w600),),
              margin: EdgeInsets.all(15),
            ),
            Container(
              padding: EdgeInsets.only(left: 50,right: 50),
              margin: EdgeInsets.only(bottom: 10),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Container(
                    child: Row(
                      children: [
                        // Image(height: 15,width: 15,image: AssetImage('lib/images/range.png'),),
                        // Text(' 增重范围',style: TextStyle(fontSize: 11,color: Color(0xFF292929)),),
                      ],
                    ),
                  ),
                  Container(
                    child: Row(
                      children: [
                        Image(height: 15,width: 15,image: AssetImage('lib/images/max.png'),),
                        Text(' 我的体重(kg)',style: TextStyle(fontSize: 11,color: Color(0xFF292929)),),
                      ],
                    ),
                  ),
                  Container(
                    child: Row(
                      children: [
                        // Image(height: 15,width: 15,image: AssetImage('lib/images/min.png'),),
                        // Text(' 过重/过轻',style: TextStyle(fontSize: 11,color: Color(0xFF292929)),),
                      ],
                    ),
                  )
                ],
              ),
            ),
            Container(
              margin: EdgeInsets.only(top: 5),
              child: weights.length>0?LineChartSample7(weight: weights,):Container(),
            )
          ],
        ),
      ),
    );
  }

  _getWomanBodyData() async{
    Map dict = await ysRequestHttp(context, requestType.post, 'phase/gestationList', {'type':'weight '});
    if(dict!=null){
      weights = dict['data']['weights'];
      // weights.sort((a, b) => (b.week).compareTo(a.week));
      for(int i=0;i<weights.length-1;i++){
        for(int j=0;j<weights.length-1-i;j++){
          if(weights[j]['week']>weights[j+1]['week']){
            Map temp = weights[j];
            weights[j] = weights[j+1];
            weights[j+1] = temp;
          }
        }
      }
      weights.forEach((element) {
        int index = weightArray.indexWhere((elementSub) => elementSub['week']==element['week']);
        weightArray[index] = element;
      });
      // LogUtil.d(weights);
      setState(() {});
    }
  }
}

class LineChartSample7 extends StatelessWidget {
  final List weight;
  const LineChartSample7({Key key, this.weight}) : super(key: key);
  @override
  Widget build(BuildContext context) {
    return SingleChildScrollView(
      padding: EdgeInsets.only(top: 5,left: 10,right: 10),
      scrollDirection: Axis.horizontal,
      child: SizedBox(
        width: (MediaQuery.of(context).size.width-40)/8*50,
        height: MediaQuery.of(context).size.height/100*50,
        child: LineChart(
          LineChartData(
            // borderData: FlBorderData(
            //   border: Border(
            //     left: BorderSide(width: 1,color: Colors.black),
            //     right: BorderSide(width: 1,color: Colors.black),
            //     bottom: BorderSide(width: 1,color: Colors.black)
            //   )
            // ),
            lineTouchData: LineTouchData(enabled: false),
            lineBarsData: [
              LineChartBarData(
                spots: weight.map((f) {
                  return FlSpot(
                    double.parse('${f['week']}'),
                    double.parse('${f['weight']}')
                  );
                }).toList(),
                isCurved: true,
                barWidth: 2,
                colors: [
                  Colors.green,
                ],
                dotData: FlDotData(
                  show: true,
                ),
              ),
            ],
            titlesData: FlTitlesData(
              bottomTitles: SideTitles(
                showTitles: true,
                getTitles: (value) {
                  return '第'+value.toInt().toString()+'周';
                },
              ),
              leftTitles: SideTitles(
                showTitles: true,
                getTitles: (value) {
                  return value%10==0?value.toInt().toString()+'kg':'';
                },
              ),
              rightTitles: SideTitles(
                showTitles: true,
                getTitles: (value) {
                  return value%10==0?value.toInt().toString()+'kg':'';
                },
              ),
            ),
            maxY: 120,
            maxX: 50,
            minX: 1,
            minY: 0,
            gridData: FlGridData(
              show: true,
              checkToShowHorizontalLine: (double value) {
                return value%10==0;
              },
              checkToShowVerticalLine: (double value) {
                return true;
              },
              drawVerticalLine: true,
              drawHorizontalLine: true,
              verticalInterval: 1,
              horizontalInterval: 1,
            ),
          ),
        ),
      ),
    );
  }
}
