//CustomerContact _model.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/model/customer_contact.dart';
import 'package:mwf_app/set1/serve_customers.dart';
import 'package:need_resume/need_resume.dart';
import 'package:mwf_app/set5/customer_representative_add.dart';
import 'package:mwf_app/set5/customer_representative_edit.dart';

class CustomerRepresentativeList extends StatefulWidget {
 
  CustomerRepresentativeList();
  @override
  _CustomerRepresentativeListState createState() =>
      _CustomerRepresentativeListState();
}

class _CustomerRepresentativeListState
    extends ResumableState<CustomerRepresentativeList> {
  _CustomerRepresentativeListState();

  bool isLoading = false;
  String isView = '';
  String isAdd = '';
  String isUpdate = '';
  String isDelete = '';
  String isAll = '';

  @override
  void onReady() {
    print('Screen is ready! Customer_representative_list.dart');
    print('รายชื่อผู้แทน');
    print('Permission for this menu ...');
    setPermission();
    loadData(); // ดึงข้อมูล
  }

  @override
  void onResume() {
    // Implement your code inside here
    loadData(); // ดึงข้อมูลใหม่
    print('Screen is resumed!');
  }

  @override
  void onPause() {
    print('Screen is paused!');
  }

  setPermission() async {
    var data = await Permission.getResource("menuListUserData");
    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);
  }

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

  delData(String customerId, index) async {
    bool conf = await alertConfirm(context, "แจ้งเตือน", "ยืนยันการลบ");
    if (conf == true) {
      setState(() {
        isLoading = true;
      });
      await new Future.delayed(const Duration(milliseconds: 1000));
      var chk = await CustomerContact.deleteData(context, customerId, index);
      if (chk == true) {
        loadData();
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    if (isLoading == true) {
      AppLoader.show();
    }
    if (isLoading == false) {
      AppLoader.hide();
    }
    double _width = MediaQuery.of(context).size.width;
    Header.routes = ServeCustomer();
    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,
              //color: Colors.black26,
              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', 60),
                          ),
                        ),
                        isAdd == "1" || isAdd == '' || isAll == "1"
                            ? GestureDetector(
                                onTap: () {
                                  print('click Add');
                                  push(
                                    context,
                                    MaterialPageRoute(
                                        builder: (context) =>
                                            CustomerRepresentativeAdd()),
                                  );
                                },
                                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),
                                      ),
                                    ),
                                  ],
                                ),
                              )
                            : Container(width: mediaQuery(context, 'w', 14)),
                      ],
                    ),
                  ),
                ],
              ),
            ),
            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: List.generate(CustomerContact.data.length, (index) {
                    return _buildContent(
                        context,
                        (index + 1).toString(),
                        CustomerContact.data[index].firstName +
                            " " +
                            CustomerContact.data[index].lastName,
                        CustomerContact.data[index].position,
                        CustomerContact.data[index].contactTel,
                        CustomerContact.data[index].contactEtc,
                        index);
                  }),
                ),
              ),
            )
          ],
        ),
      ),
    );
  }

  _buildContent(context, number, name, position, phone, contactMethod, index) {
    return Container(
      width: mediaQuery(context, 'w', 1150),
//      height: mediaQuery(context, 'h', 380),
      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', 760),
            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 == null ? "" : 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 == null ? "" : 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(
                          position == null ? "" : position,
                          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(
                          phone == null ? "" : phone,
                          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(
                          contactMethod ?? "",
                          style: TextStyle(
                            color: AppColors.color_text,
                            fontSize: mediaQuery(context, 'h', 40),
                          ),
                        ),
                      ],
                    ),
                  ],
                ),
              ],
            ),
          ),
          Column(
            children: <Widget>[
              isUpdate == "1" || isUpdate == '' || isAll == "1"
                  ? GestureDetector(
                      onTap: () {
                        print('on edit');
                        push(
                          context,
                          MaterialPageRoute(
                            builder: (context) =>
                                CustomerRepresentativeEdit(index),
                          ),
                        );
                      },
                      child: Container(
                        alignment: Alignment.center,
                        padding: EdgeInsets.only(
                          left: mediaQuery(context, 'w', 68),
                        ),
                        child: Center(
                          child: Icon(
                            FontAwesomeIcons.pencilAlt,
                            size: mediaQuery(context, 'h', 80),
                            color: AppColors.color,
                          ),
                        ),
                      ),
                    )
                  : Container(width: mediaQuery(context, 'w', 68)),
              SizedBox(
                height: mediaQuery(context, 'h', 60),
              ),
              isDelete == "1" || isDelete.isEmpty
                  ? GestureDetector(
                      onTap: () {
                        print('on delete');
                        delData(
                          CustomerContact.data[index].customerContactInfoId
                              .toString(),
                          index,
                        );
                      },
                      child: Container(
                        alignment: Alignment.center,
                        padding: EdgeInsets.only(
                          left: mediaQuery(context, 'w', 68),
                        ),
                        child: Center(
                          child: Icon(
                            FontAwesomeIcons.trashAlt,
                            size: mediaQuery(context, 'h', 80),
                            color: AppColors.color_gold,
                          ),
                        ),
                      ),
                    )
                  : Container(width: mediaQuery(context, 'w', 68)),
            ],
          )
        ],
      ),
    );
  }
}
