//VisitPlan_model.dart
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/service/convert.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/model/visit_plan.dart';
import 'package:mwf_app/set1/serve_customers.dart';
import 'package:mwf_app/set2/visiting_plan_save.dart';
import 'package:mwf_app/set4/service_visit_user.dart';
import 'package:need_resume/need_resume.dart';
import 'package:mwf_app/service/alert.dart';
import 'package:mwf_app/set2/visiting_plan_add.dart';

class VisitingPlanList extends StatefulWidget {

  VisitingPlanList();
  @override
  _VisitingPlanListState createState() => _VisitingPlanListState();
}

VisitIdClass visitIdVal = VisitIdClass("");

class _VisitingPlanListState extends ResumableState<VisitingPlanList> {
  _VisitingPlanListState();
  bool isLoading = false;
  String isView = '';
  String isAdd = '';
  String isUpdate = '';
  String isDelete = '';
  String isAll = '';

  @override
  void onReady() {
    Header.routes = ServeCustomer();
    setPermission();
    setState(() {
      NotificationCount.visitplanCount = 0;
    });
    print('Get Permission from pass page ...');
   
    setState(() {
      loadData();
    });

    print('Screen is ready!');
  }

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

  @override
  void onPause() {
    print('Screen is paused!  plan list ');
    setState(() {
      loadData();
    });
  }

