import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.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/alert.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/screen.dart';
import 'package:mwf_app/service/url.dart';
import 'package:mwf_app/service/convert.dart';
import 'package:mwf_app/model/customer_relation.dart';
import 'package:mwf_app/model/location_type.dart';
import 'package:mwf_app/service/shadow.dart';
import 'package:mwf_app/model/activity_type.dart';
import 'package:buddhist_datetime_dateformat/buddhist_datetime_dateformat.dart';
import 'package:mwf_app/set2/activity_relationship.dart';

class AddActivity extends StatefulWidget {
  final customerRelationID;

  AddActivity(
    this.customerRelationID,
  );

  @override
  _AddActivityState createState() => _AddActivityState(
        this.customerRelationID,
      );
}

class _AddActivityState extends State<AddActivity> {
  String customerRelationID;
  bool chkList = false;
  String _radioValueID;
  String proposeTypename = "";
  String strStartDate = "";
  String strEndDate = "";
  String activityID = "";
  String customerID = "";
  _AddActivityState(
    this.customerRelationID,
  );

  TextEditingController subject = TextEditingController(); //เรื่อง
  TextEditingController startDate = TextEditingController(); // วันที่เริ่มต้น
  TextEditingController startTime = TextEditingController(); //เวลาที่เริ่มต้น
  TextEditingController endDate = TextEditingController(); //วันที่สิ้นสุด
  TextEditingController endTime = TextEditingController(); //เวลาที่สิ้นสุด
  TextEditingController peopleInvited =
      TextEditingController(); //จำนวนคนที่เชิญ
  TextEditingController peopleAttended =
      TextEditingController(); //จำนวนคนที่ร่วมงาน
  TextEditingController valueLocationType =
      TextEditingController(); //จำนวนคนที่ร่วมงาน

  bool isLoading = true;
  String valueActivityType = '';
  TextEditingController valueActivityName = TextEditingController();
  //String valueLocationType = '';

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

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

  @override
  void initState() {
    super.initState();
    Intl.defaultLocale = 'th';
    initializeDateFormatting();
    CustomerRelation.data = []; //clear data
    print("add_activity.dart");

    if (customerRelationID != null) {
      getDataEdit(context, customerRelationID).then((res) {
        setState(() {
          isLoading = false;
        });
      });
    } else {
      setState(() {
        peopleInvited.text = "0";
        peopleAttended.text = "0";
      });
    }

    loadDataActivityType().then((res) {
      setState(() {
        //_radioValue = 0;
        isLoading = false;
      });
    });
  }

  @override
  void dispose() {
    CustomerRelation.data.clear();
    super.dispose();
  }

  updateData() async {
    List chk = [
      // startDate.text,
      // startTime.text,
      // endDate.text,
      // endTime.text,
      peopleInvited.text,
      peopleAttended.text,
      valueActivityType,
      valueLocationType.text,
    ];

    var chkForm = await checkForm(chk);

    if (chkForm == false) {
      alertForm(context, "แจ้งเตือน", "กรอกข้อมูลไม่ครบ");
    } else {
      print(startDate.text + " -");
      print(strStartDate + " 00:00");
      print(endDate.text + " -");
      print(strEndDate + " 00:00");
      print(" people in : " + peopleInvited.text);
      print(" people att : " + peopleAttended.text);
      print(" activity : " + activityID);
      print(" customerRelationID : " + customerRelationID);
      print(" Location : " + valueLocationType.text);
      print(" Customer id : " + AppUrl.CustomerID.toString());
      CustomerRelation.updateData(
        context,
        customerRelationID,
        activityID,
        peopleInvited.text,
        peopleAttended.text,
      );
    }
  }

