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/model/Permission_model.dart';
import 'package:mwf_app/service/alert.dart';
import 'package:mwf_app/service/color.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/service/style.dart';
import 'package:mwf_app/service/url.dart';
import 'package:mwf_app/model/PackageRequest_model.dart';
import 'package:mwf_app/set1/serve_customers.dart';
import 'package:mwf_app/set4/list_additional.dart';
import 'package:mwf_app/set8/list_request_additional.dart';
import 'package:need_resume/need_resume.dart';

class OfferAdditionalList extends StatefulWidget {
  OfferAdditionalList();
  @override
  _OfferAdditionalListState createState() => _OfferAdditionalListState();
}

class _OfferAdditionalListState extends ResumableState<OfferAdditionalList> {
  _OfferAdditionalListState();
  Future _future;
  String isView = '';
  String isAdd = '';
  String isUpdate = '';
  String isDelete = '';
  String isAll = '';
  bool isLoading = false;
  @override
  void onReady() {
    Header.routes = ServeCustomer();
    setPermission();
    print('OfferAdditionalList : Screen is ready!');
    print('Permission for this menu ...');
    //loadData();
    _future = _getData();
  }

  setPermission() async {
    var data = await Permission.getResource("menuServicesUserData");
    isAdd = data.add;
    isUpdate = data.edit;
    isDelete = data.delete;
    isAll = data.all;
    print("isView -->" + isView);
    print("isAdd -->" + isAdd);
    print("isUpdate -->" + isUpdate);
    print("isDelete -->" + isDelete);
    print("isAll -->" + isAll);
  }

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

  @override
  void onPause() {
    // Implement your code inside here
    print('OfferAdditionalList : Screen is paused!');
  }

  Future<void> loadData() async {
    print('_OfferAdditionalListState : loadData');
    try {
      setState(() {
        isLoading = true;
      });
      final list =
          await PackageRequest.getData(); // ไปเรียกฟังชั่นดึงข้อมูลจาก api
      setState(() {
        list.forEach((v) {
          final list = PackageRequest.fromJson(v);
          PackageRequest.data.add(list); // loop เก็บข้อมูล
        });
      });
      
      isLoading = false;
      
    } catch (e) {
      setState(() {
        isLoading = false;
      });
      print(e);
    }
  }

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

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

