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/color.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/alert.dart';
import 'package:mwf_app/model/customer_relation.dart';
import 'package:mwf_app/set1/serve_customers.dart';
import 'package:mwf_app/set6/add_activity.dart';
import 'package:need_resume/need_resume.dart';

//CustomerRelation_model
class ActivityRelationship extends StatefulWidget {

  ActivityRelationship();
  @override
  _ActivityRelationshipState createState() => _ActivityRelationshipState();
}

class _ActivityRelationshipState extends ResumableState<ActivityRelationship> {
  _ActivityRelationshipState();

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

  @override
  void onReady() {
    setPermission();

    print('Screen is ready!');
    print('activity_relationship');
    print('Permission for this menu ...');
    loadData();
  }

  @override
  void onResume() {
    loadData();
    print('Screen is resumed!');
  }

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

  setPermission() async {
    var data = await Permission.getResource("menuActivityUserData");
    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;
    });
    final list =
        await CustomerRelation.getData(); // ไปเรียกฟังชั่นดึงข้อมูลจาก api

    String errorMsg = "";
    try {
      errorMsg = list['Message'];
    } catch (e) {
      errorMsg = "";
    }
    print(errorMsg);
    if (errorMsg.indexOf('An error has occurred') == 0 ||
        errorMsg.indexOf('No HTTP resource was') == 0) {
    } else {
      CustomerRelation.data = [];
      setState(() {
        list.forEach((v) {
          final dataList = CustomerRelation.fromJson(v);
          CustomerRelation.data.add(dataList); // loop เก็บข้อมูล
        });
        isLoading = false;
      });
    }

    return true;
  }

  @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(
              width: _width,
              height: mediaQuery(context, 'h', 1250),
              margin: EdgeInsets.only(
                top: mediaQuery(context, 'h', 950),
                left: mediaQuery(context, 'w', 60),
                right: mediaQuery(context, 'w', 60),
              ),
              child: SingleChildScrollView(
                child: Column(
                  children: <Widget>[
                    Container(
                      alignment: Alignment.center,
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: <Widget>[
                          Container(
                            width: mediaQuery(context, 'w', 120),
                          ),
                          Text(
                            'กิจกรรมสร้างความสัมพันธ์',
                            style: TextStyle(
                              color: Color(0xFFB58E38),
                              fontSize: mediaQuery(context, 'h', 58),
                            ),
                          ),
                          Container(
                            child: isAdd == "1" || isAdd == '' || isAll == "1"
                                ? GestureDetector(
                                    onTap: () {
                                      push(
                                        context,
                                        MaterialPageRoute(
                                            builder: (context) =>
                                                AddActivity(null)),
                                      );
                                    },
                                    child: Row(
                                      children: <Widget>[
                                        Icon(
                                          Icons.add_circle_outline,
                                          size: mediaQuery(context, 'h', 80),
                                          color: AppColors.color,
                                        ),
                                        SizedBox(
                                          width: mediaQuery(context, 'w', 14),
                                        ),
                                        Text(
                                          'เพิ่ม',
                                          style: TextStyle(
                                            color: AppColors.color,
                                            fontSize:
                                                mediaQuery(context, 'h', 34),
                                          ),
                                        ),
                                      ],
                                    ),
                                  )
                                : null,
                          ),
                        ],
                      ),
                    ),
                    SizedBox(
                      height: mediaQuery(context, 'h', 50),
                    ),
                    Column(
                      children:
                          List.generate(CustomerRelation.data.length, (index) {
                        return _buildContent(
                          context,
                          (index + 1).toString(),
                          CustomerRelation.data[index].activityName == null
                              ? ""
                              : CustomerRelation.data[index].activityName,
                          (CustomerRelation.data[index].startDate == null
                              ? ""
                              : CustomerRelation.data[index].startDate),
                          (CustomerRelation.data[index].endDate == null
                              ? ""
                              : CustomerRelation.data[index].endDate),
                          "",
                          CustomerRelation.data[index].activityTypeName == null
                              ? ""
                              : CustomerRelation.data[index].activityTypeName,
                          CustomerRelation.data[index]
                                      .customerRelationshipActivityId ==
                                  null
                              ? ""
                              : CustomerRelation
                                  .data[index].customerRelationshipActivityId,
                        );
                      }),
                    ),
                  ],
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  _buildContent(
    context,
    number,
    subject,
    startDate,
    endDate,
    place,
    type,
    String customerRelationID,
  ) {
    return Container(
      width: mediaQuery(context, 'w', 1005),
//      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: 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),
                      ),
                    ),
                    Flexible(
                      child: Text(
                        subject == null ? "" : subject,
                        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(
                        startDate == null ? "" : 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),
                      ),
                    ),
                    Flexible(
                      child: Text(
                        endDate == null ? "" : endDate,
                        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(
                      place == null ? "" : place,
                      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(
                        type == null ? "" : type,
                        style: TextStyle(
                          color: AppColors.color_text,
                          fontSize: mediaQuery(context, 'h', 40),
                        ),
                      ),
                    ),
                  ],
                ),
              ],
            ),
          ),
          // EDIT and Delete
          Column(
            children: <Widget>[
              Container(
                width: mediaQuery(context, 'w', 150),
                alignment: Alignment.centerRight,
                child: Center(
                  child: isUpdate == "1" || isUpdate == '' || isAll == "1"
                      ? GestureDetector(
                          onTap: () {
                            push(
                              context,
                              MaterialPageRoute(
                                builder: (context) =>
                                    AddActivity(customerRelationID),
                              ),
                            );
                          },
                          child: Icon(
                            FontAwesomeIcons.pencilAlt,
                            size: mediaQuery(context, 'h', 80),
                            color: AppColors.color,
                          ),
                        )
                      : null,
                ),
              ),
              SizedBox(
                height: mediaQuery(context, 'h', 130),
              ),
              Container(
                width: mediaQuery(context, 'w', 50),
                alignment: Alignment.center,
                child: Center(
                  child: isDelete == "1" || isDelete == '' || isAll == "1"
                      ? GestureDetector(
                          onTap: () async {
                            bool chk = await alertConfirm(
                                context, "แจ้งเตือน", "ยืนยันการลบ");
                            if (chk) {
                              CustomerRelation.deleteData(
                                      context, customerRelationID)
                                  .then((res) {
                                loadData();
                              });
                            }
                          },
                          child: Icon(
                            FontAwesomeIcons.trashAlt,
                            size: mediaQuery(context, 'h', 80),
                            color: AppColors.color_gold,
                          ),
                        )
                      : null,
                ),
              ),
            ],
          ),

          //===============================================================================================
          //
          //===============================================================================================
        ],
      ),
    );
  }
} //class
