import 'package:flutter/material.dart';
import 'package:get/get.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/loader.dart';
import 'package:mwf_app/model/history_contact.dart';
import 'package:flutter/cupertino.dart';
import 'package:intl/date_symbol_data_local.dart';
import 'package:intl/intl.dart';
import 'package:mwf_app/service/url.dart';
import 'package:buddhist_datetime_dateformat/buddhist_datetime_dateformat.dart';
import 'package:flutter_rounded_date_picker/rounded_picker.dart';
import 'package:mwf_app/set7/contact_user.dart';

class ContactUserEdit extends StatefulWidget {
  final historyContactID;
  ContactUserEdit(this.historyContactID);

  @override
  _ContactUserEditState createState() =>
      _ContactUserEditState(this.historyContactID);
}

class _ContactUserEditState extends State<ContactUserEdit> {
  final historyContactID;

  _ContactUserEditState(this.historyContactID);
  bool isLoading = false;
  String contactId;
  TextEditingController date = TextEditingController(); // วันที่แจ้ง
  TextEditingController time = TextEditingController(); // เวลา
  String contactType = ""; // แบบการติดต่อ
  String contactChannel = ""; // ช่องทางการติดต่อ
  String contactNamePEA = ""; // ชื่อผู้ติดต่อ กฟภ
  String contactNameCus = ""; // ชื่อผู้ติดต่อ ลูกค้า
  String contactReason = ""; // เหตุผลที่ติดต่อ
  String strDateCreate = "";

  String hitContacTypeName = "";
  String hitContacChannelName = "";
  String hitContacReasonName = "";

  var dropdownValue;
  TextEditingController contactDetails = TextEditingController(); // รายละเอียด
  TextEditingController teContactNamePEA = TextEditingController();
  TextEditingController teContactNameCus = TextEditingController();
  TextEditingController teContactReason = TextEditingController();

  List<KeyValueModel> contactTypeList = [
    //รายการแบบการติดต่อ
    KeyValueModel(key: "เลือก", value: ""),
  ];

  List<KeyValueModel> contactChannelList = [
    //รายการช่องทางการติดต่อ
    KeyValueModel(key: "เลือก", value: ""),
  ];

  List<KeyValueModel> contactNamePEAList = [
    //รายการชื่อผู้ติดต่อ กฟภ
    KeyValueModel(key: "เลือก", value: ""),
  ];

  List<KeyValueModel> contactNameCusList = [
    //รายการช ชื่อผู้ติดต่อ ลูกค้า
    KeyValueModel(key: "เลือก", value: ""),
  ];

  List<KeyValueModel> contactReasonList = [
    //รายการเหตุผลที่ติดต่อ
    KeyValueModel(key: "เลือก", value: ""),
  ];

  var mapCheck = [];
  @override
  void initState() {
    super.initState();
    print("On Edit HistoryCommunication Page11");
    Intl.defaultLocale = 'th';
    initializeDateFormatting();

    setState(() {
      isLoading = true;
      print("historyContactID ::: " + historyContactID);
      contactId = historyContactID;
      contactNamePEA = AppUrl.userName;
      teContactNamePEA.text = contactNamePEA;

      loadDataDropDown().then((res) {
        setState(() {
          loadHistoryData(contactId);
        });
      });

      isLoading = false;
    });
  }

