import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:font_awesome_flutter/font_awesome_flutter.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/notification_count.dart';
import 'package:mwf_app/service/screen.dart';
import 'package:mwf_app/service/shadow.dart';
import 'package:mwf_app/service/url.dart';
import 'package:mwf_app/home.dart';
import 'package:mwf_app/model/PackageRequest_model.dart';
import 'package:mwf_app/model/package.dart';
import 'package:mwf_app/set8/list_request_additional.dart';
import 'package:need_resume/need_resume.dart';

// Package model
class RequestAdditional extends StatefulWidget {
  @override
  _RequestAdditionalState createState() => _RequestAdditionalState();
}

class _RequestAdditionalState extends ResumableState<RequestAdditional> {
  bool isLoading = false;
  GlobalKey<RefreshIndicatorState> refreshKey;
  Future _future;

  @override
  void onReady() {
    Header.routes = HomePage();
    Header.currentPage = "";
    NotificationCount.packageRequestCount = 0;
    _future = _getData();
    // isLoading = true;
    // wait();
    print('Screen is ready! : RequestAdditional : listคำขอใช้บริการเสริม');
  }

  @override
  void onResume() {
    // Implement your code inside here
    //loadData();
    print('Screen is resumed!');
  }

  @override
  void onPause() {
    // Implement your code inside here
    print('Screen is paused!');
  }
  
  wait() async {
    await Future.delayed(Duration(seconds: 1));
    setState(() {
      isLoading = false;    
    });
  }

  List<dynamic> requestAdditionalList =
      Package.requestAdditionalList; // รายการ คำขอใช้บริการเสริม

  loadData() async {
    setState(() {
      isLoading = true;
    });
    await Future.delayed(const Duration(milliseconds: 2000));
    try {
      final listPackage = await PackageRequest.getDataList();
      setState(() {
        listPackage.forEach((v) {
          final questionList = PackageRequest.fromJson(v);
          PackageRequest.data.add(questionList);
          PackageRequest.data.sort((a, b) =>
              AppConvert.dateTimeThaiToEng(b.strCreateDate)
                  .compareTo(AppConvert.dateTimeThaiToEng(a.strCreateDate)));
        });
        isLoading = false;
      });
    } catch (e) {
      setState(() {
        isLoading = false;
      });
      print(e);
    }
  }

  Future<List<PackageRequest>> _getData() async {
    try{
      final list = await PackageRequest.getDataList();
      setState(() {
        list.forEach((v) {
          final list = PackageRequest.fromJson(v);
          PackageRequest.data.add(list); // loop เก็บข้อมูล
          PackageRequest.data.sort((a, b) =>
                AppConvert.dateTimeThaiToEng(b.strCreateDate)
                    .compareTo(AppConvert.dateTimeThaiToEng(a.strCreateDate)));
        });
      });
    }catch(e){
      print(e);
    }
    return PackageRequest.data;
  }

  loadRequestAdditionalList() async {
    var res = await Package.getData();
    Package.requestAdditionalList = res['Package'];
  }