  setPermission() async {
    var data = await Permission.getResource("menuVisitUserData");
    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 {
    print("visiting_plan_list");
    isLoading = true;
    try {
      final list =
          await VisitPlanCreate.getData(); // ไปเรียกฟังชั่นดึงข้อมูลจาก api
      setState(() {
        list.forEach((v) {
          final visitList = VisitPlanCreate.fromJson(v);
          VisitPlanCreate.data.add(visitList); // loop เก็บข้อมูล
          VisitPlanCreate.data.sort(
            (a, b) => AppConvert.dateTimeThaiToEng(b.visitPlanDate.split("-")[0]).compareTo(AppConvert.dateTimeThaiToEng(a.visitPlanDate).split("-")[0])
          );
        });
        isLoading = false;
      });
    } catch (e) {
      setState(() {
        isLoading = false;
      });
      print(e);
    }
  }

  @override
  Widget build(BuildContext context) {
    if (isLoading == true) {
      AppLoader.show();
    }
    if (isLoading == false) {
      AppLoader.hide();
    }
    double _width = MediaQuery.of(context).size.width;
    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', 1200),
              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),
                            ),
                          ),
                          isAdd == "1" || isAdd == '' || isAll == "1"
                              ? GestureDetector(
                                  onTap: () {
                                    push(
                                      context,
                                      MaterialPageRoute(
                                          builder: (context) =>
                                              VisitingPlanAdd()),
                                    );
                                  },
                                  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),
                                        ),
                                      ),
                                    ],
                                  ),
                                )
                              : Text('')
                        ],
                      ),
                    ),
                    SizedBox(
                      height: mediaQuery(context, 'h', 50),
                    ),
                    Column(
                      children:
                          List.generate(VisitPlanCreate.data.length, (index) {
                        return _buildContent(
                          context,
                          (index + 1).toString(),
                          VisitPlanCreate.data[index].visitId,
                          VisitPlanCreate.data[index].visitPlanDate,
                          VisitPlanCreate.data[index].visitObjective,
                          VisitPlanCreate.data[index].visitTeamPosition,
                          VisitPlanCreate.data[index].visitStatus,
                        );
                      }),
                    ),
                  ],
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  _buildContent(
    context,
    number,
    visitId,
    todate,
    purpose,
    visitor,
    status,
  ) {
    return Container(
      width: mediaQuery(context, 'w', 1006),
//      height: mediaQuery(context, 'h', 380),
      padding: EdgeInsets.all(
        mediaQuery(context, 'h', 30),
      ),
      margin: EdgeInsets.only(
        bottom: mediaQuery(context, 'h', 30),
      ),
      decoration: BoxDecoration(
        borderRadius: BorderRadius.all(
          Radius.circular(
            mediaQuery(context, 'h', 20),
          ),
        ),
        boxShadow: [
          appShadow(),
        ],
        color: Colors.white,
      ),
      child: Row(
        children: <Widget>[
          Container(
            width: mediaQuery(context, 'w', 800),
            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,
                      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(
                        todate != null
                            ? todate.toString().replaceAll("-", " น. - ") +
                                " น."
                            : '',
                        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(
                        purpose != null ? purpose : '',
                        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(
                      status,
                      style: TextStyle(
                        color: AppColors.color_text,
                        fontSize: mediaQuery(context, 'h', 40),
                      ),
                    ),
                  ],
                ),
              ],
            ),
          ),
          Container(
            child: Column(
              children: [
                isUpdate == "1" || isUpdate == '' || isAll == "1"
                    ? Container(
                        child: SizedBox.fromSize(
                          size: Size(32, 32),
                          child: ClipOval(
                            child: Material(
                              color: Colors.white,
                              child: InkWell(
                                splashColor: Colors.purple.shade50,
                                onTap: () {
                                  print("Go to Edit.");
                                  push(
                                    context,
                                    MaterialPageRoute(
                                        builder: (context) => VisitingPlanSave(
                                              visitIdEdit: visitId,
                                            )),
                                  );
                                },
                                child: Column(
                                  mainAxisAlignment: MainAxisAlignment.center,
                                  children: <Widget>[
                                    Icon(
                                      FontAwesomeIcons.pencilAlt,
                                      color: AppColors.color,
                                    ),
                                  ],
                                ),
                              ),
                            ),
                          ),
                        ),
                      )
                    : SizedBox.fromSize(
                        size: Size(32, 32),
                      ),
                isDelete == "1" || isDelete == '' || isAll == "1"
                    ? Container(
                        child: SizedBox.fromSize(
                          size: Size(32, 32),
                          child: ClipOval(
                            child: Material(
                              color: Colors.white,
                              child: InkWell(
                                splashColor: Colors.purple.shade50,
                                onTap: () async {
                                  print("Del");
                                  bool chk = await alertConfirm(
                                      context, "แจ้งเตือน", "ยืนยันการลบ");
                                  if (chk) {
                                    setState(() {
                                      isLoading = true;
                                    });
                                    VisitPlanCreate.deleteData(context, visitId)
                                        .then((res) {
                                      isLoading = false;
                                      loadData();
                                      // Nav.push(context, VisitingPlanList());
                                    });
                                  }
                                },
                                child: Column(
                                  mainAxisAlignment: MainAxisAlignment.center,
                                  children: <Widget>[
                                    Icon(
                                      FontAwesomeIcons.trashAlt,
                                      color: AppColors.color_gold,
                                    ),
                                  ],
                                ),
                              ),
                            ),
                          ),
                        ),
                      )
                    : SizedBox.fromSize(size: Size(32, 32)),
                Container(
                  child: SizedBox.fromSize(
                    size: Size(mediaQuery(context, 'w', 138),
                        mediaQuery(context, 'h', 110)),
                    child: Material(
                      color: Colors.white,
                      child: InkWell(
                        splashColor: Colors.purple.shade50,
                        onTap: () {
                          visitIdVal = VisitIdClass(visitId);
                          Navigator.of(context).pushReplacement(
                            MaterialPageRoute(
                              settings: const RouteSettings(
                                  name: '/serviceVisitUser'),
                              builder: (context) => ServiceVisitUser(
                                visitId,
                              ),
                            ),
                          );
                        },
                        child: Column(
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: <Widget>[
                            Text(
                              'เยี่ยมเยือน',
                              style: TextStyle(
                                color: AppColors.color,
                                decoration: TextDecoration.underline,
                                fontSize: mediaQuery(context, 'h', 35),
                                fontWeight: FontWeight.bold
                              ),
                            )
                          ],
                        ),
                      ),
                    ),
                  ),
                ),
              ],
            ),
          )
        ],
      ),
    );
  }
} //class
