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/convert.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/url.dart';
import 'package:mwf_app/model/customer_care.dart';
import 'package:mwf_app/set1/serve_customers.dart';
import 'package:mwf_app/set9/edit_staff.dart';
import 'package:need_resume/need_resume.dart';
import 'package:mwf_app/set3/customer_care_staff.dart';

class Customerstaff_list extends StatefulWidget {
  Customerstaff_list();
  @override
  _Customerstaff_listState createState() => _Customerstaff_listState();
}

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

  @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!');
  }

  loadData() async {
    setState(() {
      isLoading = true;
    });
    final list = await CustomerCare.getData(); // ไปเรียกฟังชั่นดึงข้อมูลจาก api
    setState(() {
      list.forEach((v) {
        final staffList = CustomerCare.fromJson(v);
        CustomerCare.data.add(staffList); // loop เก็บข้อมูล        
        CustomerCare.data.sort((a, b) =>
            b.customerCareStartDate.compareTo(a.customerCareStartDate));
      });
    });
    await new Future.delayed(const Duration(milliseconds: 1000));
    setState(() {
      isLoading = false;
    });
  }

  setPermission() async {
    var data = await Permission.getResource("menuCareUserData");
    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
  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(
              //            icon เมนู
              width: _width,
              margin: EdgeInsets.only(
                top: mediaQuery(context, 'h', 950),
                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.spaceBetween,
                      children: <Widget>[
                        Container(
                          width: mediaQuery(context, 'w', 200),
                        ),
                        Text(
                          'รายชื่อพนักงานดูแลลูกค้า',
                          style: TextStyle(
                            color: Color(0xFFB58E38),
                            fontSize: mediaQuery(context, 'h', 55),
                          ),
                        ),
                        Container(
                            child: isAdd == "1" || isAdd == '' || isAll == "1"
                                ? GestureDetector(
                                    onTap: () {
                                      push(
                                        context,
                                        MaterialPageRoute(
                                            builder: (context) =>
                                                CustomerCareStaff()),
                                      );
                                    },
                                    child: Row(
                                      children: <Widget>[
                                        Icon(
                                          Icons.add_circle_outline,
                                          size: mediaQuery(context, 'h', 100),
                                          color: AppColors.color,
                                        ),
                                        SizedBox(
                                          width: mediaQuery(context, 'w', 14),
                                        ),
                                        Text(
                                          AppStrings.addTask,
                                          style: TextStyle(
                                            color: AppColors.color,
                                            fontSize:
                                                mediaQuery(context, 'h', 40),
                                          ),
                                        ),
                                      ],
                                    ),
                                  )
                                : null)
                      ],
                    ),
                  ),
                ],
              ),
            ),
            Container(
              width: _width,
              height: mediaQuery(context, 'h', 1150),
              margin: EdgeInsets.only(
                top: mediaQuery(context, 'h', 1100),
                left: mediaQuery(context, 'w', 60),
                right: mediaQuery(context, 'w', 60),
              ),
              child: SingleChildScrollView(
                child: Column(
                  children: <Widget>[
                    Column(
                      children: List.generate(CustomerCare.data.length, (index) {
                        return _buildContent(
                          context,
                          (index + 1).toString(),
                          CustomerCare.data[index].employeeFullName,
                          CustomerCare.data[index].customerCareStartDate,
                          CustomerCare.data[index].customerCareEndDate,
                          CustomerCare.data[index].customerSaleInfoId,
                        );
                      }),
                    ),
                  ],
                ),
              ),
            )
          ],
        ),
      ),
    );
  }

  _buildContent(
      context, number, name, String startDate, String endDate, customerCareID) {
    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', 740),
            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(
                          name,
                          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(
                          AppConvert.dateOnly(startDate),
                          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(
                          AppConvert.dateOnly(endDate),
                          style: TextStyle(
                            color: AppColors.color_text,
                            fontSize: mediaQuery(context, 'h', 40),
                          ),
                        ),
                      ],
                    ),
                  ],
                ),
              ],
            ),
          ),
          Container(
            width: 60,
            height: 81,
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Flexible(
                  child: isUpdate == "1" || isUpdate == '' || isUpdate == "1"
                      ? GestureDetector(
                          onTap: () {
                            print("--- CustomerCare ID : " + customerCareID);
                            push(
                              context,
                              MaterialPageRoute(
                                builder: (context) => EditStaff(
                                  name,
                                  startDate,
                                  endDate,
                                  customerCareID,
                                ),
                              ),
                            );
                          },
                          child: Container(
                            alignment: Alignment.center,
                            padding: EdgeInsets.only(
                              left: mediaQuery(context, 'w', 10),
                            ),
                            child: Center(
                              child: Icon(
                                Icons.edit,
                                size: mediaQuery(context, 'h', 80),
                                color: AppColors.color,
                              ),
                            ),
                          ),
                        )
                      : Container(width: mediaQuery(context, 'w', 10)),
                ),
                Flexible(
                  child: isDelete == "1" || isDelete == '' || isDelete == "1"
                      ? GestureDetector(
                          onTap: () async {
                            bool conf = await alertConfirm(
                                context, "แจ้งเตือน", "ยืนยันการลบ");
                            if (conf) {
                              Map<String, dynamic> data = {
                                "CustomerSaleInfoId": customerCareID,
                                "AuthenKey": AppUrl.AuthenKey
                              };
                              print(data);
                              bool res =
                                  await CustomerCare.delete(context, data);
                              if (res) {
                                AppLoader.showSuccess("ลบสำเร็จ");
                                await loadData();
                              }
                            }
                          },
                          child: Container(
                            alignment: Alignment.center,
                            padding: EdgeInsets.only(
                              left: mediaQuery(context, 'w', 20),
                            ),
                            child: Center(
                              child: Icon(
                                FontAwesomeIcons.trashAlt,
                                size: mediaQuery(context, 'h', 80),
                                color: AppColors.color_gold,
                              ),
                            ),
                          ),
                        )
                      : Container(width: mediaQuery(context, 'w', 20)),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }
}
