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/model/history_contact.dart';
import 'package:mwf_app/set1/serve_customers.dart';
import 'package:mwf_app/set7/history_communication.dart';
import 'package:mwf_app/set7/contact_user_edit.dart';
import 'package:need_resume/need_resume.dart';

class ContactUser extends StatefulWidget {

  ContactUser();

  @override
  _ContactUserState createState() => _ContactUserState();
}

class _ContactUserState extends ResumableState<ContactUser> {
  _ContactUserState();

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

  @override
  void onReady() {
    print('Screen is ready! contact_user.dart list ประวัติการติดต่อสื่อสาร');
    print('Permission for this menu ...');
    setPermission();
    loadData(); // ดึงข้อมูล
  }

  @override
  void onResume() {
    loadData(); // ดึงข้อมูลใหม่
  }
  
  setPermission() async {
    var data = await Permission.getResource("menuContactUserData");
    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);
  }
  
  Future<void> loadData() async {
    setState(() {
      isLoading = true;
    });
    AppLoader.show();
    try {
      final list =
          await HistoryContact.getData(); // ไปเรียกฟังชั่นดึงข้อมูลจาก api
      setState(() {
        list.forEach((v) {
          final contactList = HistoryContact.fromJson(v);
          HistoryContact.data.add(contactList); // loop เก็บข้อมูล
          HistoryContact.data
              .sort((a, b) => b.communicateDate.compareTo(a.communicateDate));
        });
        isLoading = false;
      });
    } catch (e) {
      setState(() {
        isLoading = false;
      });
      print(e);
    }
    AppLoader.hide();
  }

  @override
  Widget build(BuildContext context) {
    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(
              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', 120),
                        ),
                        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) =>
                                          HistoryCommunication(),
                                    ),
                                  );
                                },
                                child: Row(
                                  children: <Widget>[
                                    Icon(
                                      Icons.add_circle_outline,
                                      size: mediaQuery(context, 'h', 100),
                                      color: AppColors.color,
                                    ),
                                    SizedBox(
                                      width: mediaQuery(context, 'w', 10),
                                    ),
                                    Text(
                                      'เพิ่ม',
                                      style: TextStyle(
                                        color: AppColors.color,
                                        fontSize: mediaQuery(context, 'h', 40),
                                      ),
                                    ),
                                  ],
                                ),
                              )
                            : Container(width: mediaQuery(context, 'w', 10))
                      ],
                    ),
                  ),
                ],
              ),
            ),
            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(HistoryContact.data.length, (index) {
                    return _buildContent(
                      context,
                      (index + 1).toString(),
                      HistoryContact.data[index].communicateDate,
                      HistoryContact.data[index].communicateDetail,
                      HistoryContact.data[index].communicateWith,
                      HistoryContact.data[index].customerCommunicateId,
                    );
                  }),
                ),
              ),
            )
          ],
        ),
      ),
    );
  }

  _buildContent(
      context, number, dateReport, list, userReport, historyContactID) {
    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>[
          GestureDetector(
            onTap: () {},
            child: Container(
              width: mediaQuery(context, 'w', 770),
              child: Wrap(
                spacing: 2.0,
                runSpacing: 2.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(
                            AppConvert.dateTimeConvert(dateReport) + " น.",
                            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),
                            ),
                          ),
                          Flexible(
                            child: Text(
                              list,
                              softWrap: true,
                              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(
                            userReport,
                            style: TextStyle(
                              color: AppColors.color_text,
                              fontSize: mediaQuery(context, 'h', 40),
                            ),
                          ),
                        ],
                      ),
                    ],
                  ),
                ],
              ),
            ),
          ),
          Column(
            children: <Widget>[
              isUpdate == "1" || isUpdate.isEmpty || isAll == "1"
                  ? GestureDetector(
                      onTap: () {
                        print('on edit');
                        push(
                          context,
                          MaterialPageRoute(
                            builder: (context) =>
                                ContactUserEdit(historyContactID),
                          ),
                        );
                      },
                      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 == '' || isAll == "1"
                  ? GestureDetector(
                      onTap: () {
                        print('on delete');
                        delData(historyContactID);
                      },
                      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),
                    ),
            ],
          )
        ],
      ),
    );
  }

  delData(historyContactID) async {
    bool conf = await alertConfirm(context, "แจ้งเตือน", "ยืนยันการลบ");
    if (conf == true) {
      var chk = await HistoryContact.deleteData(context, historyContactID);
      if (chk == true) {
        loadData();
      }
    }
  }
}