  getDataEdit(context, customerRelationID) async {
    try {
      print(customerRelationID);
      var list = await CustomerRelation.getDataEdit(
          context, customerRelationID); // ไปเรียกฟังชั่นดึงข้อมูลจาก api
      var dataList;
      setState(() {
        CustomerRelation.data.clear();
        dataList = CustomerRelation.fromJson(list);
        CustomerRelation.data.add(dataList); // loop เก็บข้อมูล
      });
      subject.text = CustomerRelation.data[0].activityName;
      startDate.text = CustomerRelation.data[0].startDate == "" ? "" : CustomerRelation.data[0].startDate.split(" ")[0];
      startTime.text = CustomerRelation.data[0].startDate == "" ? "" : CustomerRelation.data[0].startDate.split(" ")[1];
      endDate.text = CustomerRelation.data[0].endDate  == "" ? "" : CustomerRelation.data[0].endDate.split(" ")[0];
      endTime.text = CustomerRelation.data[0].endDate == "" ? "" : CustomerRelation.data[0].endDate.split(" ")[1];
      valueLocationType.text = CustomerRelation.data[0].location;
      valueActivityType = valueActivityType =
          CustomerRelation.data[0].activityTypeId.toString() +
              "|" +
              CustomerRelation.data[0].activityTypeName.toString();
      valueActivityName.text =
          CustomerRelation.data[0].activityTypeName.toString();
      peopleAttended.text =
          CustomerRelation.data[0].numberofPeopleAttending.toString();
      peopleInvited.text = CustomerRelation.data[0].numberofPeopleInvite;
      activityID = CustomerRelation.data[0].activityId.toString();

    } catch (e) {
      print(e);
      print("getData_Edit Error");
    }
  }

  loadDataActivityType() async {
    final listActivityType =
        await ActivityType.getData(); // ไปเรียกฟังชั่นดึงข้อมูลจาก api

    for (var i = 0; i < listActivityType.length; i++) {
      setState(() {
        _dropdownAct.add(
          KeyValueModel(
            key: listActivityType[i]['ActivityType']
                .toString(), // key คือค่าที่แสดง
            value: listActivityType[i]['ActivityId'].toString() +
                '|' +
                listActivityType[i]['ActivityType']
                    .toString(), // value ค่าที่บันทึก
          ),
        );
      });
    }

    setState(() {
      listActivityType.forEach((v) {
        final activityTypeList = ActivityType.fromJson(v);
        ActivityType.data.add(activityTypeList); // loop เก็บข้อมูล
      });
    });

    final listLocationType =
        await LocationType.getData(); // ไปเรียกฟังชั่นดึงข้อมูลจาก api

    return "xx";
  }
  //===============================================================================================
  //                                      Radio Button
  //===============================================================================================

