import 'dart:async';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:mwf_app/service/color.dart';
import 'package:mwf_app/service/fontsize.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/url.dart';
import 'package:mwf_app/home.dart';
import 'package:mwf_app/model/Notification_model.dart';

class NotificationPage extends StatefulWidget {
  @override
  _NotificationPageState createState() => _NotificationPageState();
}

class _NotificationPageState extends State<NotificationPage> {
  bool isLoading = false;
  Future _future;

  @override
  void initState() {
    super.initState();
    Header.routes = HomePage();
    print(AppUrl.EmployeeID);
    isLoading = true;
    wait();
    _future = _getD();
    //loadData(); //เรียกอันนี้เชื่อม api
  }
  
  wait() async {
    await Future.delayed(Duration(seconds: 2));
    setState(() {
      isLoading = false;    
    });
  }

  Future<List<NotificationModel>> _getD() async {
    //NotificationModel.data.clear();
    try{
      final list = await NotificationModel.getData();
      list.forEach((v) {
        final list = NotificationModel.fromJson(v);
        NotificationModel.data.add(list); // loop เก็บข้อมูล
      });
    }catch(e){
      print(e);
    }
    return NotificationModel.data;
  }

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

  @override
  Widget build(BuildContext context) {
    Header.currentPage = "alert";
    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.header2ListPage(context),
            Header.mainMenu(context),
            Container(
              width: _width,
              height: mediaQuery(context, 'h', 1800),
              margin: EdgeInsets.only(
                // top: mediaQuery(context, 'h', 400),
                top: mediaQuery(context, 'h', 370),
                left: mediaQuery(context, 'w', 60),
                right: mediaQuery(context, 'w', 60),
              ),
              // child: SingleChildScrollView(
                child: Column(
                  children: <Widget>[
                    Container(
                      alignment: Alignment.center,
                      child: Text(
                        'แจ้งเตือน',
                        style: TextStyle(
                          color: AppColors.color_gold,
                          fontSize:
                              mediaQuery(context, 'h', AppFontSize.headText),
                        ),
                      ),
                    ),
                    SizedBox(
                      height: mediaQuery(context, 'h', 40),
                    ),
                    Container(
                      width: _width,
                      height: mediaQuery(context, 'h', 1640),
                      child: FutureBuilder(
                        future: _future,
                            builder: (BuildContext context, AsyncSnapshot snapshot) {
                              if (snapshot.data == null) {
                                return Container(
                                  child: AppLoader.show(),
                                );
                              } else {
                                AppLoader.hide();
                                return ListView.builder(
                                  shrinkWrap: true,
                                  itemCount: snapshot.data.length,
                                  itemBuilder: (BuildContext context, int index) {

                                    return _buildContent(
                                      context,
                                      snapshot.data[index].customerName,
                                      snapshot.data[index].notificationTitle,
                                      snapshot.data[index].detail,
                                      snapshot.data[index].eventDate,
                                      snapshot.data[index].notificationType,
                                    );
                                  },
                                );
                              }
                            },
                          )
                    )
                    // Column(
                    //   children: List.generate(
                    //       NotificationModel.data.length, (index) {
                    //     return _buildContent(
                    //       context,
                    //       NotificationModel.data[index].customerName,
                    //       NotificationModel.data[index].notificationTitle,
                    //       NotificationModel
                    //           .data[index].detail,
                    //       NotificationModel.data[index].eventDate,
                    //     );
                    //   }),
                    // ),
                  ],
                ),
              //),
            ),
          ],
        ),
      ),
    );
  }

  _buildContent(context, name, title, detail, date, type) {
    String detailTask = "";
    String detailData = "";
    String titleDetail = "";
    String nameDetail = "";
    if(type == "PackageRequest"){
      if(detail.isNotEmpty){
        var dataLength =  detail.split(" ").length;
        detailData = detail.split(" ")[0];
        if(dataLength > 3 && dataLength > 6 ){
          for(var i = 3; i< dataLength; i++){
            titleDetail = detail.split(" ")[1] + detail.split(" ")[2];
            nameDetail = nameDetail + " " + detail.split(" ")[i];
          }
        }else if(dataLength > 3 && dataLength < 7){
          titleDetail = detail.split(" ")[1];
          for(var i = 2; i < dataLength; i++){
            nameDetail = nameDetail + " " + detail.split(" ")[i];
          }
        }else{
          titleDetail = detail.split(" ")[1];
          nameDetail = detail.split(" ")[2];
        }
        detailTask = detailData + "\n" + titleDetail + "\n" + nameDetail.trim();
      }else{
        detailTask = "";
      }
    }
    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: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          Row(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: <Widget>[
              Text(
                'ชื่อบริษัท : ',
                style: TextStyle(
                  color: AppColors.color_text,
                  fontSize: mediaQuery(context, 'h', 40),
                ),
              ),
              Flexible(
                child: Text(
                  name,
                  style: TextStyle(
                    color: AppColors.color_text,
                    fontSize: mediaQuery(context, 'h', 40),
                    fontWeight: FontWeight.bold,
                  ),
                ),
              ),
            ],
          ),
          Row(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: <Widget>[
              Text(
                'ชื่อเรื่อง : ',
                style: TextStyle(
                  color: AppColors.color_text,
                  fontSize: mediaQuery(context, 'h', 40),
                ),
              ),
              Flexible(
                child: Text(
                  title,
                  style: TextStyle(
                    color: AppColors.color_text,
                    fontSize: mediaQuery(context, 'h', 40),
                    fontWeight: FontWeight.bold,
                  ),
                ),
              ),
            ],
          ),
          Row(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: <Widget>[
              Text(
                'วันที่ : ',
                style: TextStyle(
                  color: AppColors.color_text,
                  fontSize: mediaQuery(context, 'h', 40),
                ),
              ),
              Flexible(
                child: Text(
                  date != "" ? date : "" + " น.",
                  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', 40),
                ),
              ),
              Flexible(
                child: Text(
                  type == "PackageRequest" ? detailTask : detail != "" ? detail : "",
                  style: TextStyle(
                    color: AppColors.color_text,
                    fontSize: mediaQuery(context, 'h', 40),
                  ),
                ),
              ),
            ],
          ),
        ],
      ),
    );
  }
} //class

class KeyValueModel {
  String key;
  String value;

  KeyValueModel({this.key, this.value});

  KeyValueModel.fromJson(Map<String, dynamic> json) {
    key = json['key'];
    value = json['value'];
  }

  static List<KeyValueModel> data = []; // ตัวแปรที่จะเรียกใช้งาน
}