  @override
  Widget build(BuildContext context) {
    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 {
          loadData();
        },
        child: WillPopScope(
          onWillPop: () async {
            Get.offAll(Header.routes);
            return false;
          },
          child: Stack(
            children: <Widget>[
              Header.header2ListPage(context),
              Header.mainMenu(context),
              Container(
                width: _width,
                height: mediaQuery(context, 'h', 1908),
                margin: EdgeInsets.only(
                  top: mediaQuery(context, 'h', 355),
                  left: mediaQuery(context, 'w', 60),
                  right: mediaQuery(context, 'w', 60),
                ),
                child: Column(
                  children: <Widget>[
                    Container(
                      margin: EdgeInsets.only(
                        top: mediaQuery(context, 'h', 15),
                        bottom: mediaQuery(context, 'h', 30),
                      ),
                      child: Text(
                        'คำขอใช้บริการเสริม',
                        textAlign: TextAlign.center,
                        style: TextStyle(
                          color: Color(0xFFB58E38),
                          fontSize:
                              mediaQuery(context, 'h', AppFontSize.headText),
                        ),
                      ),
                    ),
                    Container(
                      width: _width,
                      height: mediaQuery(context, 'h', 1750),
                      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.hasError){
                                  AppLoader.hide();
                                  return Center(
                                    child: Text("เกิดข้อผิดพลาดในการโหลดข้อมูล", 
                                      style: TextStyle(fontSize: mediaQuery(context, 'h', 40)),
                                  ));
                                }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 ContentBuilder(
                                        ca: PackageRequest.data[index].ca,
                                        pId: PackageRequest.data[index].pId,
                                        prId: PackageRequest.data[index].prId,
                                        packageName: PackageRequest.data[index].pName,
                                        process: PackageRequest.data[index].prStatusName,
                                        packageID: PackageRequest.data[index].pCode.trim(),
                                        customerName: PackageRequest.data[index].customerName,
                                        customerAddress: PackageRequest.data[index].customerAddress,
                                      );
                                    }
                                  );
                                } else {
                                  AppLoader.hide();
                                  return ListView.builder(
                                    shrinkWrap: true,
                                    addAutomaticKeepAlives: true,
                                    itemCount: snapshot.data.length,
                                    itemBuilder: (BuildContext context, int index) {
                                      return ContentBuilder(
                                        ca: PackageRequest.data[index].ca,
                                        pId: PackageRequest.data[index].pId,
                                        prId: PackageRequest.data[index].prId,
                                        packageName: PackageRequest.data[index].pName,
                                        process: PackageRequest.data[index].prStatusName,
                                        packageID: PackageRequest.data[index].pCode.trim(),
                                        customerName: PackageRequest.data[index].customerName,
                                        customerAddress: PackageRequest.data[index].customerAddress,
                                      );



                                      // return _buildContent(
                                      //   context,
                                      //   PackageRequest.data[index].pCode.trim(),
                                      //   PackageRequest.data[index].pName,
                                      //   PackageRequest.data[index].prStatusName,
                                      //   PackageRequest.data[index].ca,
                                      //   PackageRequest.data[index].customerName,
                                      //   PackageRequest.data[index].customerAddress,
                                      //   PackageRequest.data[index].prId,
                                      //   PackageRequest.data[index].pId,
                                      // );
                                    },
                                  );
                                }
                              },
                            ),                        
                    )


                    // Container(
                    //     width: _width,
                    //     height: mediaQuery(context, 'h', 1750),
                    //     child: 
                    //     SingleChildScrollView(
                    //     child: Column(
                    //       children:
                    //         List.generate(PackageRequest.data.length, (index) {
                    //         return _buildContent(
                    //           context,
                    //           PackageRequest.data[index].pCode.trim(),
                    //           PackageRequest.data[index].pName,
                    //           PackageRequest.data[index].prStatusName,
                    //           PackageRequest.data[index].ca,
                    //           PackageRequest.data[index].customerName,
                    //           PackageRequest.data[index].customerAddress,
                    //           PackageRequest.data[index].prId,
                    //           PackageRequest.data[index].pId,
                    //         );
                    //       }),
                    //     ),
                    //   ),
                    // )
                  ],
                )
              ),
            ],
          ),
        ),
      ),
    );
  }

  _buildContent(
      context,
      String packageID,
      String packageName,
      String process,
      String ca,
      String customerName,
      String customerAddress,
      String prId,
      String pId) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.center,
      children: <Widget>[
        Container(
          width: mediaQuery(context, 'w', 1450),
          decoration: BoxDecoration(
            borderRadius: BorderRadius.all(
              Radius.circular(
                mediaQuery(context, 'h', 60),
              ),
            ),
            color: Colors.white,
          ),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: <Widget>[
              Container(
                width: mediaQuery(context, 'w', 1022),
                height: mediaQuery(context, 'h', 190),
                // height: mediaQuery(context, 'h', 164),
                decoration: BoxDecoration(
                  borderRadius: BorderRadius.all(
                    Radius.circular(
                      mediaQuery(context, 'h', 140),
                    ),
                  ),
                  boxShadow: [
                    appShadow(),
                  ],
                  color: Colors.white,
                ),
                child: Row(
                  children: <Widget>[
                    Container(
                      margin: EdgeInsets.only(top: 6.0, bottom: 6, left: 4),
                      width: mediaQuery(context, 'w', 250),
                      height: mediaQuery(context, 'h', 150),
                      padding: EdgeInsets.all(
                        mediaQuery(context, 'h', 35),
                      ),
                      decoration: BoxDecoration(
                        borderRadius: BorderRadius.all(
                          Radius.circular(
                            mediaQuery(context, 'h', 90),
                          ),
                        ),
                        boxShadow: [
                          appShadow(),
                        ],
                        color: AppColors.color_gold,
                      ),
                      child: Text(
                        '$packageID',
                        overflow: TextOverflow.ellipsis,
                        textAlign: TextAlign.center,
                        style: TextStyle(
                          fontSize: mediaQuery(context, 'h', 30),
                          color: Colors.white,
                          fontWeight: FontWeight.bold,
                        ),
                      ),
                    ),
                    SizedBox(
                      width: 4,
                    ),
                    Container(
                      width: mediaQuery(context, 'w', 300),
                      child: Text(
                        '$packageName',
                        textAlign: TextAlign.start,
                        style: TextStyle(
                          fontSize: mediaQuery(context, 'h', 36),
                          color: Color(0xFF383838),
                        ),
                      ),
                    ),
                    Container(
                      width: mediaQuery(context, 'w', 2),
                      height: mediaQuery(context, 'h', 100),
                      color: AppColors.color_gold,
                    ),
                    Container(
                      width: mediaQuery(context, 'h', 280),
                      padding: EdgeInsets.only(
                        left: mediaQuery(context, 'w', 20),
                      ),
                      child: Column(
                        mainAxisAlignment: MainAxisAlignment.center,
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: <Widget>[
                          Text(
                            'สถานะ',
                            textAlign: TextAlign.center,
                            style: TextStyle(
                              fontSize: mediaQuery(context, 'h', 36),
                              color: Color(0xFF383838),
                            ),
                          ),
                          Text(
                            '$process',
                            textAlign: TextAlign.start,
                            style: TextStyle(
                              fontSize: mediaQuery(context, 'h', 36),
                              color: AppColors.color_gold,
                            ),
                          ),
                        ],
                      ),
                    ),
                    Container(
                      width: mediaQuery(context, 'w', 3),
                      height: mediaQuery(context, 'h', 100),
                      color: AppColors.color_gold,
                    ),
                    GestureDetector(
                      onTap: () {
                        AppUrl.PR_Id = prId;
                        AppUrl.P_Id = pId;
                        AppUrl.CA = ca;
                        print("On tabbbbbb");
                        push(
                          context,
                          MaterialPageRoute(
                              builder: (context) => ListRequestAdditional()),
                        );
                      },
                      child: Container(
                        width: mediaQuery(context, 'w', 150),
                        height: mediaQuery(context, 'h', 120),
                        child: Icon(
                          FontAwesomeIcons.pencilAlt,
                          size: mediaQuery(context, 'h', 56),
                          color: AppColors.color,
                        ),
                      ),
                    ),
                  ],
                ),
              ),
              Container(
                padding: EdgeInsets.all(
                  mediaQuery(context, 'h', 60),
                ),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: <Widget>[
                    Text(
                      'CA : $ca',
                      style: TextStyle(
                        fontSize: mediaQuery(context, 'h', 42),
                        color: AppColors.color_text,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                    Text(
                      '$customerName',
                      style: TextStyle(
                        fontSize: mediaQuery(context, 'h', 42),
                        color: AppColors.color_text,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                    Text(
                      '$customerAddress',
                      style: TextStyle(
                        fontSize: mediaQuery(context, 'h', 42),
                        color: Color(0xFF8B939A),
                      ),
                    ),
                  ],
                ),
              )
            ],
          ),
        ),
        SizedBox(
          height: mediaQuery(context, 'h', 60),
        ),
      ],
    );
  }
} //class