  _buildRadio(String customerRelationshipActivityId) {
    //CustomerRelation.data[index].customerRelationshipActivityId
    return SizedBox(
      child: Row(
        children: <Widget>[
          Radio(
            value: customerRelationshipActivityId,
            groupValue: _radioValueID,
            onChanged: (value) {
              //print(customerRelationshipActivityId);
              setState(() {
                _radioValueID = value;
              });
            },
          ),
        ],
      ),
    );
  }

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

    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(
//            color: Colors.teal,
              width: _width,
              height: mediaQuery(context, 'h', 1250),
              margin: EdgeInsets.only(
                top: mediaQuery(context, 'h', 950),
                left: mediaQuery(context, 'w', 60),
                right: mediaQuery(context, 'w', 60),
              ),
              child: SingleChildScrollView(
                child: Column(
                  children: <Widget>[
                    Container(
                      alignment: Alignment.center,
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: <Widget>[
                          Text(
                            'ค้นหากิจกรรมที่จะเข้าร่วม',
                            style: TextStyle(
                              color: Color(0xFFB58E38),
                              fontSize: mediaQuery(context, 'h', 58),
                            ),
                          ),
                        ],
                      ),
                    ),
                    _buildTextMenu(context, "เรื่อง :"), //แก้คอมเม้น
                    _buildSizeBox(context),
                    customerRelationID != null
                        ? _buildRowDisable(context, subject)
                        : _buildRow(context, subject),
                    _buildSizeBox(context),
                    //_buildTextMenuTwoColumn(context, 'วันที่เริ่มต้น :', "เวลา :", 400.0),
                    _buildSizeBox(context),
                    //_buildTextFieldTwoColumnStart(context, startDate, endDate),
                    _buildSizeBox(context),
                    //_buildTextMenuTwoColumn(context, AppStrings.TaskList_EndDate,AppStrings.TaskList_time, 400.0),
                    // _buildSizeBox(context),
                    // _buildSizeBox(context),
                    //_buildTextFieldTwoColumnEnd(context, startDate, endDate),
                    customerRelationID != null
                        ? _buildTextTimeDisable(context, startDate, endDate)
                        : _buildDateTwoField(
                            context, startDate, endDate), // Disable for DateTime
                    _buildSizeBox(context),
                    if (customerRelationID != null)
                      _buildTextMenu(context, "สถานที"),
                    _buildSizeBox(context),
                    if (customerRelationID != null)
                      _buildRowDisable(context, valueLocationType),
                    // _buildDropDownLo(context),
                    _buildSizeBox(context),
                    _buildTextMenu(context, "ประเภทกิจกรรม :"),
                    _buildSizeBox(context),
                    customerRelationID != null
                        ? _buildDropDownActDisable(
                            context, valueActivityType, valueActivityName)
                        : _buildDropDownAct(context),
                    _buildSizeBox(context),
                    _buildSizeBox(context),
                    _buildSizeBox(context),

//===============================================================================================
//
//===============================================================================================
                    if (customerRelationID == null)
                      Column(
                        children: <Widget>[
                          if (customerRelationID == null)
                            if (customerRelationID != null)
                              _buildSizeBox(context),
                          if (customerRelationID != null) _buildSizeBox(context),
                          if (customerRelationID != null) _buildSizeBox(context),
                          GestureDetector(
                            onTap: () async {
                              setState(() {
                                search();
                              });
                            },
                            child: Container(
                              width: mediaQuery(context, 'w', 995),
                              height: mediaQuery(context, 'h', 150),
                              decoration: BoxDecoration(
                                borderRadius: BorderRadius.all(
                                  Radius.circular(
                                    mediaQuery(context, 'h', 100),
                                  ),
                                ),
                                boxShadow: [
                                  appShadow(),
                                ],
                                color: AppColors.color_gold,
                              ),
                              child: Center(
                                child: Text(
                                  'ค้นหา',
                                  textAlign: TextAlign.center,
                                  style: TextStyle(
                                    fontSize: mediaQuery(context, 'h', 50),
                                    color: Colors.white,
                                  ),
                                ),
                              ),
                            ),
                          ),

                          _buildSizeBox(context), //มันคือ CSS เว้นวรรค
                          _buildSizeBox(context), //มันคือ CSS เว้นวรรค
                          _buildSizeBox(context), //มันคือ CSS เว้นวรรค
                          _buildSizeBox(context),
                        ],
                      ), //มันคือ CSS เว้นวรรค
//===============================================================================================
//
//===============================================================================================
                    if (customerRelationID == null)
                      _buildListView(context), // Show result search
                    _buildSizeBox(context), //มันคือ CSS เว้นวรรค
                    _buildSizeBox(context), //มันคือ CSS เว้นวรรค
                    _buildTextMenuTwoColumn(context, 'จำนวนคนที่เชิญ :',
                        "จำนวนคนที่ร่วมงาน :", 400.0),
                    _buildSizeBox(context),
                    _buildTextFieldTwoColumnNoIcon(
                        context, peopleInvited, peopleAttended),
                    _buildSizeBox(context),
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                      children: <Widget>[
                        _buildButton(
                            context, "ยกเลิก", Colors.white, AppColors.color),
                        if (customerRelationID != null)
                          _buildButton(
                              context, "แก้ไข", AppColors.color, Colors.white),
                        if (customerRelationID == null)
                          _buildButton(
                              context, "บันทึก", AppColors.color, Colors.white),
                      ],
                    ),
//===============================================================================================
//
//===============================================================================================

                    Container(
                      height: 200,
                    ),
                  ],
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

//========================================================================================
//
//========================================================================================

  search() async {
    if (valueActivityType.isEmpty &&
        subject.text.isEmpty &&
        startDate.text.isEmpty &&
        endDate.text.isEmpty) {
      alertForm(context, "แจ้งเตือน", "กรุณาใส่เงื่อนไขในการค้นหากิจกรรม");
    } else {
      try {
        CustomerRelation.data.clear(); // clear data
        var monthStartDate;
        var yearStartDate;
        var monthEndDate;
        var yearEndDate;
        var listMonthDate;
        var listYearDate;
        var valueActivity =
            valueActivityType == "" ? "" : valueActivityType.split("|")[0];
        // print(valueActivity);
        // print(subject.text);
        bool acceptCondition = false;
        var resultSearch;
        var startDate;
        var endDate;
        if (strStartDate.isNotEmpty && strEndDate.isNotEmpty) {
          startDate = DateTime.parse(strStartDate);
          endDate = DateTime.parse(strEndDate);
          if ((startDate == endDate || startDate.isBefore(endDate))) {
            acceptCondition = true;
          } else {
            alertForm(context, "แจ้งเตือน",
                "กรุณาตรวจสอบ วันหรือเวลา เริ่มต้น และสิ้นสุดอีกครั้ง");
          }
        } else if (strStartDate.isNotEmpty && strEndDate.isEmpty) {
          startDate = DateTime.parse(strStartDate);
          strEndDate = DateTime.now().toString().substring(0, 10);
          acceptCondition = true;
        } else {
          acceptCondition = true;
        }

        if (acceptCondition) {
          setState(() {
            isLoading = true;
          });
          await Future.delayed(const Duration(seconds: 1));
          resultSearch = await CustomerRelation.getDataSearch(
              context,
              subject.text,
              valueActivity,
              strStartDate == ""
                  ? ""
                  : strStartDate +
                      "-" +
                      (startTime.text == "" ? "00:00:00" : startTime.text),
              strEndDate == ""
                  ? ""
                  : strEndDate +
                      "-" +
                      (endTime.text == "" ? "00:00:00" : endTime.text));
        }
        print("resultSearch: " + resultSearch.length.toString());
        if (resultSearch.isNotEmpty) {
          if (strStartDate.isNotEmpty && strEndDate.isNotEmpty) {
            monthStartDate =
                strStartDate != "" ? DateTime.parse(strStartDate).month : "";
            yearStartDate =
                strStartDate != "" ? DateTime.parse(strStartDate).year : "";

            monthEndDate =
                strEndDate != "" ? DateTime.parse(strEndDate).month : "";
            yearEndDate =
                strEndDate != "" ? DateTime.parse(strEndDate).year : "";
            setState(() {
              resultSearch.forEach((v) {
                final dataList = CustomerRelation.fromJson(v);
                listMonthDate =
                    DateTime.parse(dataList.relationshipActivityStartDate)
                        .month;
                listYearDate =
                    DateTime.parse(dataList.relationshipActivityStartDate).year;
                if (monthStartDate <= listMonthDate ||
                    yearEndDate >= listYearDate) {
                  CustomerRelation.data.add(dataList); // loop เก็บข้อมูล
                  CustomerRelation.data.sort(
                    (a, b) => a.relationshipActivityStartDate
                        .compareTo(b.relationshipActivityStartDate),
                  );
                }
              });
              print("resultafterSearch: " +
                  CustomerRelation.data.length.toString());
            });
            await Future.delayed(const Duration(seconds: 1));
            setState(() {
              isLoading = false;
            });
          } else {
            setState(() {
              resultSearch.forEach((v) {
                final dataList = CustomerRelation.fromJson(v);
                if (dataList.relationshipActivityStartDate != null)
                  CustomerRelation.data.add(dataList); // loop เก็บข้อมูล
                CustomerRelation.data.sort((a, b) => a
                    .relationshipActivityStartDate
                    .compareTo(b.relationshipActivityStartDate));
              });
              print("resultafterSearch: " +
                  CustomerRelation.data.length.toString());
            });
            await Future.delayed(const Duration(seconds: 1));
            setState(() {
              isLoading = false;
            });
          }
        } else {
          setState(() {
            isLoading = false;
          });
          print("resutl : " + resultSearch.toString());
          await Future.delayed(const Duration(seconds: 1));
          AppLoader.showInfo("ไม่พบข้อมูล");
        }
      } catch (e) {
        setState(() {
          isLoading = false;
        });
        await Future.delayed(const Duration(seconds: 1));
        AppLoader.showInfo("ไม่พบข้อมูล");
        print(e);
        //throw e;
      }
    }
  }

  //=====================================================================

  _buildButton(context, text, bgColor, fontColor) {
    return ButtonTheme(
      minWidth: mediaQuery(context, "w", 477),
      height: mediaQuery(context, "h", 120),
      child: FlatButton(
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(
            mediaQuery(context, "w", 50),
          ),
          side: BorderSide(color: AppColors.color),
        ),
        color: bgColor,
        textColor: Colors.red,
        padding: EdgeInsets.all(
          mediaQuery(context, "w", 10),
        ),
        onPressed: () {
          print(text);
          if (text == "บันทึก") {
            saveAct();
          } else if (text == "แก้ไข") {
            updateData();
          } else {
            Get.offAll(ActivityRelationship());
          }
        },
        child: Text(
          text,
          style: TextStyle(
            fontSize: 14.0,
            color: fontColor,
          ),
        ),
      ),
    );
  }

