import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_rounded_date_picker/rounded_picker.dart';
import 'package:get/get.dart';
import 'package:intl/date_symbol_data_local.dart';
import 'package:intl/intl.dart';
import 'package:mwf_app/service/notification_count.dart';
import 'package:mwf_app/service/fontsize.dart';
import 'package:mwf_app/service/loader.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/screen.dart';
import 'package:mwf_app/service/shadow.dart';
import 'package:mwf_app/service/strings.dart';
import 'package:mwf_app/service/url.dart';
import 'package:mwf_app/service/convert.dart';
import 'package:mwf_app/set4/webview_additional.dart';
import 'package:mwf_app/model/StatusType_model.dart';
import 'package:mwf_app/model/PackageRequestHistory_model.dart';
import 'package:mwf_app/model/PackageRequest_model.dart';
import 'package:buddhist_datetime_dateformat/buddhist_datetime_dateformat.dart';
import 'package:mwf_app/set8/request_additional.dart';

// Package model
class ListRequestAdditional extends StatefulWidget {
  @override
  _ListRequestAdditionalState createState() => _ListRequestAdditionalState();
}

class _ListRequestAdditionalState extends State<ListRequestAdditional> {
  TextEditingController requestCus =
      TextEditingController(); // ความต้องการลูกค้า
  TextEditingController action = TextEditingController(); //สถานะการดำเนินการ
  TextEditingController date = TextEditingController(); // วันที่
  TextEditingController time = TextEditingController(); // เวลา
  TextEditingController operation = TextEditingController(); // การดำเนินงาน
  TextEditingController startDataText = TextEditingController(); //วันที่เริ่มต้น
  TextEditingController startTimeText = TextEditingController(); //วันที่สิ้นสุด
  TextEditingController strTearTimeText = TextEditingController(); //วันที่สิ้นสุด

  String strStartDate = "";
  bool isLoading = false;
  String dateCreate = "";
  String valueAction = '';
  String packCode = '';
  String packName = '';
  String packStatus = '';
  String pid = '';
  String createB = '';
  String detail = '';
  String prDescription = '';
  String prStatusType = '';
  bool actionEdit = false;
  bool actionCancel = false;

  var colorCard; // set Card color
  @override
  void initState() {
    super.initState();
    Intl.defaultLocale = 'th';
    actionEdit = false;
    Header.routes = RequestAdditional();
    initializeDateFormatting();
    strTearTimeText.text = "น.";
    print("-- List_request_additional.dart --");
    loadData(); // ดึงข้อมูล
    loadHistory();
    loadDataDropDown();
    initDefaultDate();
  }

  List<KeyValueModel> _dropdownAction = [
    KeyValueModel(key: "", value: 'เลือก')
  ];

  void initDefaultDate() {
    setState(() {
      print("Name :: " + AppUrl.userName.trim());
      DateTime newDate = DateTime.now();
      var dtArray = newDate.toString().split(" ");
      TimeOfDay newTime = TimeOfDay.now();
      String timeStr =
          AppConvert.fillZeroTime("", newTime.hour.toString(), newTime.minute.toString());
      setState(() {
        var formatter = DateFormat.yMd();
        var showDate = formatter.formatInBuddhistCalendarThai(newDate);
        date.text = showDate;
        dateCreate = dtArray[0];
        time.text = timeStr;
      });
    });
  }

  loadDataDropDown() async {
    final statusType =
        await StatusType.getData(); // ไปเรียกฟังชั่นดึงข้อมูลจาก api
    for (var i = 0; i < statusType.length; i++) {
      setState(() {
        _dropdownAction.add(
          KeyValueModel(
              key: statusType[i]['Id'].toString(), // key คือค่าที่แสดง
              value: statusType[i]['StatusType']),
        );
      });
    }
  }

  loadHistory() async {
    //List history
    final listHistory = await PackageRequestHistory
        .getHistoryData(); // ไปเรียกฟังชั่นดึงข้อมูลจาก api
    setState(() {
      listHistory.forEach((v) {
        final historyList = PackageRequestHistory.fromJson(v);
        PackageRequestHistory.data.add(historyList); // loop เก็บข้อมูล
      });
      PackageRequestHistory.data
          .sort((a, b) => 
          AppConvert.dateTimeEngSeperate(a.createDate).compareTo(
            AppConvert.dateTimeEngSeperate(b.createDate)
          )
        );
      List<PackageRequestHistory> reversedata =
          PackageRequestHistory.data.reversed.toList();
      PackageRequestHistory.data = reversedata;
    });
  }

  deleteHistory(context, id) async {
    //List history
    final listHistory = await PackageRequestHistory.deleteData(
      context,
      id.toString(),
    ); // ไปเรียกฟังชั่นดึงข้อมูลจาก api
    loadHistory();
  }

