import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';

import 'package:mwf_app/service/color.dart';
import 'package:mwf_app/service/convert.dart';
import 'package:mwf_app/service/fontsize.dart';
import 'package:mwf_app/service/header.dart';
import 'package:mwf_app/service/loader.dart';
import 'package:mwf_app/service/screen.dart';
import 'package:mwf_app/service/shadow.dart';
import 'package:mwf_app/service/strings.dart';
import 'package:mwf_app/model/electric_shutdown.dart';
import 'package:mwf_app/home.dart';

class PowerFail extends StatefulWidget {
  @override
  _PowerFailState createState() => _PowerFailState();
}

class _PowerFailState extends State<PowerFail> {
  bool isLoading = false;
  GlobalKey<RefreshIndicatorState> refreshKey;
  Future _future;

  @override
  void initState() {
    super.initState();
    Header.currentPage = "";
    print("เหตุขัดข้องจากลูกค้า set7/powerFail_User.dart");
    _future = _getData();
    //loadData(); // ดึงข้อมูล
  }

  loadData() async {
    setState(() {
      isLoading = true;
    });
    try {
      final list = await ElectricProblemInfo
          .getDataFromCustomer(); // ไปเรียกฟังชั่นดึงข้อมูลจาก api
      setState(() {
        list.forEach((v) {
          final powerFailList = ElectricProblemInfo.fromJson(v);
          ElectricProblemInfo.data.add(powerFailList); // loop เก็บข้อมูล
          ElectricProblemInfo.data.sort(
            (a, b) => AppConvert.dateTimeThaiToEng(b.startdate).compareTo(
              AppConvert.dateTimeThaiToEng(a.startdate),
            ),
          );
        });
      });
      await new Future.delayed(const Duration(seconds: 1));
      setState(() {
        isLoading = false;
      });
    } catch (e) {
      setState(() {
        isLoading = false;
      });
      print(e);
    }
  }

  Future<List<ElectricProblemInfo>> _getData() async {
    try{
      final list = await ElectricProblemInfo
          .getDataFromCustomer(); // ไปเรียกฟังชั่นดึงข้อมูลจาก api
      setState(() {
        list.forEach((v) {
          final powerFailList = ElectricProblemInfo.fromJson(v);
          ElectricProblemInfo.data.add(powerFailList); // loop เก็บข้อมูล
          ElectricProblemInfo.data.sort(
            (a, b) => AppConvert.dateTimeThaiToEng(b.startdate).compareTo(
              AppConvert.dateTimeThaiToEng(a.startdate),
            ),
          );
        });
      });
    }catch(e){
      print(e);
    }
    return ElectricProblemInfo.data;
  }

  @override
  Widget build(BuildContext context) {
    Header.routes = HomePage();
    if (isLoading == true) {
      AppLoader.show();
    }
    if (isLoading == false) {
      AppLoader.hide();
    }
    double _width = MediaQuery.of(context).size.width;

    return Material(
      color: AppColors.bgColor,
      child: RefreshIndicator(
        key: refreshKey,
        onRefresh: () async {
          _getData();
          //loadData();
        },
        child: WillPopScope(
          onWillPop: () async {
            Get.offAll(Header.routes);
            return false;
          },
          child: Stack(
            children: <Widget>[
              Header.header2ListPage(context),
              Header.mainMenu(context),
              Container(
                width: _width,
                margin: EdgeInsets.only(
                  top: mediaQuery(context, 'h', 380),
                  left: mediaQuery(context, 'w', 60),
                  right: mediaQuery(context, 'w', 60),
                  bottom: mediaQuery(context, 'h', 30),
                ),
                child: Column(
                  children: <Widget>[
                    Container(
                      alignment: Alignment.center,
                      margin: EdgeInsets.only(
                        bottom: mediaQuery(context, 'h', 60),
                      ),
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: <Widget>[
                          Text(
                            AppStrings.home_powerFail,
                            style: TextStyle(
                              color: Color(0xFFB58E38),
                              fontSize: mediaQuery(
                                  context, 'h', AppFontSize.headText),
                            ),
                          ),
                        ],
                      ),
                    ),
                  ],
                ),
              ),
              Container(
                width: _width,
                height: mediaQuery(context, 'h', 1700),
                margin: EdgeInsets.only(
                  top: mediaQuery(context, 'h', 540),
                  left: mediaQuery(context, 'w', 60),
                  right: mediaQuery(context, 'w', 60),
                ),
                child: FutureBuilder(
                  future: _future,
                      builder: (BuildContext context, AsyncSnapshot snapshot) {
                        if (snapshot.data == null && 
                            snapshot.connectionState == ConnectionState.waiting || 
                            snapshot.connectionState == ConnectionState.none) {
                          return Container(
                            child: AppLoader.show(),
                          );
                        }else if(snapshot.connectionState == ConnectionState.done){
                          AppLoader.hide();
                          return ListView.builder(
                            shrinkWrap: true,
                            addAutomaticKeepAlives: true,
                            itemCount: snapshot.data.length,
                            itemBuilder: (BuildContext context, int index) {
                            return _buildContent(
                              context,
                              (index + 1).toString(),
                              ElectricProblemInfo.data[index].startdate,
                              ElectricProblemInfo.data[index].detail,
                              ElectricProblemInfo.data[index].customerPhone,
                              ElectricProblemInfo.data[index].customerName,
                            );
                            }
                          );
                          } else {
                          AppLoader.hide();
                          return ListView.builder(
                            shrinkWrap: true,
                            addAutomaticKeepAlives: true,
                            itemCount: snapshot.data.length,
                            itemBuilder: (BuildContext context, int index) {
                              return _buildContent(
                                context,
                                (index + 1).toString(),
                                ElectricProblemInfo.data[index].startdate,
                                ElectricProblemInfo.data[index].detail,
                                ElectricProblemInfo.data[index].customerPhone,
                                ElectricProblemInfo.data[index].customerName,
                              );
                            },
                          );
                        }
                      },
                    ),
                // child: SingleChildScrollView(
                //   child: Column(
                //     children:
                //         List.generate(ElectricProblemInfo.data.length, (index) {
                //       return _buildContent(
                //         context,
                //         (index + 1).toString(),
                //         ElectricProblemInfo.data[index].startdate,
                //         ElectricProblemInfo.data[index].detail,
                //         ElectricProblemInfo.data[index].customerPhone,
                //         ElectricProblemInfo.data[index].customerName,
                //       );
                //     }),
                //   ),
                // ),
              )
            ],
          ),
        ),
      ),
    );
  }
} //class