  //==================================================================================================
  //                                          Save Button
  //==================================================================================================
  saveAct() async {
    List chk = [
      peopleInvited.text,
      peopleAttended.text,
      _radioValueID,
    ];

    var chkForm = await checkForm(chk);

    if (chkForm == true) {
      print("Invite :: " + peopleInvited.text);
      print("Attend :: " + peopleAttended.text);
      print("ID :: " + _radioValueID.toString());
      final response = await CustomerRelation.saveData(
          context, _radioValueID, peopleInvited.text, peopleAttended.text);
      if (response.hashCode == 200) {
        loadDataActivityType().then((response) {
          setState(() {
            getDataEdit(context, customerRelationID);
            _radioValueID = "";
            isLoading = false;
          });
        });
      }
    } else {
      alertForm(context, "แจ้งเตือน", "กรอกข้อมูลไม่ครบ");
    }
  }

  _buildDropDownActDisable(context, values, valueName) {
    return Container(
      height: mediaQuery(context, 'h', 110),
      width: mediaQuery(context, 'w', 1005),
      child: TextField(
        controller: valueName == null ? "" : valueName,
        enabled: false,
        decoration: InputDecoration(
          border: OutlineInputBorder(
            borderRadius: const BorderRadius.all(
              const Radius.circular(50.0),
            ),
          ),
          filled: true,
          counterText: "",
          contentPadding: EdgeInsets.fromLTRB(10.0, 0.0, 20.0, 10.0),
          hintStyle: TextStyle(color: Colors.grey[800]),
          fillColor: Colors.grey[100],
        ),
        style: TextStyle(fontSize: 12),
      ),
    );
  }