  loadData() async {
    setState(() {
      isLoading = true;
    });
    // ดึงข้อมูลของ id ที่ดึงเข้ามา
    final list = await PackageRequest
        .getDataReadList(); // ไปเรียกฟังชั่นดึงข้อมูลจาก api

    print("CA : " + AppUrl.CA);
    print("PR_Id : " + AppUrl.PR_Id);
    print("P_Id : " + AppUrl.P_Id);

    setState(() {
      final packageRequest = PackageRequest.fromJson(list);
      PackageRequest.data.add(packageRequest); // loop เก็บข้อมูล
      packCode = packageRequest.pCode;
      packName = packageRequest.pName;
      packStatus = packageRequest.prStatusName;
      pid = packageRequest.pId;
      createB = packageRequest.createBy;
      detail = packageRequest.pDetail;
      startTimeText.text = packageRequest.appointmentDate != null ? 
        packageRequest.appointmentDate.split("T")[0].substring(0,4) != "0001" ? 
          packageRequest.appointmentDate.split("T")[1].substring(0,5) : 
          "" : 
        "";
      
      startDataText.text = packageRequest.appointmentDate != null ? 
        packageRequest.appointmentDate.split("T")[0].substring(0,4) != "0001" ? 
          AppConvert.date(packageRequest.appointmentDate.split("T")[0]) : 
          "" :
        "";
      strStartDate = packageRequest.appointmentDate != null ? 
        packageRequest.appointmentDate.split("T")[0].substring(0,4) != "0001" ? 
          packageRequest.appointmentDate.split("T")[0] : 
          "" : 
        "";
      prDescription = packageRequest.prDescreption;
      prStatusType = packageRequest.prStatusType.toString();
      valueAction = packageRequest.prStatusType.toString();
      isLoading = false;
    });
  }