    return Material(
      color: AppColors.bgColor,
      child: WillPopScope(
        onWillPop: () async {
          Get.offAll(Header.routes);
          return false;
        },
        child: Stack(
          children: <Widget>[
            Header.headerListPage(context),
            Header.mainMenu(context),
            Container(
              margin: EdgeInsets.only(
                top: mediaQuery(context, 'h', 950),
              ),
              child: Column(
                children: <Widget>[
                  Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: <Widget>[
                      Text(
                        AppStrings.offerAdditional,
                        style: AppStyle.headTextStyle(context),
                      ),
                    ],
                  ),
                  Padding(
                    padding: EdgeInsets.only(
                      top: mediaQuery(context, 'h', 30),
                      right: mediaQuery(context, 'w', 60),
                    ),
                    child: isAdd == "1" || isAdd == '' || isAll == "1"
                        ? GestureDetector(
                            onTap: () {
                              push(
                                context,
                                MaterialPageRoute(
                                    builder: (context) => ListAdditional()),
                              );
                            },
                            child: Row(
                              mainAxisAlignment: MainAxisAlignment.end,
                              children: <Widget>[
                                Icon(
                                  Icons.add_circle_outline,
                                  color: AppColors.color,
                                  size: 25,
                                ),
                                SizedBox(
                                  width: 5,
                                ),
                                Text(
                                  AppStrings.AddAdditionalServices,
                                  style: TextStyle(
                                    color: AppColors.color,
                                    fontSize: mediaQuery(context, "h", 44),
                                  ),
                                )
                              ],
                            ),
                          )
                        : null,
                  ),
                ],
              ),
            ),
            Container(
              width: _width,
              height: mediaQuery(context, 'h', 1000),
              margin: EdgeInsets.only(
                top: mediaQuery(context, 'h', 1200),
              ),

              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(
                              isAll: isAll,
                              isDelete: isDelete,
                              isUpdate: isUpdate,
                              ca: PackageRequest.data[index].ca,
                              pId: PackageRequest.data[index].pId,
                              name: PackageRequest.data[index].pName,
                              pCode: PackageRequest.data[index].pCode,
                              detail: PackageRequest.data[index].pDetail,
                              status: PackageRequest.data[index].prStatusType,
                              packageOptionID: PackageRequest.data[index].prId,
                              statusName: PackageRequest.data[index].prStatusName,
                            );


                            // return _buildRow(
                            //   context,
                            //   PackageRequest.data[index].prId,
                            //   PackageRequest.data[index].pId,
                            //   PackageRequest.data[index].pId,
                            //   PackageRequest.data[index].pName,
                            //   PackageRequest.data[index].pDetail,
                            //   PackageRequest.data[index].prStatusType,
                            //   PackageRequest.data[index].prStatusName,
                            //   PackageRequest.data[index].pCode,
                            //   PackageRequest.data[index].ca,
                            // );
                          },
                        );
                      } else {
                        return ListView.builder(
                          shrinkWrap: true,
                          addAutomaticKeepAlives: true,
                          itemCount: snapshot.data.length,
                          itemBuilder: (BuildContext context, int index) {
                            return ContentBuilder(
                              isAll: isAll,
                              isDelete: isDelete,
                              isUpdate: isUpdate,
                              ca: PackageRequest.data[index].ca,
                              pId: PackageRequest.data[index].pId,
                              name: PackageRequest.data[index].pName,
                              pCode: PackageRequest.data[index].pCode,
                              detail: PackageRequest.data[index].pDetail,
                              status: PackageRequest.data[index].prStatusType,
                              packageOptionID: PackageRequest.data[index].prId,
                              statusName: PackageRequest.data[index].prStatusName,
                            );
                          },
                        );
                      }
                    },
                  ),




              // child: SingleChildScrollView(
              //   child: Column(
              //     children: List.generate(PackageRequest.data.length, (index) {
              //       return _buildRow(
              //         context,
              //         PackageRequest.data[index].prId,
              //         PackageRequest.data[index].pId,
              //         PackageRequest.data[index].pId,
              //         PackageRequest.data[index].pName,
              //         PackageRequest.data[index].pDetail,
              //         PackageRequest.data[index].prStatusType,
              //         PackageRequest.data[index].prStatusName,
              //         PackageRequest.data[index].pCode,
              //         PackageRequest.data[index].ca,
              //       );
              //     }),
              //   ),
              // ),
            ),
          ],
        ),
      ),
    );
  }

  _buildSizeBox(context) {
    return SizedBox(
      height: mediaQuery(context, "h", 40),
    );
  }

  _buildRow(context, packageOptionID, pId, id, name, detail, status, statusName,
      pCode, ca) {
//    1 ขอใช้บริการ
//    2 ระหว่างดำเนินการ
//    3 ดำเนินการจบแล้ว
    var textStatus = statusName;
    dynamic icon;
    if (status == 1) {
      textStatus = "ขอใช้บริการ";
      icon = isDelete == "1" || isDelete == '' || isAll == "1"
          ? GestureDetector(
              onTap: () async {
                print("ลบ");

                bool chk =
                    await alertConfirm(context, "แจ้งเตือน", "ยืนยันการลบ");
                if (chk) {
                  PackageRequest.deleteData(context, packageOptionID)
                      .then((res) {
                    loadData();
                  });
                }
              },
              child: Icon(
                FontAwesomeIcons.trashAlt,
                color: AppColors.color_gold,
              ),
            )
          : null;
    } else if (status == 2) {
      textStatus = "ระหว่างดำเนินการ";
      icon = isUpdate == "1" || isUpdate == '' || isAll == "1"
          ? GestureDetector(
              onTap: () {
                // push(
                //   context,
                //   MaterialPageRoute(builder: (context) => OfferAdditional(packageOptionID, id, pId, name, status, textStatus, detail)),
                // );

                AppUrl.PR_Id = packageOptionID;
                AppUrl.P_Id = pId;
                AppUrl.CA = ca;
                push(
                  context,
                  MaterialPageRoute(
                      builder: (context) => ListRequestAdditional()),
                );
              },
              child: Icon(
                FontAwesomeIcons.pencilAlt,
                color: AppColors.color,
              ),
            )
          : null;
    } else if (status == 3) {
      textStatus = "ดำเนินการจบแล้ว";
      icon = Icon(
        FontAwesomeIcons.checkCircle,
        color: Colors.grey,
      );
    }

    return Column(
      children: <Widget>[
        Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[
                Container(
                  width: mediaQuery(context, 'w', 1005),
                  height: mediaQuery(context, 'h', 150),
                  decoration: BoxDecoration(
                    borderRadius: new BorderRadius.all(
                      Radius.circular(
                        mediaQuery(context, 'h', 140),
                      ),
                    ),
                    boxShadow: [
                      BoxShadow(
                        offset: Offset(2.0, 2.0),
                        blurRadius: 10.0,
                        color: Color(0xFF000000).withOpacity(0.10),
                      ),
                    ],
                    color: Colors.white,
                  ),
                  child: Row(
                    children: <Widget>[
                      Container(
                        width: mediaQuery(context, 'w', 230),
                        height: mediaQuery(context, 'h', 150),
                        padding: EdgeInsets.all(
                          mediaQuery(context, 'h', 20),
                        ),
                        decoration: BoxDecoration(
                          borderRadius: new BorderRadius.all(
                            Radius.circular(
                              mediaQuery(context, 'h', 70),
                            ),
                          ),
                          boxShadow: [
                            appShadow(),
                          ],
                          color: AppColors.color_gold,
                        ),
                        child: Text(
                          pCode,
                          textAlign: TextAlign.center,
                          style: TextStyle(
                            fontSize: mediaQuery(context, 'h', 42),
                            color: Colors.white,
                            fontWeight: FontWeight.bold,
                          ),
                        ),
                      ),
                      Container(
                        width: mediaQuery(context, 'h', 400),
                        child: Column(
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: <Widget>[
                            Flexible(
                              child: Text(
                                name,
                                textAlign: TextAlign.center,
                                style: TextStyle(
                                  fontSize: mediaQuery(context, 'h', 40),
                                  color: Color(0xFF383838),
                                ),
                              ),
                            ),
                          ],
                        ),
                      ),
                      Container(
                        width: mediaQuery(context, 'w', 2),
                        height: mediaQuery(context, 'h', 100),
                        color: AppColors.color_gold,
                      ),
                      Container(
                        width: mediaQuery(context, 'h', 310),
                        padding: EdgeInsets.only(
                          left: mediaQuery(context, 'w', 36),
                        ),
                        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(
                              textStatus,
                              textAlign: TextAlign.center,
                              style: TextStyle(
                                fontSize: mediaQuery(context, 'h', 36),
                                color: AppColors.color_gold,
                              ),
                            ),
                          ],
                        ),
                      ),
                      Container(
                        width: mediaQuery(context, 'w', 2),
                        height: mediaQuery(context, 'h', 100),
                        color: isUpdate == 1.toString() ||
                                isUpdate == '' ||
                                isAll == 1.toString()
                            ? AppColors.color_gold
                            : null,
                      ),
                      Container(
                        alignment: Alignment.center,
                        width: mediaQuery(context, 'w', 118),
                        child: icon,
                      ),
                    ],
                  ),
                ),
              ],
            ),
          ],
        ),
        _buildSizeBox(context),
      ],
    );
  }
} //class