  _buildDropDownAct(context) {
    return Row(
      mainAxisAlignment: MainAxisAlignment.center,
      children: <Widget>[
        Container(
          height: mediaQuery(context, 'h', 110),
          width: mediaQuery(context, 'w', 1005),
          padding: EdgeInsets.symmetric(horizontal: 10.0),
          decoration: BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.circular(53.0),
            border: Border.all(
                color: AppColors.color_border,
                style: BorderStyle.solid,
                width: 0.80),
          ),
          child: DropdownButtonHideUnderline(
            child: DropdownButton<String>(
              iconSize: 0,
              icon: Icon(Icons.keyboard_arrow_down),
              underline: SizedBox(),
              items: _dropdownAct
                  .map(
                    (data) => DropdownMenuItem<String>(
                      child: Container(
                        child: Text(
                          data.key,
                          style: TextStyle(
                            fontSize: mediaQuery(context, "h", 50),
                          ),
                          textScaleFactor: 0.7,
                        ),
                      ),
                      value: data.value,
                    ),
                  )
                  .toList(),
              isExpanded: true,
              onChanged: (String value) {
                setState(() {
                  valueActivityType = value;
                });
              },
              value: valueActivityType,
            ),
          ),
        ),
      ],
    );
  }

  _buildTextMenuTwoColumn(context, text_1, text_2, width) {
    return Row(
      mainAxisAlignment: MainAxisAlignment.start,
      children: <Widget>[
        _buildTextMenu(context, text_1),
        SizedBox(width: mediaQuery(context, "w", 320)),
        _buildTextMenu(context, text_2),
      ],
    );
  }

  _buildTextFieldTwoColumnNoIcon(context, TextEditingController controller1,
      TextEditingController controller2) {
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceEvenly,
      children: <Widget>[
        Container(
          height: mediaQuery(context, 'h', 105),
          width: mediaQuery(context, 'w', 490),
          child: Stack(
            children: <Widget>[
              TextField(
                keyboardType: TextInputType.number,
                inputFormatters: <TextInputFormatter>[
                  FilteringTextInputFormatter.digitsOnly
                ],
                controller: controller1,
                enabled: true,
                decoration: InputDecoration(
                  border: OutlineInputBorder(
                    borderRadius: const BorderRadius.all(
                      const Radius.circular(50.0),
                    ),
                  ),
                  filled: true,
                  hintStyle: TextStyle(color: Colors.grey[800]),
                  counterText: "",
                  contentPadding: EdgeInsets.fromLTRB(15.0, 0.0, 20.0, 10.0),
                  fillColor: Colors.white,
                ),
              ),
              GestureDetector(
                onTap: () {
                  print("Call calendar");
                },
                child: Container(
                  margin: EdgeInsets.only(
                    top: mediaQuery(context, 'h', 10),
                    left: mediaQuery(context, 'w', 400),
                  ),
                  child: Text("คน"),
                ),
              ),
            ],
          ),
        ),
        Container(
          height: mediaQuery(context, 'h', 105),
          width: mediaQuery(context, 'w', 490),
          child: Stack(
            children: <Widget>[
              TextField(
                keyboardType: TextInputType.number,
                inputFormatters: <TextInputFormatter>[
                  FilteringTextInputFormatter.digitsOnly
                ],
                controller: controller2,
                enabled: true,
                decoration: InputDecoration(
                  border: OutlineInputBorder(
                    borderRadius: const BorderRadius.all(
                      const Radius.circular(50.0),
                    ),
                  ),
                  filled: true,
                  hintStyle: TextStyle(color: Colors.grey[800]),
                  counterText: "",
                  contentPadding: EdgeInsets.fromLTRB(15.0, 0.0, 20.0, 10.0),
                  fillColor: Colors.white70,
                ),
              ),
              GestureDetector(
                onTap: () {
                  print("Call calendar");
                },
                child: Container(
                  margin: EdgeInsets.only(
                    top: mediaQuery(context, 'h', 10),
                    left: mediaQuery(context, 'w', 400),
                  ),
                  child: Text("คน"),
                ),
              ),
            ],
          ),
        ),
      ],
    );
  }

  _buildTextTimeDisable(
      context, TextEditingController startdate, TextEditingController enddate) {
    setState(() {
      strStartDate = startdate.text;
    });
    return Column(
      children: [
        _buildRowText(context, 'วันที่เริ่มต้น', 'วันที่สิ้นสุด'),
        Row(
          children: [
            Container(
              alignment: Alignment.centerLeft,
              height: mediaQuery(context, 'h', 100),
              width: mediaQuery(context, 'w', 490),
              child: TextField(
                controller: startdate == null ? "" : startdate,
                enabled: false,
                decoration: InputDecoration(
                  border: OutlineInputBorder(
                    borderRadius: const BorderRadius.all(
                      const Radius.circular(50.0),
                    ),
                  ),
                  filled: true,
                  counterText: "",
                  contentPadding: EdgeInsets.fromLTRB(10.0, 0.0, 20.0, 10.0),
                  hintStyle: TextStyle(color: Colors.grey[800]),
                  fillColor: Colors.grey[100],
                ),
              ),
            ),
            SizedBox(width: mediaQuery(context, "w", 20)),
            Container(
              height: mediaQuery(context, 'h', 100),
              width: mediaQuery(context, 'w', 490),
              child: TextField(
                controller: enddate == null ? "" : enddate,
                enabled: false,
                decoration: InputDecoration(
                  border: OutlineInputBorder(
                    borderRadius: const BorderRadius.all(
                      const Radius.circular(50.0),
                    ),
                  ),
                  filled: true,
                  counterText: "",
                  contentPadding: EdgeInsets.fromLTRB(10.0, 0.0, 20.0, 10.0),
                  hintStyle: TextStyle(color: Colors.grey[800]),
                  fillColor: Colors.grey[100],
                ),
              ),
            ),
          ],
        ),
      ],
    );
  }

  _buildDateTwoField(context, TextEditingController startdate,
      TextEditingController endtdate) {
    return Column(
      children: [
        _buildRowText(context, 'วันที่เริ่มต้น', 'วันที่สิ้นสุด'),
        Row(
          mainAxisAlignment: MainAxisAlignment.start,
          children: <Widget>[
            Container(
              height: mediaQuery(context, 'h', 105),
              width: mediaQuery(context, 'w', 490),
              child: Stack(
                children: <Widget>[
                  TextField(
                    controller: startDate,
                    enabled: false,
                    decoration: InputDecoration(
                      border: OutlineInputBorder(
                        borderRadius: const BorderRadius.all(
                          const Radius.circular(50.0),
                        ),
                      ),
                      filled: true,
                      hintStyle: TextStyle(color: Colors.grey[800]),
                      counterText: "",
                      contentPadding:
                          EdgeInsets.fromLTRB(15.0, 0.0, 20.0, 10.0),
                      fillColor: Colors.white70,
                    ),
                  ),
                  GestureDetector(
                    onTap: () async {
                      var date = await datePicker(context, "startDate");
                      print(date);
                      if (date != null) {
                        setState(() {
                          var formatter = DateFormat.yMd();
                          var showDate =
                              formatter.formatInBuddhistCalendarThai(date);
                          startDate.text = showDate;
                          strStartDate = date.toString().split(" ")[0];
                        });
                      }
                    },
                    child: Container(
                      margin: EdgeInsets.only(
                        top: mediaQuery(context, 'h', 10),
                        left: mediaQuery(context, 'w', 400),
                      ),
                      child: Icon(
                        Icons.calendar_today,
                        color: Colors.grey,
                      ),
                    ),
                  ),
                ],
              ),
            ),
            SizedBox(width: mediaQuery(context, "w", 20)),
            Container(
              height: mediaQuery(context, 'h', 105),
              width: mediaQuery(context, 'w', 490),
              child: Stack(
                children: <Widget>[
                  TextField(
                    controller: endDate,
                    enabled: false,
                    decoration: InputDecoration(
                      border: OutlineInputBorder(
                        borderRadius: const BorderRadius.all(
                          const Radius.circular(50.0),
                        ),
                      ),
                      filled: true,
                      hintStyle: TextStyle(color: Colors.grey[800]),
                      counterText: "",
                      contentPadding:
                          EdgeInsets.fromLTRB(15.0, 0.0, 20.0, 10.0),
                      fillColor: Colors.white70,
                    ),
                  ),
                  GestureDetector(
                    onTap: () async {
                      var date = await datePicker(context, "endDate");
                      print(date);
                      if (date != null) {
                        setState(() {
                          var formatter = DateFormat.yMd();
                          var showDate =
                              formatter.formatInBuddhistCalendarThai(date);
                          endDate.text = showDate;
                          strEndDate = date.toString().split(" ")[0];
                        });
                      }
                      print("Call calendar 3");
                    },
                    child: Container(
                      margin: EdgeInsets.only(
                        top: mediaQuery(context, 'h', 10),
                        left: mediaQuery(context, 'w', 400),
                      ),
                      child: Icon(
                        Icons.calendar_today,
                        color: Colors.grey,
                      ),
                    ),
                  ),
                ],
              ),
            ),
          ],
        ),
      ],
    );
  }

  _buildListView(context) {
    return Column(
      children: List.generate(CustomerRelation.data.length, (
        index,
      ) {
        return _buildContent(
          context,
          (index + 1).toString(),
          CustomerRelation.data[index].relationshipActivityName,
          (CustomerRelation.data[index].relationshipActivityStartDate == null
              ? ""
              : CustomerRelation.data[index].relationshipActivityStartDate),
          (CustomerRelation.data[index].relationshipActivityEndDate == null
              ? ""
              : CustomerRelation.data[index].relationshipActivityEndDate),
          CustomerRelation.data[index].relationshipActivityPlace,
          CustomerRelation.data[index].categoryRelationshipActivityName,
          CustomerRelation.data[index].relationshipActivityId,
        );
      }),
    );
  }

  datePicker(context, from) async {
    DateTime newDate = await showRoundedDatePicker(
      context: context,
      initialDate: from == "startDate"
          ? strStartDate == ""
              ? DateTime.now()
              : DateTime.parse(strStartDate)
          : strEndDate == ""
              ? DateTime.now()
              : DateTime.parse(strEndDate),
      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: (){
          if(from == "startDate"){
            setState(() {
              startDate.clear();
              strStartDate = "";
            });
          } else {
            setState(() {
              endDate.clear();
              strEndDate = "";
            });
          }
      },
    );
    return newDate;
  }

  timePicker() async {
    TimeOfDay newTime = await showTimePicker(
      context: context,
      initialTime: TimeOfDay.now(),
      builder: (context, child) {
        return 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: 450,
            width: 700,
            child: child,
          ),
        );
      },
    );

    return newTime.hour.toString() + ":" + newTime.minute.toString();
  }

  _buildRow(context, TextEditingController controller) {
    return Container(
      height: mediaQuery(context, 'h', 110),
      width: mediaQuery(context, 'w', 1005),
      child: TextField(
        controller: controller,
        enabled: true,
        decoration: InputDecoration(
          border: OutlineInputBorder(
            borderRadius: const BorderRadius.all(
              const Radius.circular(50.0),
            ),
          ),
          filled: true,
          counterText: "",
          contentPadding: EdgeInsets.fromLTRB(10.0, 0.0, 20.0, 10.0),
          hintStyle: TextStyle(color: Colors.grey[800]),
          fillColor: Colors.white70,
        ),
      ),
    );
  }

  _buildRowDisable(context, TextEditingController controller) {
    return Container(
      height: mediaQuery(context, 'h', 110),
      width: mediaQuery(context, 'w', 1005),
      child: TextField(
        controller: controller == null ? "" : controller,
        enabled: false,
        decoration: InputDecoration(
          border: OutlineInputBorder(
            borderRadius: const BorderRadius.all(
              const Radius.circular(50.0),
            ),
          ),
          filled: true,
          counterText: "",
          contentPadding: EdgeInsets.fromLTRB(10.0, 0.0, 20.0, 10.0),
          hintStyle: TextStyle(color: Colors.grey[800]),
          fillColor: Colors.grey[100],
        ),
        style: TextStyle(fontSize: 12),
      ),
    );
  }

  _buildSizeBox(context) {
    return SizedBox(
      height: mediaQuery(context, "h", 15),
    );
  }

  _buildBoxWidth(context) {
    return SizedBox(
      width: mediaQuery(context, "w", 400),
    );
  }

  _buildRowText(context, startday, endday) {
    return Row(children: [
      Text(
        startday,
        style: TextStyle(
            fontSize: mediaQuery(context, 'h', 30), color: AppColors.Black),
      ),
      _buildBoxWidth(context),
      Text(
        endday,
        style: TextStyle(
            fontSize: mediaQuery(context, 'h', 30), color: AppColors.Black),
      ),
    ]);
  }

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

  //===============================================================================================
  //                                      Search Result
  //===============================================================================================

  _buildContent(
    context,
    number,
    subject,
    startDate,
    endDate,
    place,
    type,
    String customerRelationID,
  ) {
    return Container(
      width: mediaQuery(context, 'w', 1005),
      //height: mediaQuery(context, 'h', 500),
      padding: EdgeInsets.all(
        mediaQuery(context, 'h', 50),
      ),
      margin: EdgeInsets.only(
        bottom: mediaQuery(context, 'h', 40),
      ),
      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', 760),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: <Widget>[
                Row(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: <Widget>[
                    Text(
                      'ลำดับ : ',
                      style: TextStyle(
                        color: AppColors.color_text,
                        fontSize: mediaQuery(context, 'h', 42),
                      ),
                    ),
                    Flexible(
                      child: 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(
                        subject == null ? "" : subject,
                        style: TextStyle(
                          color: AppColors.color_text,
                          fontSize: mediaQuery(context, 'h', 40),
                        ),
                      ),
                    ),
                  ],
                ),
                Row(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: <Widget>[
                    Text(
                      'วันเวลาเริ่ม : ',
                      style: TextStyle(
                        color: AppColors.color_text,
                        fontSize: mediaQuery(context, 'h', 42),
                      ),
                    ),
                    Flexible(
                      child: Text(
                        startDate == ""
                            ? ""
                            : AppConvert.dateTimeConvert(startDate.toString()) +
                                " น.",
                        style: TextStyle(
                          color: AppColors.color_text,
                          fontSize: mediaQuery(context, 'h', 40),
                        ),
                      ),
                    ),
                  ],
                ),
                Row(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: <Widget>[
                    Text(
                      '             : ',
                      style: TextStyle(
                        color: AppColors.color_text,
                        fontSize: mediaQuery(context, 'h', 42),
                      ),
                    ),
                    Flexible(
                      child: Text(
                        endDate == ""
                            ? ""
                            : AppConvert.dateTimeConvert(endDate.toString()) +
                                " น.",
                        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(
                        place == null ? "" : place,
                        style: TextStyle(
                          color: AppColors.color_text,
                          fontSize: mediaQuery(context, 'h', 40),
                        ),
                      ),
                    ),
                  ],
                ),
                Row(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: <Widget>[
                    Text(
                      'กิจกรรม : ',
                      style: TextStyle(
                        color: AppColors.color_text,
                        fontSize: mediaQuery(context, 'h', 42),
                      ),
                    ),
                    Flexible(
                      child: Text(
                        type == null ? "" : type,
                        style: TextStyle(
                          color: AppColors.color_text,
                          fontSize: mediaQuery(context, 'h', 40),
                        ),
                      ),
                    ),
                  ],
                ),
              ],
            ),
          ),
          _buildRadio(customerRelationID),
        ],
      ),
    );
  }
} //class

class KeyValueModel {
  String key;
  String value;

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