  loadHistoryData(String customerContactId) async {
    try {
      final response =
          await HistoryContact.getHistoryContactRead(customerContactId);
      setState(() {
        var history = response;
        DateTime strStart;
        var formatter = DateFormat.yMd();
        strStart = DateTime.parse(history['CommunicateDate'].split('T')[0]);
        time.text = history['CommunicateDate'].split('T')[1].substring(0, 5);
        contactDetails.text = history['CommunicateDetail'];
        teContactNameCus.text = history['CommunicateWith'];

        date.text = formatter.formatInBuddhistCalendarThai(strStart);
        strDateCreate = strStart.toString().substring(0, 10);
        contactType = history['CommunicateDirectionId'];
        contactChannel = history['CommunicateChannelId'];
        contactReason = history['CategoryContactId'];
        print(contactReason);
        for (var i = 1; i < contactTypeList.length; i++) {
          if (contactTypeList[i].value.split("|")[1] == contactType)
            hitContacTypeName = contactTypeList[i].key.toString();
          print(hitContacTypeName);
        }

        for (var i = 1; i < contactChannelList.length; i++) {
          if (contactChannelList[i].value.split("|")[1] == contactChannel)
            hitContacChannelName = contactChannelList[i].key.toString();
          print(hitContacChannelName);
        }

        for (var i = 1; i < contactReasonList.length; i++) {
          if (contactReasonList[i].value.split("|")[1] == contactReason)
            hitContacReasonName = contactReasonList[i].key.toString();
          print(hitContacReasonName);
        }
      });
      print(response);
      return true;
    } catch (e) {
      print(e);
    }
  }

  loadDataDropDown() async {
    final listContactTypeList =
        await HistoryContact.getCommunicateDirectionList();
    for (var i = 0; i < listContactTypeList.length; i++) {
      setState(() {
        contactTypeList.add(KeyValueModel(
            key: listContactTypeList[i]['CommunicateDirectionName'].toString(),
            value: listContactTypeList[i]['CommunicateDirectionName']
                    .toString() +
                "|" +
                listContactTypeList[i]['CommunicateDirectionId'].toString()));
      });
    }

    final listContactChanelReadList = await HistoryContact
        .getCommunicateChannelList(); // ไปเรียกฟังชั่นดึงข้อมูลจาก api
    for (var i = 0; i < listContactChanelReadList.length; i++) {
      setState(() {
        contactChannelList.add(KeyValueModel(
            key: listContactChanelReadList[i]['CommunicateChannelName']
                .toString(),
            value: listContactChanelReadList[i]['CommunicateChannelName']
                    .toString() +
                "|" +
                listContactChanelReadList[i]['CommunicateChannelId']
                    .toString()));
      });
    }

    final listCategoryContactList = await HistoryContact
        .getCategoryContactList(); // ไปเรียกฟังชั่นดึงข้อมูลจาก api เหตุผลที่ติดต่อ
    for (var i = 0; i < listCategoryContactList.length; i++) {
      setState(() {
        contactReasonList.add(KeyValueModel(
            key: listCategoryContactList[i]['CategoryContactName'].toString(),
            value: listCategoryContactList[i]['CategoryContactName']
                    .toString() +
                "|" +
                listCategoryContactList[i]['CategoryContactId'].toString()));
      });
    }
  } // function