class ContentBuilder extends StatefulWidget {
  ContentBuilder({
    this.packageOptionID, this.pId, this.name, this.detail, this.status, this.statusName, this.pCode, this.ca,
     this.isUpdate,
     this.isAll,
     this.isDelete,
  });
  
  final String packageOptionID;
  final String name;
  final String ca;
  final String detail;
  final int status;
  final String statusName;
  final String pId;
  final String pCode;
  final String isUpdate;
  final String isAll;
  final String isDelete;

  @override
  _ContentBuilderState createState() => _ContentBuilderState(
    this.packageOptionID, this.pId, this.name, this.detail, this.status, this.statusName, this.pCode, this.ca,
    this.isUpdate,
    this.isAll,
    this.isDelete,
  );
}

class _ContentBuilderState extends ResumableState<ContentBuilder>
with  AutomaticKeepAliveClientMixin<ContentBuilder> {
  _ContentBuilderState(
    this.packageOptionID, this.pId, this.name, this.detail, this.status, this.statusName, this.pCode, this.ca,
    this.isUpdate,
    this.isAll,
    this.isDelete,
  );

  final String packageOptionID;
  final String name;
  final String ca;
  final String detail;
  final int status;
  final String statusName;
  final String pId;
  final String pCode;
  final String isUpdate;
  final String isAll;
  final String isDelete;


  @override
  Widget build(BuildContext context) {
    super.build(context);
    var textStatus = statusName;
    dynamic icon;
    if (status == 1) {
      textStatus = "ขอใช้บริการ";
      icon = isDelete == "1" || isDelete == '' || isAll == "1"
          ? GestureDetector(
              onTap: () async {
                print("ลบ");

                bool chk =
                    await alertConfirm(context, "แจ้งเตือน", "ยืนยันการลบ");
                if (chk) {
                  PackageRequest.deleteData(context, packageOptionID)
                      .then((res) {
                    Get.offAll(OfferAdditionalList());
                  });
                }
              },
              child: Icon(
                FontAwesomeIcons.trashAlt,
                color: AppColors.color_gold,
              ),
            )
          : null;
    } else if (status == 2) {
      textStatus = "ระหว่างดำเนินการ";
      icon = isUpdate == "1" || isUpdate == '' || isAll == "1"
          ? GestureDetector(
              onTap: () {
                // push(
                //   context,
                //   MaterialPageRoute(builder: (context) => OfferAdditional(packageOptionID, id, pId, name, status, textStatus, detail)),
                // );

                AppUrl.PR_Id = packageOptionID;
                AppUrl.P_Id = pId;
                AppUrl.CA = ca;
                push(
                  context,
                  MaterialPageRoute(
                      builder: (context) => ListRequestAdditional()),
                );
              },
              child: Icon(
                FontAwesomeIcons.pencilAlt,
                color: AppColors.color,
              ),
            )
          : null;
    } else if (status == 3) {
      textStatus = "ดำเนินการจบแล้ว";
      icon = Icon(
        FontAwesomeIcons.checkCircle,
        color: Colors.grey,
      );
    }

    return Column(
      children: <Widget>[
        Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[
                Container(
                  width: mediaQuery(context, 'w', 1005),
                  height: mediaQuery(context, 'h', 150),
                  decoration: BoxDecoration(
                    borderRadius: new BorderRadius.all(
                      Radius.circular(
                        mediaQuery(context, 'h', 140),
                      ),
                    ),
                    boxShadow: [
                      BoxShadow(
                        offset: Offset(2.0, 2.0),
                        blurRadius: 10.0,
                        color: Color(0xFF000000).withOpacity(0.10),
                      ),
                    ],
                    color: Colors.white,
                  ),
                  child: Row(
                    children: <Widget>[
                      Container(
                        width: mediaQuery(context, 'w', 230),
                        height: mediaQuery(context, 'h', 150),
                        padding: EdgeInsets.all(
                          mediaQuery(context, 'h', 20),
                        ),
                        decoration: BoxDecoration(
                          borderRadius: new BorderRadius.all(
                            Radius.circular(
                              mediaQuery(context, 'h', 70),
                            ),
                          ),
                          boxShadow: [
                            appShadow(),
                          ],
                          color: AppColors.color_gold,
                        ),
                        child: Text(
                          pCode,
                          textAlign: TextAlign.center,
                          style: TextStyle(
                            fontSize: mediaQuery(context, 'h', 42),
                            color: Colors.white,
                            fontWeight: FontWeight.bold,
                          ),
                        ),
                      ),
                      Container(
                        width: mediaQuery(context, 'h', 400),
                        child: Column(
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: <Widget>[
                            Flexible(
                              child: Text(
                                name,
                                textAlign: TextAlign.center,
                                style: TextStyle(
                                  fontSize: mediaQuery(context, 'h', 40),
                                  color: Color(0xFF383838),
                                ),
                              ),
                            ),
                          ],
                        ),
                      ),
                      Container(
                        width: mediaQuery(context, 'w', 2),
                        height: mediaQuery(context, 'h', 100),
                        color: AppColors.color_gold,
                      ),
                      Container(
                        width: mediaQuery(context, 'h', 310),
                        padding: EdgeInsets.only(
                          left: mediaQuery(context, 'w', 36),
                        ),
                        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(
                              textStatus,
                              textAlign: TextAlign.center,
                              style: TextStyle(
                                fontSize: mediaQuery(context, 'h', 36),
                                color: AppColors.color_gold,
                              ),
                            ),
                          ],
                        ),
                      ),
                      Container(
                        width: mediaQuery(context, 'w', 2),
                        height: mediaQuery(context, 'h', 100),
                        color: isUpdate == 1.toString() ||
                                isUpdate == '' ||
                                isAll == 1.toString()
                            ? AppColors.color_gold
                            : null,
                      ),
                      Container(
                        alignment: Alignment.center,
                        width: mediaQuery(context, 'w', 118),
                        child: icon,
                      ),
                    ],
                  ),
                ),
              ],
            ),
          ],
        ),
        _buildSizeBox(context),
      ],
    );
  }

  @override
  bool get wantKeepAlive => true;

  _buildSizeBox(context) {
    return SizedBox(
      height: mediaQuery(context, "h", 40),
    );
  }
}