_buildContent(context, number, date, detail, user, company) {
  return Container(
    width: mediaQuery(context, 'w', 1005),
    padding: EdgeInsets.all(
      mediaQuery(context, 'h', 50),
    ),
    margin: EdgeInsets.only(
      bottom: mediaQuery(context, 'h', 40),
    ),
    decoration: BoxDecoration(
      borderRadius: new BorderRadius.all(
        Radius.circular(
          mediaQuery(context, 'h', 20),
        ),
      ),
      boxShadow: [
        appShadow(),
      ],
      color: Colors.white,
    ),
    child: Row(
      children: <Widget>[
        Container(
          width: mediaQuery(context, 'w', 780),
          child: Wrap(
            spacing: 5.0,
            runSpacing: 5.0,
            direction: Axis.vertical,
            children: <Widget>[
              Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: <Widget>[
                  Row(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: <Widget>[
                      Text(
                        'ลำดับ : ',
                        style: TextStyle(
                          color: AppColors.color_text,
                          fontSize: mediaQuery(context, 'h', 42),
                        ),
                      ),
                      Text(
                        number,
                        style: TextStyle(
                          color: AppColors.color_text,
                          fontSize: mediaQuery(context, 'h', 40),
                        ),
                      ),
                    ],
                  ),
                  // Row(
                  //   crossAxisAlignment: CrossAxisAlignment.start,
                  //   children: <Widget>[
                  //     Text(
                  //       'ชื่อบริษัท : ',
                  //       style: TextStyle(
                  //         color: AppColors.color_text,
                  //         fontSize: mediaQuery(context, 'h', 42),
                  //       ),
                  //     ),
                  //     Text(
                  //       company != null ? '$company' : '',
                  //       style: TextStyle(
                  //         color: AppColors.color_text,
                  //         fontSize: mediaQuery(context, 'h', 40),
                  //       ),
                  //     ),
                  //   ],
                  // ),
                  Row(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: <Widget>[
                      Text(
                        'วันที่ : ',
                        style: TextStyle(
                          color: AppColors.color_text,
                          fontSize: mediaQuery(context, 'h', 42),
                        ),
                      ),
                      Text(
                        date != null ? '$date น.' : '',
                        style: TextStyle(
                          color: AppColors.color_text,
                          fontSize: mediaQuery(context, 'h', 40),
                        ),
                      ),
                    ],
                  ),
                  Row(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: <Widget>[
                      Text(
                        'รายละเอียด : ',
                        style: TextStyle(
                          color: AppColors.color_text,
                          fontSize: mediaQuery(context, 'h', 42),
                        ),
                      ),
                      Text(
                        detail != null ? detail : '',
                        style: TextStyle(
                          color: AppColors.color_text,
                          fontSize: mediaQuery(context, 'h', 40),
                        ),
                      ),
                    ],
                  ),
                  Row(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: <Widget>[
                      Text(
                        'ผู้แจ้ง : ',
                        style: TextStyle(
                          color: AppColors.color_text,
                          fontSize: mediaQuery(context, 'h', 42),
                        ),
                      ),
                      Text(
                        user != null ? user : '',
                        style: TextStyle(
                          color: AppColors.color_text,
                          fontSize: mediaQuery(context, 'h', 40),
                        ),
                      ),
                    ],
                  ),
                ],
              ),
            ],
          ),
        ),
      ],
    ),
  );
}
//class