  @override
  Widget build(BuildContext context) {
    if (isLoading == true) {
      AppLoader.show();
    }
    if (isLoading == false) {
      AppLoader.hide();
    }
    double _width = MediaQuery.of(context).size.width;

    colorCard = Colors.purple[200];

    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', 1350),
              margin: EdgeInsets.only(
                top: mediaQuery(context, 'h', 895),
                left: mediaQuery(context, 'w', 30),
                right: mediaQuery(context, 'w', 30),
              ),
              child: SingleChildScrollView(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: <Widget>[
                    Container(
                      margin: EdgeInsets.only(
                        top: mediaQuery(context, 'h', 30),
                        bottom: mediaQuery(context, 'h', 50),
                      ),
                      child: Text(
                        'รายการขอใช้บริการเสริม',
                        textAlign: TextAlign.center,
                        style: TextStyle(
                          color: Color(0xFFB58E38),
                          fontSize: mediaQuery(context, 'h', 50),
                        ),
                      ),
                    ),
                    Container(
                      width: mediaQuery(context, 'w', 1005),
                      height: mediaQuery(context, 'h', 160),
                      decoration: BoxDecoration(
                        borderRadius: BorderRadius.all(
                          Radius.circular(
                            mediaQuery(context, 'h', 140),
                          ),
                        ),
                        boxShadow: [
                          appShadow(),
                        ],
                        color: Colors.white,
                      ),
                      child: Row(
                        children: <Widget>[
                          Container(
                            width: mediaQuery(context, 'w', 230),
                            height: mediaQuery(context, 'h', 150),
                            padding: EdgeInsets.all(
                              mediaQuery(context, 'h', 35),
                            ),
                            decoration: BoxDecoration(
                              borderRadius: BorderRadius.all(
                                Radius.circular(
                                  mediaQuery(context, 'h', 90),
                                ),
                              ),
                              boxShadow: [
                                appShadow(),
                              ],
                              color: AppColors.color_gold,
                            ),
                            child: Text(
                              packCode,
                              textAlign: TextAlign.center,
                              style: TextStyle(
                                fontSize: mediaQuery(context, 'h', 50),
                                color: Colors.white,
                                fontWeight: FontWeight.bold,
                              ),
                            ),
                          ),
                          Container(
                            width: mediaQuery(context, 'h', 340),
                            child: Text(
                              packName,
                              textAlign: TextAlign.center,
                              style: TextStyle(
                                fontSize: mediaQuery(context, 'h', 36),
                                color: Color(0xFF383838),
                              ),
                            ),
                          ),
                          Container(
                            width: mediaQuery(context, 'w', 2),
                            height: mediaQuery(context, 'h', 100),
                            color: AppColors.color_gold,
                          ),
                          Container(
                            width: mediaQuery(context, 'h', 465),
                            padding: EdgeInsets.only(
                              left: mediaQuery(context, 'w', 66),
                            ),
                            child: Column(
                              mainAxisAlignment: MainAxisAlignment.center,
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: <Widget>[
                                Text(
                                  'สถานะ',
                                  textAlign: TextAlign.center,
                                  style: TextStyle(
                                    fontSize: mediaQuery(context, 'h', 36),
                                    color: Color(0xFF383838),
                                  ),
                                ),
                                Text(
                                  packStatus,
                                  textAlign: TextAlign.center,
                                  style: TextStyle(
                                    fontSize: mediaQuery(context, 'h', 36),
                                    color: AppColors.color_gold,
                                  ),
                                ),
                              ],
                            ),
                          )
                        ],
                      ),
                    ),
                    SizedBox(
                      height: mediaQuery(context, 'h', 50),
                    ),
                    Container(
                      width: mediaQuery(context, 'w', 1005),
                      height: mediaQuery(context, 'h', 150),
                      decoration: BoxDecoration(
                        borderRadius: BorderRadius.all(
                          Radius.circular(
                            mediaQuery(context, 'h', 100),
                          ),
                        ),
                        boxShadow: [
                          appShadow(),
                        ],
                        color: AppColors.color_gold,
                      ),
                      child: GestureDetector(
                        onTap: () {
                          Navigator.push(
                            context,
                            MaterialPageRoute(
                                // builder: (context) => ListAdditional()
                                builder: (context) =>
                                    WebviewAdditional(pid: pid)),
                          );
                        },
                        child: Center(
                          child: Text(
                            'ข้อมูลบริการเสริม',
                            textAlign: TextAlign.center,
                            style: TextStyle(
                              fontSize: mediaQuery(context, 'h', 50),
                              color: Colors.white,
                            ),
                          ),
                        ),
                      ),
                    ),
                    SizedBox(
                      height: mediaQuery(context, 'h', 50),
                    ),
                    SizedBox(
                      height: mediaQuery(context, 'h', 50),
                    ),
                    Card(
                      // Block ความต้องการลูกค้า
                      elevation: 10,
                      child: Container(
                        padding: EdgeInsets.all(10),
                        decoration: BoxDecoration(
                          boxShadow: [
                            BoxShadow(
                              color: colorCard,
                              blurRadius: 1,
                            ),
                          ],
                        ),
                        child: Column(
                          children: <Widget>[
                            Column(
                              // ช่องกรอกความต้องการลูกค้า
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: <Widget>[
                                Row(
                                  children: <Widget>[
                                    Text(
                                      'ความต้องการลูกค้า :',
                                      textAlign: TextAlign.center,
                                      style: TextStyle(
                                        fontSize: mediaQuery(context, 'h', 34),
                                        color: Color(0xFF383838),
                                      ),
                                    ),
                                    SizedBox(
                                      width: mediaQuery(context, 'w', 570),
                                    ),
                                    _editButton(context),
                                  ],
                                ),
                                SizedBox(
                                  height: mediaQuery(context, 'h', 20),
                                ),
                                _widgetOfferCustomer(context, _width),
                                actionEdit
                                    ?
                                   
                                    Column(
                                        crossAxisAlignment:
                                            CrossAxisAlignment.start,
                                        children: <Widget>[
                                          SizedBox(
                                            height: mediaQuery(context, 'h', 20),
                                          ),
                                           _buildTextMenuTwoColumn(
                                            context,
                                            "วันที่นัดเข้าให้บริการ",
                                            AppStrings.TaskList_time,
                                            320.0,
                                          ),
                                          _buildTextFieldTwoColumnStart(
                                            context, startDataText, startTimeText),
                                          SizedBox(
                                            height: mediaQuery(context, 'h', 20),
                                          ),
                                          Text(
                                            'การดำเนินการ :',
                                            textAlign: TextAlign.center,
                                            style: TextStyle(
                                              fontSize:
                                                  mediaQuery(context, 'h', 34),
                                              color: Color(0xFF383838),
                                            ),
                                          ),
                                          _buildDropDownRow(context),
                                        ],
                                      )
                                    : Text(''),
                              ],
                            ),
                            SizedBox(
                              height: actionEdit ? mediaQuery(context, 'h', 50) :  mediaQuery(context, 'h', 1),
                            ),
                            actionEdit
                                ? Row(
                                    mainAxisAlignment: MainAxisAlignment.center,
                                    children: <Widget>[
                                      Container(
                                        //ปุ่มบันทึก แก้ไข ความต้องการลูกค้า
                                        width: mediaQuery(context, 'w', 280),
                                        height: mediaQuery(context, 'h', 150),
                                        child: RaisedButton(
                                          color: AppColors.color,
                                          onPressed: () {
                                            setState(() {
                                              actionCancel = false;
                                              actionEdit = false;
                                              update();
                                            });
                                          },
                                          shape: RoundedRectangleBorder(
                                            borderRadius: BorderRadius.circular(
                                              mediaQuery(context, 'h', 90),
                                            ),
                                          ),
                                          child: Text(
                                            'บันทึก',
                                            style: TextStyle(
                                              color: Colors.white,
                                              fontSize:
                                                  mediaQuery(context, 'h', 50),
                                            ),
                                          ),
                                        ),
                                      ),
                                      SizedBox(
                                        width: mediaQuery(context, 'w', 100),
                                      ),
                                      Container(
                                        //ปุ่มบันทึก แก้ไข ความต้องการลูกค้า
                                        width: mediaQuery(context, 'w', 280),
                                        height: mediaQuery(context, 'h', 150),
                                        child: RaisedButton(
                                          color: AppColors.color,
                                          onPressed: () {
                                            setState(() {
                                              actionCancel = false;
                                              actionEdit = false;
                                            });
                                          },
                                          shape: RoundedRectangleBorder(
                                            borderRadius: BorderRadius.circular(
                                              mediaQuery(context, 'h', 90),
                                            ),
                                          ),
                                          child: Text(
                                            'ยกเลิก',
                                            style: TextStyle(
                                              color: Colors.white,
                                              fontSize:
                                                  mediaQuery(context, 'h', 50),
                                            ),
                                          ),
                                        ),
                                      ),
                                    ],
                                  )
                                : SizedBox(
                                    height: mediaQuery(context, 'h', 0),
                                  ),
                                   SizedBox(
                              // ถึงใต้นี้
                              height: mediaQuery(context, 'h', 50),
                            ),
                            actionEdit ? 
                            Container() :
                            Column(
                              children: [
                                Row(
                                  children: [
                                    Text('วันที่นัดเข้าให้บริการ',style: TextStyle(fontSize: mediaQuery(context, 'h', 50),),),
                                  ],
                                ),
                                Row(
                                  children: <Widget>[
                                    SizedBox(
                                     //height: mediaQuery(context, 'h', 150),
                                      width: mediaQuery(context, 'w', 370),
                                      child: TextField(
                                        enabled: false,
                                        controller: startDataText,
                                        style: TextStyle(fontSize: mediaQuery(context, 'h', 50)),
                                      ),
                                    ),
                                    SizedBox(
                                      // ถึงใต้นี้
                                    width: mediaQuery(context, 'w', 50),
                                    ),
                                    SizedBox(
                                      //height: mediaQuery(context, 'h', 150),
                                      width: mediaQuery(context, 'w', 170),
                                      child: TextField(
                                        enabled: false,
                                        controller:  startTimeText,
                                        style: TextStyle(fontSize: mediaQuery(context, 'h', 50)),
                                      ),
                                    ),
                                    SizedBox(
                                      //height: mediaQuery(context, 'h', 150),
                                      width: mediaQuery(context, 'w', 40),
                                      child: TextField(
                                        enabled: false,
                                        controller:  strTearTimeText,
                                        style: TextStyle(fontSize: mediaQuery(context, 'h', 50)),
                                      ),
                                    ),
                                  ],
                                ),
                              ],
                            ),
                            SizedBox(
                              // ถึงใต้นี้
                              height: mediaQuery(context, 'h', 50),
                            ),
                          ],
                        ),
                      ),
                    ),
                    SizedBox(
                      height: mediaQuery(context, 'h', 50),
                    ),
                    Card(
                      // Block การดำเนินการ
                      elevation: 10,
                      child: Container(
                        padding: EdgeInsets.all(10),
                        decoration: BoxDecoration(
                          boxShadow: [
                            BoxShadow(
                              color: colorCard,
                              blurRadius: 1,
                            ),
                          ],
                        ),
                        child: Column(
                          children: <Widget>[
                            SizedBox(
                              height: mediaQuery(context, 'h', 50),
                            ),
                            Text(
                              'บันทึกการดำเนินการ',
                              textAlign: TextAlign.center,
                              style: TextStyle(
                                fontSize: mediaQuery(context, 'h', 60),
                                color: Color(0xFF383838),
                              ),
                            ),
                            SizedBox(
                              height: mediaQuery(context, 'h', 50),
                            ),
                            Row(
                              mainAxisAlignment: MainAxisAlignment.spaceBetween,
                              children: <Widget>[
                                Column(
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  children: <Widget>[
                                    Text(
                                      'วันที่ :',
                                      textAlign: TextAlign.center,
                                      style: TextStyle(
                                        fontSize: mediaQuery(context, 'h', 34),
                                        color: Color(0xFF383838),
                                      ),
                                    ),
                                    Container(
                                      height: mediaQuery(context, 'h', 130),
                                      width: mediaQuery(context, 'w', 487),
                                      decoration: BoxDecoration(
                                        borderRadius: BorderRadius.circular(20),
                                        border: Border.all(
                                          color: Color(0xFF999C9D),
                                          width: 0.5,
                                        ),
                                        color: Colors.white,
                                      ),
                                      child: GestureDetector(
                                        onTap: () async {
                                          DateTime newDate =
                                              await showRoundedDatePicker(
                                            context: context,
                                            initialDate: dateCreate != ""
                                                ? DateTime.parse(dateCreate)
                                                : DateTime.now(),
                                            firstDate: DateTime(
                                                DateTime.now().year - 10),
                                            lastDate: DateTime(
                                                DateTime.now().year + 10),
                                            locale: Locale('th', 'TH'),
                                            era: EraMode.BUDDHIST_YEAR,
                                            theme: ThemeData(
                                                primarySwatch: Colors.deepPurple),
                                            height: 280,
                                          );
                                          if (newDate != null) {
                                            setState(() {
                                              print(newDate);
                                              var dtArray =
                                                  newDate.toString().split(" ");
                                              setState(() {
                                                var formatter = DateFormat.yMd();
                                                var showDate = formatter
                                                    .formatInBuddhistCalendarThai(
                                                        newDate);
                                                date.text = showDate;
                                                dateCreate = dtArray[0];
                                              });
                                            });
                                          }
                                        },
                                        child: Container(
                                          height: mediaQuery(context, 'h', 105),
                                          width: mediaQuery(context, 'w', 490),
                                          padding: EdgeInsets.only(
                                            left: mediaQuery(context, 'h', 20),
                                            right: mediaQuery(context, 'h', 20),
                                          ),
                                          decoration: BoxDecoration(
                                            borderRadius: BorderRadius.all(
                                              Radius.circular(
                                                mediaQuery(
                                                  context,
                                                  'h',
                                                  150,
                                                ),
                                              ),
                                            ),
                                            border: Border.all(
                                              color: Colors.grey[500],
                                            ),
                                            color: Colors.white,
                                          ),
                                          child: Row(
                                            mainAxisAlignment:
                                                MainAxisAlignment.spaceBetween,
                                            children: <Widget>[
                                              Text(date.text),
                                              Icon(
                                                Icons.calendar_today,
                                                color: Colors.grey,
                                                size: mediaQuery(
                                                  context,
                                                  'h',
                                                  80,
                                                ),
                                              ),
                                            ],
                                          ),
                                        ),
                                      ),
                                    )
                                  ],
                                ),
                                Column(
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  children: <Widget>[
                                    Text(
                                      'เวลา :',
                                      textAlign: TextAlign.center,
                                      style: TextStyle(
                                        fontSize: mediaQuery(context, 'h', 34),
                                        color: Color(0xFF383838),
                                      ),
                                    ),
                                    Container(
                                      height: mediaQuery(context, 'h', 130),
                                      width: mediaQuery(context, 'w', 487),
                                      decoration: BoxDecoration(
                                        borderRadius: BorderRadius.circular(20),
                                        border: Border.all(
                                          color: Color(0xFF999C9D),
                                          width: 0.5,
                                        ),
                                        color: Colors.white,
                                      ),
                                      child: GestureDetector(
                                        onTap: () async {
                                          TimeOfDay newTime =
                                              await showTimePicker(
                                            context: context,
                                            initialTime: time.text != ""
                                                ? TimeOfDay(
                                                    hour: CheckTime.getHour(time),
                                                    minute:
                                                        CheckTime.getMin(time))
                                                : TimeOfDay.now(),
                                            builder: (context, child) {
                                              return Container(
                                                child: Column(children: <Widget>[
                                                  MediaQuery(
                                                      data: MediaQuery.of(context)
                                                          .copyWith(
                                                              alwaysUse24HourFormat:
                                                                  true),
                                                      child: child),
                                                  Theme(
                                                    data: Theme.of(context)
                                                        .copyWith(
                                                      primaryColor:
                                                          AppColors.color,
                                                      accentColor:
                                                          AppColors.color_gold,
                                                      colorScheme:
                                                          ColorScheme.light(
                                                        primary: AppColors.color,
                                                      ),
                                                      buttonTheme:
                                                          ButtonThemeData(
                                                        textTheme: ButtonTextTheme
                                                            .primary,
                                                      ),
                                                    ),
                                                    child: Container(
                                                      height: 0,
                                                      width: 0,
                                                      child: child,
                                                    ),
                                                  ),
                                                ]),
                                              );
                                            },
                                          );
                                          if (newTime != null) {
                                            String hour = newTime.hour.toString();
                                            String min =
                                                newTime.minute.toString();
                                            var times = AppConvert.fillZeroTime(
                                                newTime, hour, min);
                                            setState(() {
                                              time.text = times;
                                            });
                                          }
                                        },
                                        child: Container(
                                          height: mediaQuery(context, 'h', 105),
                                          width: mediaQuery(context, 'w', 490),
                                          padding: EdgeInsets.only(
                                            left: mediaQuery(context, 'h', 20),
                                            right: mediaQuery(context, 'h', 20),
                                          ),
                                          decoration: BoxDecoration(
                                            borderRadius: BorderRadius.all(
                                              Radius.circular(
                                                mediaQuery(
                                                  context,
                                                  'h',
                                                  150,
                                                ),
                                              ),
                                            ),
                                            border: Border.all(
                                              color: Colors.grey[500],
                                            ),
                                            color: Colors.white,
                                          ),
                                          child: Row(
                                            mainAxisAlignment:
                                                MainAxisAlignment.spaceBetween,
                                            children: <Widget>[
                                              Text(time.text),
                                              Icon(
                                                Icons.access_time,
                                                color: Colors.grey,
                                                size: mediaQuery(
                                                  context,
                                                  'h',
                                                  80,
                                                ),
                                              ),
                                            ],
                                          ),
                                        ),
                                      ),
                                    )
                                  ],
                                ),
                              ],
                            ),
                            SizedBox(
                              height: mediaQuery(context, 'h', 50),
                            ),
                            Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: <Widget>[
                                Text(
                                  'การดำเนินงาน :',
                                  textAlign: TextAlign.center,
                                  style: TextStyle(
                                    fontSize: mediaQuery(context, 'h', 34),
                                    color: Color(0xFF383838),
                                  ),
                                ),
                                Card(
                                  color: Colors.white,
                                  child: Padding(
                                    padding: EdgeInsets.all(
                                      mediaQuery(context, 'h', 40),
                                    ),
                                    child: TextField(
                                      controller: operation,
                                      maxLines: 8,
                                      style: TextStyle(
                                        fontSize: mediaQuery(context, 'h', 36),
                                        color: Color(0xFF707070),
                                      ),
                                      decoration: InputDecoration.collapsed(
                                        hintText: "",
                                      ),
                                    ),
                                  ),
                                ),
                              ],
                            ),
                            SizedBox(
                              height: mediaQuery(context, 'h', 50),
                            ),
                            Container(
                              //บันทึกการดำเนินการ
                              width: mediaQuery(context, 'w', 1005),
                              height: mediaQuery(context, 'h', 150),
                              child: Row(
                                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                children: <Widget>[
                                  Container(
                                    width: mediaQuery(context, 'w', 487),
                                    child: RaisedButton(
                                      color: Color(0xFFF2F5F7),
                                      onPressed: () {
                                        //saveFeedback();
                                        Navigator.of(context).pop(false);
                                      },
                                      shape: RoundedRectangleBorder(
                                        borderRadius: BorderRadius.circular(
                                          mediaQuery(context, 'h', 90),
                                        ),
                                        side: BorderSide(color: AppColors.color),
                                      ),
                                      child: Text(
                                        'ยกเลิก',
                                        style: TextStyle(
                                          color: AppColors.color,
                                          fontSize: mediaQuery(context, 'h', 50),
                                        ),
                                      ),
                                    ),
                                  ),
                                  Container(
                                    width: mediaQuery(context, 'w', 487),
                                    child: RaisedButton(
                                      color: AppColors.color,
                                      onPressed: () {
                                        print("-- Save History --");
                                        saveWorkHistory(context);
                                      },
                                      shape: RoundedRectangleBorder(
                                        borderRadius: BorderRadius.circular(
                                          mediaQuery(context, 'h', 90),
                                        ),
                                      ),
                                      child: Text(
                                        'บันทึก',
                                        style: TextStyle(
                                          color: Colors.white,
                                          fontSize: mediaQuery(context, 'h', 50),
                                        ),
                                      ),
                                    ),
                                  ),
                                ],
                              ),
                            ),
                          ],
                        ),
                      ), //Container แดง
                    ), // Card สุดที่นี่
                    SizedBox(
                      height: mediaQuery(context, 'h', 50),
                    ),
                    Text(
                      'ประวัติการดำเนินการ',
                      textAlign: TextAlign.center,
                      style: TextStyle(
                        fontSize: mediaQuery(context, 'h', 60),
                        color: Color(0xFF383838),
                      ),
                    ),
                    SizedBox(
                      height: mediaQuery(context, 'h', 80),
                    ),
                    Column(
                        children:
                            List.generate(PackageRequestHistory.data.length, (i) {
                      return _buildCard(
                        context,
                        PackageRequestHistory.data[i].createDate,
                        PackageRequestHistory.data[i].pHDescreption,
                        PackageRequestHistory.data[i].createBy,
                        PackageRequestHistory.data[i].pRId,
                        PackageRequestHistory?.data[i].statusType,
                        PackageRequestHistory?.data[i].id,
                      );
                    }))
                  ],
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  _widgetOfferCustomer(context, width) {
    return actionCancel
        ? Card(
            color: Colors.white,
            child: Padding(
              padding: EdgeInsets.all(
                mediaQuery(context, 'h', 40),
              ),
              child: TextField(
                controller: requestCus,
                maxLines: 8,
                style: TextStyle(
                  fontSize: mediaQuery(context, 'h', 36),
                  color: Color(0xFF707070),
                ),
                decoration: InputDecoration.collapsed(hintText: ""),
              ),
            ),
          )
        : Card(
            color: Colors.white70,
            child: Padding(
              padding: EdgeInsets.all(
                mediaQuery(context, 'h', 40),
              ),
              child: SizedBox(
                width: width,
                height: 136,
                child: Container(
                  child: Text(
                    prDescription,
                    style: TextStyle(fontSize: 11, color: Colors.grey[800]),
                  ),
                ),
              ),
            ),
          );
  }

  _editButton(context) {
    return Container(
      //ปุ่มบันทึก แก้ไข ความต้องการลูกค้า
      width: mediaQuery(context, 'w', 150),
      height: mediaQuery(context, 'h', 90),
      alignment: Alignment.center,
      child: RaisedButton(
        color: AppColors.color,
        onPressed: () {
          setState(() {
            print("Edit");
            requestCus.text = prDescription;
            actionEdit = true;
            actionCancel = true;
          });
        },
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(
            mediaQuery(context, 'h', 90),
          ),
        ),
        child: Icon(
          Icons.edit,
          color: Colors.white,
          size: 21,
        ),
      ),
    );
  }
  