  @override
  Widget build(BuildContext context) {
    if (isLoading == true) {
      return AppLoader.loaderWaitPage();
    }
    double _width = MediaQuery.of(context).size.width;
    double _height = MediaQuery.of(context).size.height;
    
    Header.routes = ContactUser();
    return GestureDetector(
      onTap: (){
        FocusScope.of(context).unfocus();
      },
      child: 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(
                margin: EdgeInsets.only(
                  top: mediaQuery(context, 'h', 990),
                ),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: <Widget>[
                    Text(
                      'ประวัติการติดต่อสื่อสาร',
                      style: TextStyle(
                          fontSize: mediaQuery(context, 'h', 60),
                          color: AppColors.color_gold),
                      textAlign: TextAlign.center,
                    ),
                  ],
                ),
              ),
              Container(
                width: _width,
                height: mediaQuery(context, 'h', 1100),
                margin: EdgeInsets.only(
                  top: mediaQuery(context, 'h', 1100),
                  left: mediaQuery(context, 'w', 60),
                  right: mediaQuery(context, 'w', 60),
                ),
                child: SingleChildScrollView(
                  padding: EdgeInsets.only(
                    bottom: _height / 3.5),
                  child: Column(
                    children: <Widget>[
                      Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: <Widget>[
                          Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: <Widget>[
                              Text(
                                'วันที่แจ้ง :',
                                style: TextStyle(
                                  fontSize: mediaQuery(context, 'h', 40),
                                  color: AppColors.Black,
                                ),
                                textAlign: TextAlign.center,
                              ),
                              Container(
                                height: mediaQuery(context, 'h', 105),
                                width: mediaQuery(context, 'w', 490),
                                child: GestureDetector(
                                  onTap: () async {
                                    DateTime newDate = await showRoundedDatePicker(
                                      context: context,
                                      initialDate: 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) {
                                      var dtArray = newDate.toString().split(" ");
                                      setState(() {
                                        var formatter = DateFormat.yMd();
                                        var showDate = formatter
                                            .formatInBuddhistCalendarThai(newDate);
                                        date.text = showDate;
                                        strDateCreate = 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(
                                'เวลา :',
                                style: TextStyle(
                                    fontSize: mediaQuery(context, 'h', 40),
                                    color: AppColors.Black),
                                textAlign: TextAlign.center,
                              ),
                              Container(
                                height: mediaQuery(context, 'h', 105),
                                width: mediaQuery(context, 'w', 490),
                                child: GestureDetector(
                                  onTap: () 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,
                                          ),
                                        );
                                      },
                                    );
                                    if (newTime != null) {
                                      String timeStr = newTime.hour.toString() +
                                          ":" +
                                          newTime.minute.toString();
                                      setState(() {
                                        time.text = timeStr;
                                      });
                                    }
                                  },
                                  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,
                                          ),
                                        ),
                                      ],
                                    ),
                                  ),
                                ),
                              ),
                            ],
                          ),
                        ],
                      ),
                      _buildSizeBox(context),
                      Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: <Widget>[
                          _buildTextMenu(context, 'แบบการติดต่อ :'),
                        ],
                      ),
                      _buildSizeBox(context),
                      Row(
                        children: <Widget>[
                          _buildDropDownRow1(context),
                        ],
                      ),
                      _buildSizeBox(context),
                      Row(
                        children: <Widget>[
                          _buildTextMenu(context, 'ช่องทางการติดต่อ :'),
                        ],
                      ),
                      _buildSizeBox(context),
                      Row(
                        children: <Widget>[
//                      _buildDropDownRow(context),
                          _buildDropDownRow2(context),
                        ],
                      ),
                      _buildSizeBox(context),
                      Row(
                        children: <Widget>[
                          _buildTextMenu(context, 'ชื่อผู้ติดต่อ (กฟภ.) :'),
                        ],
                      ),
                      _buildSizeBox(context),
                      Row(
                        children: <Widget>[
                          //_buildDropDownRow3(context),
//                      _buildDropDownRow(context),
                          _buildTextField(context, teContactNamePEA),
                        ],
                      ),
                      _buildSizeBox(context),
                      Row(
                        children: <Widget>[
                          _buildTextMenu(context, 'ชื่อผู้ติดต่อ (ลูกค้า) :'),
                        ],
                      ),
                      _buildSizeBox(context),
                      Row(
                        children: <Widget>[
                          //_buildDropDownRow4(context),
//                      _buildDropDownRow(context),
                          _buildTextField(context, teContactNameCus),
                        ],
                      ),
                      _buildSizeBox(context),
                      Row(
                        mainAxisAlignment: MainAxisAlignment.start,
                        children: <Widget>[
                          _buildTextMenu(context, 'เหตุผลที่ติดต่อ :'),
                        ],
                      ),
                      _buildSizeBox(context),
                      Row(
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: <Widget>[
                          _buildDropDownRow5(context),
//                      _buildDropDownRow(context),
//                      _buildTextField(context, te_contactReason),
                        ],
                      ),
                      _buildSizeBox(context),
                      Row(
                        mainAxisAlignment: MainAxisAlignment.start,
                        children: <Widget>[
                          _buildTextMenu(context, 'รายละเอียด :'),
                        ],
                      ),
                      _buildSizeBox(context),
                      Card(
                        color: Colors.white,
                        child: Padding(
                          padding: EdgeInsets.all(
                            mediaQuery(context, 'h', 40),
                          ),
                          child: TextField(
                            controller: contactDetails,
                            maxLines: 5,
                            style: TextStyle(
                              fontSize: mediaQuery(context, 'h', 36),
                              color: Color(0xFF707070),
                            ),
                            decoration: InputDecoration.collapsed(
                              hintText: "",
                            ),
                          ),
                        ),
                      ),
                      SizedBox(
                        height: mediaQuery(context, "h", 60),
                      ),
                      Row(
                        mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                        children: <Widget>[
                          _buildButtonCancel(context),
                          _buildButtonSave(context),
                        ],
                      ),
                    ],
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

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

  _buildTextFieldUserContact(context, controller) {
    return Container(
      height: mediaQuery(context, 'h', 110),
      width: mediaQuery(context, 'w', 1005),
      child: TextField(
        enabled: true,
        controller: controller,
        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,
        ),
      ),
    );
  }

  _buildTextField(context, controller) {
    return Container(
      height: mediaQuery(context, 'h', 110),
      width: mediaQuery(context, 'w', 1005),
      child: TextField(
        enabled: true,
        controller: controller,
        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,
        ),
      ),
    );
  }

  _buildRow(context) {
    return Container(
      height: mediaQuery(context, 'h', 130),
      width: mediaQuery(context, 'w', 1005),
      child: TextField(
        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,
        ),
      ),
    );
  }

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

  _buildDropDownRow1(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: DropdownButtonHideUnderline(
          child: DropdownButton<String>(
            iconSize: 30,
            icon: Icon(Icons.keyboard_arrow_down),
            underline: SizedBox(),
            items: contactTypeList
                .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(() {
                hitContacTypeName = value;
                print("ContactType :: " + hitContacTypeName);
                for (var i = 1; i < contactTypeList.length; i++) {
                  if (contactTypeList[i].value == hitContacTypeName)
                    contactType = hitContacTypeName.split("|")[1];
                }
                hitContacTypeName = hitContacTypeName.split("|")[0];
              });
            },
            hint: Text(
              hitContacTypeName.toString(),
              style: TextStyle(
                fontSize: mediaQuery(context, "h", 60),
                color: AppColors.Black,
              ),
              textScaleFactor: 0.7,
            ),
          ),
        ),
      ),
    );
  }

  _buildDropDownRow2(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: dropdownValue,
          icon: Icon(Icons.expand_more),
          iconSize: 30,
          elevation: 16,
//          style: TextStyle(color: AppColors.Black),
          underline: SizedBox(),
          items: contactChannelList
              .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(() {
              hitContacChannelName = value;
              print("value :: " + hitContacChannelName);
              for (var i = 0; i < contactChannelList.length; i++) {
                if (contactChannelList[i].value == hitContacChannelName)
                  contactChannel = hitContacChannelName.split("|")[1];
              }
              hitContacChannelName = hitContacChannelName.split("|")[0];
            });
          },
          hint: Text(
            hitContacChannelName.toString(),
            style: TextStyle(
              fontSize: mediaQuery(context, "h", 60),
              color: AppColors.Black,
            ),
            textScaleFactor: 0.7,
          ),
        ),
      ),
    );
  }

  _buildDropDownRow3(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: dropdownValue,
          icon: Icon(Icons.expand_more),
          iconSize: 30,
          elevation: 16,
//          style: TextStyle(color: AppColors.Black),
          underline: SizedBox(),
          items: contactNamePEAList
              .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(() {
              contactNamePEA = value;
              print(contactNamePEA);
            });
          },
          value: contactNamePEA,
        ),
      ),
    );
  }

  _buildDropDownRow4(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: dropdownValue,
          icon: Icon(Icons.expand_more),
          iconSize: 30,
          elevation: 16,
//          style: TextStyle(color: AppColors.Black),
          underline: SizedBox(),
          items: contactNameCusList
              .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(() {
              contactNameCus = value;
              print(contactNameCus);
            });
          },
          value: contactNameCus,
        ),
      ),
    );
  }

  _buildDropDownRow5(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>(
          icon: Icon(Icons.expand_more),
          iconSize: 30,
          elevation: 16,
          underline: SizedBox(),
          items: contactReasonList
              .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(() {
              hitContacReasonName = value;
              print(hitContacReasonName);
              for (var i = 0; i < contactReasonList.length; i++)
                if (contactReasonList[i].value == hitContacReasonName)
                  contactReason = hitContacReasonName.split("|")[1];
              hitContacReasonName = hitContacReasonName.split("|")[0];
            });
          },
          hint: Text(
            hitContacReasonName.toString(),
            style: TextStyle(
              fontSize: mediaQuery(context, "h", 60),
              color: AppColors.Black,
            ),
            textScaleFactor: 0.7,
          ),
        ),
      ),
    );
  }

  _buildDropDownRow2Column(context) {
    return Container(
//      color: Colors.red,
      height: mediaQuery(context, 'h', 110),
      width: mediaQuery(context, 'w', 480),
      decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(20),
          border: Border.all(color: Colors.black),
          color: Colors.white),
      child: Container(
        margin: EdgeInsets.only(
          left: mediaQuery(context, 'w', 25),
        ),
        child: DropdownButton<String>(
            value: dropdownValue,
            icon: Icon(Icons.expand_more),
            iconSize: 30,
            elevation: 16,
            style: TextStyle(color: AppColors.Black),
            underline: Container(
              height: 0,
              color: AppColors.Black,
            ),
            onChanged: (String newValue) {
              setState(() {
                dropdownValue = newValue;
              });
            },
            items: <String>['One', 'Two', 'Free', 'Four']
                .map<DropdownMenuItem<String>>((String value) {
              return DropdownMenuItem<String>(
                value: value,
                child: Text(value),
              );
            }).toList(),
            isExpanded: true),
      ),
    );
  }

  _buildButtonCancel(context) {
    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: AppColors.color,
        textColor: Colors.red,
        padding: EdgeInsets.all(
          mediaQuery(context, "w", 10),
        ),
        onPressed: () {
          print('ยกเลิก');
          Get.offAll(Header.routes);
          return false;
        },
        child: Text(
          'ยกเลิก',
          style: TextStyle(
            fontSize: 14.0,
            color: Colors.white,
          ),
        ),
      ),
    );
  }

  _buildButtonSave(context) {
    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: AppColors.color,
        textColor: Colors.red,
        padding: EdgeInsets.all(
          mediaQuery(context, "w", 10),
        ),
        onPressed: () {
          saveCommu(context);
        },
        child: Text(
          'บันทึก',
          style: TextStyle(
            fontSize: 14.0,
            color: Colors.white,
          ),
        ),
      ),
    );
  }

  saveCommu(context) async {
    if (!await checkForm([
      date.text,
      time.text,
      contactType,
      contactChannel,
      contactNamePEA,
      teContactNameCus.text,
      contactDetails.text,
    ])) {
      alertForm(context, "แจ้งเตือน", "กรอกข้อมูลไม่ครบ");
    } else {
      Map<String, dynamic> data = {
        "customerId": AppUrl.CustomerID,
        "communicateDate": strDateCreate + " " + time.text,
        "communicateWith": teContactNameCus.text,
        "communicateDirectionId": contactType,
        "communicateDetail": contactDetails.text,
        "communicateEmployee": contactNamePEA,
        "communicateChannelId": contactChannel,
        "categoryContactId": contactReason.isEmpty ? "" : contactReason,
        "AuthenKey": AppUrl.AuthenKey
      };
      print(data);
      await HistoryContact.saveData(context, data);
    }
  }
} //class

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