class ContentBuilder extends StatefulWidget {
  ContentBuilder({
    this.packageID,
    this.packageName,
    this.process,
    this.ca,
    this.customerName,
    this.customerAddress,
    this.prId,
    this.pId
  });

  final String packageID;
  final String packageName;
  final String process;
  final String ca;
  final String customerName;
  final String customerAddress;
  final String prId;
  final String pId;

  @override
  _ContentBuilderState createState() => _ContentBuilderState(
    this.packageID,
    this.packageName,
    this.process,
    this.ca,
    this.customerName,
    this.customerAddress,
    this.prId,
    this.pId
  );
}

class _ContentBuilderState extends ResumableState<ContentBuilder>
with  AutomaticKeepAliveClientMixin<ContentBuilder> {
  _ContentBuilderState(
    this.packageID,
    this.packageName,
    this.process,
    this.ca,
    this.customerName,
    this.customerAddress,
    this.prId,
    this.pId
  );

  final String packageID;
  final String packageName;
  final String process;
  final String ca;
  final String customerName;
  final String customerAddress;
  final String prId;
  final String pId;


  @override
  Widget build(BuildContext context) {
    super.build(context);
    return Column(
      crossAxisAlignment: CrossAxisAlignment.center,
      children: <Widget>[
        Container(
          width: mediaQuery(context, 'w', 1450),
          decoration: BoxDecoration(
            borderRadius: BorderRadius.all(
              Radius.circular(
                mediaQuery(context, 'h', 60),
              ),
            ),
            color: Colors.white,
          ),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: <Widget>[
              Container(
                width: mediaQuery(context, 'w', 1022),
                height: mediaQuery(context, 'h', 190),
                // height: mediaQuery(context, 'h', 164),
                decoration: BoxDecoration(
                  borderRadius: BorderRadius.all(
                    Radius.circular(
                      mediaQuery(context, 'h', 140),
                    ),
                  ),
                  boxShadow: [
                    appShadow(),
                  ],
                  color: Colors.white,
                ),
                child: Row(
                  children: <Widget>[
                    Container(
                      margin: EdgeInsets.only(top: 6.0, bottom: 6, left: 4),
                      width: mediaQuery(context, 'w', 250),
                      height: mediaQuery(context, 'h', 150),
                      padding: EdgeInsets.all(
                        mediaQuery(context, 'h', 35),
                      ),
                      decoration: BoxDecoration(
                        borderRadius: BorderRadius.all(
                          Radius.circular(
                            mediaQuery(context, 'h', 90),
                          ),
                        ),
                        boxShadow: [
                          appShadow(),
                        ],
                        color: AppColors.color_gold,
                      ),
                      child: Text(
                        '$packageID',
                        overflow: TextOverflow.ellipsis,
                        textAlign: TextAlign.center,
                        style: TextStyle(
                          fontSize: mediaQuery(context, 'h', 30),
                          color: Colors.white,
                          fontWeight: FontWeight.bold,
                        ),
                      ),
                    ),
                    SizedBox(
                      width: 4,
                    ),
                    Container(
                      width: mediaQuery(context, 'w', 300),
                      child: Text(
                        '$packageName',
                        textAlign: TextAlign.start,
                        style: TextStyle(
                          fontSize: mediaQuery(context, 'h', 36),
                          color: Color(0xFF383838),
                        ),
                      ),
                    ),
                    Container(
                      width: mediaQuery(context, 'w', 2),
                      height: mediaQuery(context, 'h', 100),
                      color: AppColors.color_gold,
                    ),
                    Container(
                      width: mediaQuery(context, 'h', 280),
                      padding: EdgeInsets.only(
                        left: mediaQuery(context, 'w', 20),
                      ),
                      child: Column(
                        mainAxisAlignment: MainAxisAlignment.center,
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: <Widget>[
                          Text(
                            'สถานะ',
                            textAlign: TextAlign.center,
                            style: TextStyle(
                              fontSize: mediaQuery(context, 'h', 36),
                              color: Color(0xFF383838),
                            ),
                          ),
                          Text(
                            '$process',
                            textAlign: TextAlign.start,
                            style: TextStyle(
                              fontSize: mediaQuery(context, 'h', 36),
                              color: AppColors.color_gold,
                            ),
                          ),
                        ],
                      ),
                    ),
                    Container(
                      width: mediaQuery(context, 'w', 3),
                      height: mediaQuery(context, 'h', 100),
                      color: AppColors.color_gold,
                    ),
                    GestureDetector(
                      onTap: () {
                        AppUrl.PR_Id = prId;
                        AppUrl.P_Id = pId;
                        AppUrl.CA = ca;
                        print("On tabbbbbb");
                        push(
                          context,
                          MaterialPageRoute(
                              builder: (context) => ListRequestAdditional()),
                        );
                      },
                      child: Container(
                        width: mediaQuery(context, 'w', 150),
                        height: mediaQuery(context, 'h', 120),
                        child: Icon(
                          FontAwesomeIcons.pencilAlt,
                          size: mediaQuery(context, 'h', 56),
                          color: AppColors.color,
                        ),
                      ),
                    ),
                  ],
                ),
              ),
              Container(
                padding: EdgeInsets.all(
                  mediaQuery(context, 'h', 60),
                ),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: <Widget>[
                    Text(
                      'CA : $ca',
                      style: TextStyle(
                        fontSize: mediaQuery(context, 'h', 42),
                        color: AppColors.color_text,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                    Text(
                      '$customerName',
                      style: TextStyle(
                        fontSize: mediaQuery(context, 'h', 42),
                        color: AppColors.color_text,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                    Text(
                      '$customerAddress',
                      style: TextStyle(
                        fontSize: mediaQuery(context, 'h', 42),
                        color: Color(0xFF8B939A),
                      ),
                    ),
                  ],
                ),
              )
            ],
          ),
        ),
        SizedBox(
          height: mediaQuery(context, 'h', 60),
        ),
      ],
    );
  }

  @override
  bool get wantKeepAlive => true;
}