  _buildTextMenuTwoColumn(context, text_1, text_2, width) {
    return Row(
      mainAxisAlignment: MainAxisAlignment.start,
      children: <Widget>[
        _buildTextMenu(context, text_1),
        SizedBox(
          width: mediaQuery(context, "w", width),
        ),
        _buildTextMenu(context, text_2),
      ],
    );
  }

  _buildTextMenu(context, text) {
    return Row(
      mainAxisAlignment: MainAxisAlignment.start,
      children: <Widget>[
        Text(
          text + " :",
          style: TextStyle(
              fontSize: mediaQuery(context, 'h', AppFontSize.label),
              color: AppColors.Black),
          textAlign: TextAlign.center,
        ),
      ],
    );
  }

  _buildDropDownRow(context) {
    return Container(
      height: mediaQuery(context, 'h', 130),
      width: mediaQuery(context, 'w', 1005),
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(20),
        border: Border.all(
          color: Color(0xFF999C9D),
          width: 0.5,
        ),
        color: Colors.white,
      ),
      child: Container(
        margin: EdgeInsets.only(
          left: mediaQuery(context, 'w', 25),
        ),
        child: DropdownButton<String>(
          value: valueAction,
          icon: Icon(Icons.expand_more),
          iconSize: 30,
          elevation: 16,
          style: TextStyle(color: AppColors.Black),
          underline: SizedBox(),
          items: _dropdownAction
              .map(
                (data) => DropdownMenuItem<String>(
                  child: Container(
                    child: Text(
                      data.value,
                      style: TextStyle(
                        fontSize: mediaQuery(context, "h", 50),
                      ),
                      textScaleFactor: 0.7,
                    ),
                  ),
                  value: data.key.toString(),
                ),
              )
              .toList(),
          isExpanded: true,
          onChanged: (String value) {
            setState(() {
              valueAction = value;
              print(valueAction);
            });
          },
        ),
      ),
    );
  }

  _buildCard(context, date, detail, name, prid, statType, id) {
    return Container(
      width: mediaQuery(context, 'w', 1005),
      //height: mediaQuery(context, 'h', 700),
      //height: mediaQuery(context, 'h', 800),
      padding: EdgeInsets.only(
        left: mediaQuery(context, 'w', 35),
        top: mediaQuery(context, 'h', 30),
      ),
      child: Column(
        children: <Widget>[
          Container(
            width: mediaQuery(context, 'w', 1005),
            height: mediaQuery(context, 'h', 120),
            padding: EdgeInsets.only(
              left: mediaQuery(context, 'w', 35),
              top: mediaQuery(context, 'h', 30),
            ),
            decoration: BoxDecoration(
              borderRadius: BorderRadius.only(
                topLeft: Radius.circular(
                  mediaQuery(context, 'h', 50),
                ),
                topRight: Radius.circular(
                  mediaQuery(context, 'h', 50),
                ),
              ),
              color: AppColors.color_gold,
            ),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              crossAxisAlignment: CrossAxisAlignment.start,
              children: <Widget>[
                Text(
                  'วันที่ ' + AppConvert.dateTimeThai(date) + " น.",
                  style: TextStyle(
                    color: Colors.white,
                    fontSize: mediaQuery(context, 'h', 40),
                    fontWeight: FontWeight.bold,
                  ),
                ),
                InkWell(
                  onTap: () async {
                    var isConfirm = await alertConfirm(
                        context, "แจ้งเตือน", "ลบบันทึกการดำเนินการ");
                    print("isConfirm  = $isConfirm");
                    if (isConfirm) {
                      setState(() {
                        isLoading = true;
                      });
                      deleteHistory(context, id);
                      await Future.delayed(const Duration(milliseconds: 2000));
                      setState(() {
                        isLoading = false;
                      });
                    }
                  },
                  child: Padding(
                    padding: const EdgeInsets.only(right: 10),
                    child: Icon(
                      Icons.delete_forever,
                      color: Colors.white,
                      size: 20,
                    ),
                  ),
                ),
              ],
            ),
          ),
          Container(
            width: mediaQuery(context, 'w', 1005),
            //height: mediaQuery(context, 'h', 400),
            //height: mediaQuery(context, 'h', 300),
            padding: EdgeInsets.fromLTRB(
              mediaQuery(context, 'w', 40),
              mediaQuery(context, 'h', 60),
              mediaQuery(context, 'w', 40),
              mediaQuery(context, 'h', 60),
            ),
            decoration: BoxDecoration(
              borderRadius: BorderRadius.only(
                bottomLeft: Radius.circular(
                  mediaQuery(context, 'h', 40),
                ),
                bottomRight: Radius.circular(
                  mediaQuery(context, 'h', 40),
                ),
              ),
              boxShadow: [
                appShadow(),
              ],
              color: Colors.white,
            ),
            child: Column(
              children: <Widget>[
                Row(
                    mainAxisAlignment: MainAxisAlignment.start,
                    children: <Widget>[
                      Text(
                        detail,
                        style: TextStyle(
                          color: Color(0xFF383838),
                          fontSize: mediaQuery(context, 'h', 36),
                        ),
                      ),
                    ]),
                Container(
                  margin: EdgeInsets.only(
                    top: mediaQuery(context, 'h', 35),
                    bottom: mediaQuery(context, 'h', 35),
                  ),
                  width: mediaQuery(context, 'w', 940),
                  height: mediaQuery(context, 'h', 0.8),
                  //height: mediaQuery(context, 'h', 0.8),
                  color: Color(0xFFC6C6C6),
                ),
                Row(
                  mainAxisAlignment: MainAxisAlignment.end,
                  children: <Widget>[
                    Text(
                      'ผู้บันทึก',
                      style: TextStyle(
                        color: AppColors.color_gold,
                        fontSize: mediaQuery(context, 'h', 36),
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                    Text(
                      ' : ',
                      style: TextStyle(
                        color: AppColors.color_gold,
                        fontSize: mediaQuery(context, 'h', 36),
                      ),
                    ),
                    Text(
                      name,
                      style: TextStyle(
                        color: AppColors.color_gold,
                        fontSize: mediaQuery(context, 'h', 36),
                      ),
                    ),
                  ],
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  saveListRequest(context) async {
    // บันทึกประวัติการดำเนินการ
    if (await checkForm([
      requestCus.text, // ความต้องการลูกค้า
      valueAction.split("|")[1], // สถานะการดำเนินการ
      date.text, // วันที่
      time.text, // เวลา
      operation.text, // การดำเนินการ
    ])) {
      Map<String, dynamic> data = {
        "EmployeeID": AppStrings.userID,
        "PackagesID": "4df7b5c8-f643-4936-baff-9fb69671c07a",
        "Packagename": "020000039829",
        "Status": "บริการล้างลุกถ้วย",
        "Requirement": requestCus.text,
        "PackageDate": dateCreate + " " + time.text,
        "PackageDetial": operation.text,
        "AuthenKey": AppUrl.AuthenKey
      };

      PackageRequest.saveData(context, data);
    } else {
      alertForm(context, "แจ้งเตือน", "กรอกข้อมูลไม่ครบ");
    }
  }

  saveWorkHistory(context) async {
    if (operation.text.isNotEmpty &&
        dateCreate.isNotEmpty &&
        time.text.isNotEmpty) {
      Map<String, dynamic> data = {
        "PR_Id": AppUrl.PR_Id,
        "CA": AppUrl.CA,
        "P_StatusType": valueAction,
        "PH_Descreption": operation.text,
        "CreateBy": AppUrl.userName,
        "CreateDate": dateCreate + " " + time.text,
        "AutoPushBack": "false",
        "AuthenKey": AppUrl.AuthenKey
      };
      print(data);
      setState(() {
        operation.text = "";
      });
      loadData();
      await PackageRequestHistory.saveData(context, data);
      loadHistory();
    } else {
      alertForm(context, "แจ้งเตือน", "กรอกข้อมูลไม่ครบ");
    }
  }

  _buildTextFieldTwoColumnStart(context, TextEditingController startDataText,
      TextEditingController time) {
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceEvenly,
      children: <Widget>[
        Container(
          height: mediaQuery(context, 'h', 105),
          width: mediaQuery(context, 'w', 490),
          child: GestureDetector(
            onTap: () async {
              DateTime newDate = await showRoundedDatePicker(
                context: context,
                initialDate: strStartDate != "" ?
                  DateTime.parse(strStartDate) : DateTime.now(),
                firstDate: DateTime(DateTime.now().year - 10),
                lastDate: DateTime(DateTime.now().year + 10),
                locale: Locale('th', 'TH'),
                era: EraMode.BUDDHIST_YEAR,
                theme: ThemeData(primarySwatch: Colors.deepPurple),
                height: 280,
                textActionButton: "ลบวันที่และเวลา",
                  onTapActionButton: (){
                    setState(() {
                      startDataText.clear();
                      startTimeText.clear();
                      strStartDate = "";
                    });
                },
              );
              if (newDate != null) {
                var dtArray = newDate.toString().split(" ");
                setState(() {
                  var formatter = DateFormat.yMd();
                  var showDate =
                      formatter.formatInBuddhistCalendarThai(newDate);
                  startDataText.text = showDate;
                  strStartDate = dtArray[0];
                  print("Start Date Bud : " + startDataText.text);
                  print("Start Date : " + strStartDate.toString());
                });
              }
            },
            child: Container(
              height: mediaQuery(context, 'h', 105),
              width: mediaQuery(context, 'w', 490),
              padding: EdgeInsets.only(
                left: mediaQuery(context, 'h', 20),
                right: mediaQuery(context, 'h', 20),
              ),
              decoration: BoxDecoration(
                borderRadius: BorderRadius.all(
                  Radius.circular(
                    mediaQuery(
                      context,
                      'h',
                      150,
                    ),
                  ),
                ),
                border: Border.all(
                  color: Colors.grey[500],
                ),
                color: Colors.white,
              ),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: <Widget>[
                  Text(startDataText.text),
                  Icon(
                    Icons.calendar_today,
                    color: Colors.grey,
                    size: mediaQuery(
                      context,
                      'h',
                      80,
                    ),
                  ),
                ],
              ),
            ),
          ),
        ),
        Container(
          height: mediaQuery(context, 'h', 105),
          width: mediaQuery(context, 'w', 490),
          child: GestureDetector(
            onTap: () async {
              TimeOfDay newTime = await showTimePicker(
                context: context,
                initialTime: startTimeText.text != "" ? 
                TimeOfDay(hour: CheckTime.getHour(startTimeText), minute: CheckTime.getMin(startTimeText),) : 
                TimeOfDay.now(),
                builder: (context, child) {
                  return Column(children: <Widget>[
                    MediaQuery(
                        data: MediaQuery.of(context)
                            .copyWith(alwaysUse24HourFormat: true),
                        child: child),
                    Theme(
                      data: Theme.of(context).copyWith(
                        primaryColor: AppColors.color,
                        accentColor: AppColors.color_gold,
                        colorScheme: ColorScheme.light(
                          primary: AppColors.color,
                        ),
                        buttonTheme: ButtonThemeData(
                          textTheme: ButtonTextTheme.primary,
                        ),
                      ),
                      child: Container(
                        height: 0,
                        width: 0,
                        child: child,
                      ),
                    ),
                  ]);
                },
              );
              if (newTime != null) {
                String hour = newTime.hour.toString();
                String min = newTime.minute.toString();
                var time = AppConvert.fillZeroTime(newTime, hour, min);
                setState(() {
                  //time.text = "time";
                  startTimeText.text = time;
                  print("Start Time : " + startTimeText.text);
                });
              }
            },
            child: Container(
              height: mediaQuery(context, 'h', 105),
              width: mediaQuery(context, 'w', 490),
              padding: EdgeInsets.only(
                left: mediaQuery(context, 'h', 20),
                right: mediaQuery(context, 'h', 20),
              ),
              decoration: BoxDecoration(
                borderRadius: BorderRadius.all(
                  Radius.circular(
                    mediaQuery(
                      context,
                      'h',
                      150,
                    ),
                  ),
                ),
                border: Border.all(
                  color: Colors.grey[500],
                ),
                color: Colors.white,
              ),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: <Widget>[
                  Text(time.text),
                  Icon(
                    Icons.access_time,
                    color: Colors.grey,
                    size: mediaQuery(
                      context,
                      'h',
                      80,
                    ),
                  ),
                ],
              ),
            ),
          ),
        ),
      ],
    );
  }

  update() async {
    // บันทึกความต้องการลูกค้า
    if (requestCus.text == "") {
      alertForm(context, "แจ้งเตือน", "กรุณาระบุความต้องการของลูกค้า");
      return;
    }
    if (await checkForm([
      requestCus.text,
    ])) {
      setState(() {
        isLoading = true;
      });
      Map<String, dynamic> data = {
        "PR_Id": AppUrl.PR_Id,
        "P_Id": AppUrl.P_Id,
        "CA": AppUrl.CA,
        "PR_StatusType": int.parse(valueAction),
        "CreateBy": PackageRequest.data[0]?.createBy,
        "PR_Descreption": requestCus.text,
        "AutoPushBack": "false",
        "AppointmentDate": strStartDate + " " + startTimeText.text,
        "EmployeeID": NotificationCount.getPrefString('EmployeeID'), 
        "P_Name" : packName,
        "AuthenKey": AppUrl.AuthenKey,
      };

      String pName = packName;
      String employeeId = NotificationCount.getPrefString('EmployeeID');
      print(data);
      bool ret = await PackageRequest.updateDataNoPushBack(
          context,
          AppUrl.PR_Id,
          AppUrl.P_Id,
          AppUrl.CA,
          valueAction,
          PackageRequest.data[0]?.createBy,
          requestCus.text,
          strStartDate,
          startTimeText.text,
          employeeId,
          pName
        );
      if (ret) {
        await Future.delayed(const Duration(milliseconds: 1000));
        this.loadData();
      } else {
        // nothing
      }
    } else {
      alertForm(context, "แจ้งเตือน", "กรอกข้อมูลไม่ครบ");
    }
  }
} //class _ListRequestAdditionalState

class KeyValueModel {
  String key;
  String value;

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