import 'dart:io';
import 'dart:convert';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.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/loader.dart';
import 'package:mwf_app/service/screen.dart';
import 'package:mwf_app/service/style.dart';
import 'package:mwf_app/service/url.dart';
import 'package:mwf_app/model/voice.dart';
import 'package:mwf_app/set6/service_report_user.dart';
import 'package:nextflow_thai_personal_id/nextflow_thai_personal_id.dart';
import 'package:file_picker/file_picker.dart';

class CustomerVoiceSave extends StatefulWidget {
  @override
  _CustomerVoiceSaveViewState createState() => _CustomerVoiceSaveViewState();
}

class _CustomerVoiceSaveViewState extends State<CustomerVoiceSave> {
  TextEditingController voiceType = TextEditingController(); // ชื่ผู้ให้ข้อมูล
  TextEditingController name = TextEditingController(); // ชื่ผู้ให้ข้อมูล
  TextEditingController idCard = TextEditingController(); //เลขบัตรประชาชน
  TextEditingController phone = TextEditingController(); // เบอร์โทรศัพท์
  TextEditingController email = TextEditingController(); // email
  TextEditingController contactLocation =
      TextEditingController(); // สถานที่ติดต่อกลับ
  TextEditingController province = TextEditingController(); // จังหวัด
  TextEditingController electricity = TextEditingController(); // การไฟฟ้า
  TextEditingController locale = TextEditingController(); // สถานที่เกิดเหตุ
  TextEditingController electricityUserNumber =
      TextEditingController(); // หมายเลขผู้ใช้ไฟฟ้า
  TextEditingController subcategory = TextEditingController(); // ประเภทย่อย
  TextEditingController topic = TextEditingController(); // หัวข้อ
  TextEditingController details = TextEditingController(); // รายละเอียด
  TextEditingController document = TextEditingController(); // เอกสารแนบ
  TextEditingController status = TextEditingController(); // สถานะ
  TextEditingController selectImage = TextEditingController();
  TextEditingController description = TextEditingController(); // คำอธิบาย
  TextEditingController selectDoc = TextEditingController();
  ThaiIdValidator validator = ThaiIdValidator();
  bool isIdCardValid = true;
  var base64Doc;
  int filesize = 0;

  List<KeyValueModel> _dropdownType = [
    KeyValueModel(key: "เลือก", value: ""),
  ];
  List<KeyValueModel> _dropdownProvince = [
    KeyValueModel(key: "เลือก", value: ""),
  ];
  List<KeyValueModel> _dropdownElectricity = [
    KeyValueModel(key: "เลือก", value: ""),
  ];
  List<KeyValueModel> _dropdownPealist = [
    KeyValueModel(key: "เลือก", value: ""),
  ];
  List<KeyValueModel> _dropdownSubComplaintType = [
    KeyValueModel(key: "เลือก", value: ""),
  ];
  List<KeyValueModel> _dropdownComplaintType = [
    KeyValueModel(key: "เลือก", value: ""),
  ];
  List<KeyValueModel> _dropdownStatus = [
    KeyValueModel(key: "เลือก", value: ""),
  ];
  List<KeyValueModel> _dropdownSuggestion = [
    KeyValueModel(key: "เลือก", value: ""),
  ];
  bool isLoading = false;
  String strTypeVoiceID = "";
  String strProvinceID = "";
  String strElectricityID = "";
  String strComplaintTypeID = "";
  String strSubComplaintTypeID = "";
  String strStatusID = "";
  String strPeaCodeName = "";
  var mapCheck = [];
  var sizeSubComplaintType = "";
  String _fileName;
  String _path;
  Map<String, String> _paths;
  String _extension;
  bool _loadingPath = false;
  bool _multiPick = false;

  bool isEmailValid = true;
  RegExp regExp = RegExp(
      r'^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,2}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|([a-zA-Z]))');
//RegExp regExp = RegExp(r'^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$');

  @override
  void initState() {
    super.initState();
    print(AppUrl.userID);
    getVoiceType();
    getVoiceProvine();
  }

  _openFileExplorer() async {
    File file = await FilePicker.getFile();
    if (file != null) {
      String base64 = base64Encode(file.readAsBytesSync());
      filesize = file.lengthSync();
      setState(() {
        selectDoc.text = file.path.split("/")[file.path.split("/").length - 1];
        base64Doc = base64;
      });
    }
  }

  getVoiceType() async {
    final list = await Voice.getVoiceType(); // ไปเรียกฟังชั่นดึงข้อมูลจาก api
    mapCheck.clear();
    setState(() {
      list.forEach((value) {
        if (!mapCheck.contains(value['TagName'].toString())) {
          mapCheck.add(value['TagName'].toString());
          _dropdownType.add(
            KeyValueModel(
              key: value['TagName'].toString(),
              value: value['TagId'].toString(), // value ค่าที่บันทึก
            ),
          );
        }
      });
    });
  }

  getVoiceProvine() async {
    final list =
        await Voice.getVoiceProvine(); // ไปเรียกฟังชั่นดึงข้อมูลจาก api
    mapCheck.clear();
    setState(() {
      list.forEach((value) {
        if (!mapCheck.contains(value['ProviceName'].toString())) {
          mapCheck.add(value['ProviceName'].toString());
          _dropdownProvince.add(
            KeyValueModel(
              key: value['ProviceName'].toString(),
              // key คือค่าที่แสดง
              value: value['ProviceId'].toString(), // value ค่าที่บันทึก
            ),
          );
        }
      });
    });
  }

  getVoiceElectricity() async {
    final list =
        await Voice.getVoiceElectricity(); // ไปเรียกฟังชั่นดึงข้อมูลจาก api
    mapCheck.clear();
    setState(() {
      list.forEach((value) {
        if (!mapCheck.contains(value['ElectricityName'].toString())) {
          mapCheck.add(value['ElectricityName'].toString());
          _dropdownElectricity.add(
            KeyValueModel(
              key: value['ElectricityName'].toString(),
              // key คือค่าที่แสดง
              value: value['ElectricityId'].toString(), // value ค่าที่บันทึก
            ),
          );
        }
      });
    });
  }

  getVoicePealist(proviceId) async {
    final list = await Voice.getVoicePealist(
      proviceId,
    ); // ไปเรียกฟังชั่นดึงข้อมูลจาก api
    mapCheck.clear();
    setState(() {
      list.forEach((value) {
        if (!mapCheck.contains(value['PeaName'].toString())) {
          mapCheck.add(value['PeaName'].toString());
          _dropdownPealist.add(
            KeyValueModel(
              key: value['PeaName'].toString(),
              value: value['PeaCode'].toString() +
                  "|" +
                  value['PeaName'].toString(), // value ค่าที่บันทึก
            ),
          );
        }
      });
    });
  }

  getVoiceSuggestion() async {
    final list =
        await Voice.getVoiceSuggestion(); // ไปเรียกฟังชั่นดึงข้อมูลจาก api
    mapCheck.clear();
    setState(() {
      list.forEach((value) {
        if (!mapCheck.contains(value['Suggestion'].toString())) {
          mapCheck.add(value['Suggestion'].toString());
          _dropdownSuggestion.add(
            KeyValueModel(
              key: value['Suggestion'].toString(),
              value: value['Id'].toString(), // value ค่าที่บันทึก
            ),
          );
        }
      });
    });
  }

  getVoiceComplaintSubTypeList(complaintTypeId) async {
    final list = await Voice.getVoiceComplaintSubTypeList(
        complaintTypeId); // ไปเรียกฟังชั่นดึงข้อมูลจาก api
    if (list.isEmpty) {
      setState(() {
        sizeSubComplaintType = "empty";
      });
      _dropdownSubComplaintType = [
        KeyValueModel(key: "เลือก", value: ""),
      ];
    } else if (list.isNotEmpty) {
      setState(() {
        sizeSubComplaintType = "notEmpty";
      });
    }
    mapCheck.clear();
    setState(() {
      list.forEach((value) {
        if (!mapCheck.contains(value['ComplaintSubtypeName'].toString())) {
          mapCheck.add(value['ComplaintSubtypeName'].toString());
          _dropdownSubComplaintType.add(
            KeyValueModel(
              key: value['ComplaintSubtypeName'].toString(),
              value:
                  value['ComplaintSubtypeId'].toString(), // value ค่าที่บันทึก
            ),
          );
        }
      });
    });
  }

  getVoice_ComplaintType(tagId) async {
    final list = await Voice.getVoiceComplaintType(
        tagId); // ไปเรียกฟังชั่นดึงข้อมูลจาก api
    mapCheck.clear();
    setState(() {
      list.forEach((value) {
        if (!mapCheck.contains(value['ComplaintTypeName'].toString())) {
          mapCheck.add(value['ComplaintTypeName'].toString());
          _dropdownComplaintType.add(
            KeyValueModel(
              key: value['ComplaintTypeName'].toString(),
              value: value['ComplaintTypeId'].toString(), // value ค่าที่บันทึก
            ),
          );
        }
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    if (isLoading == true) {
      AppLoader.show();
    }
    if (isLoading == false) {
      AppLoader.hide();
    }
    Header.routes = ServiceReportUser();
    double _width = MediaQuery.of(context).size.width;
    double _height = MediaQuery.of(context).size.height;
    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', 930),
                ),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: <Widget>[
                    Text(
                      "เสียงของลูกค้า",
                      style: AppStyle.headTextStyle(context),
                    )
                  ],
                ),
              ),
              Container(
                width: _width,
                height: mediaQuery(context, 'h', 1180),
                margin: EdgeInsets.only(
                  top: mediaQuery(context, 'h', 1030),
                  left: mediaQuery(context, 'w', 60),
                  right: mediaQuery(context, 'w', 60),
                ),
                child: SingleChildScrollView(
                  padding: EdgeInsets.only(
                    bottom: _height / 3.5),
                  child: Column(
                    children: <Widget>[
                      _buildTextMenu(context, "ประเภทเสียงของลูกค้า", false),
                      _buildSizeBox(context),
                      _buildDropDownTypeVoice(context),
                      _buildSizeBox(context),
                      _buildTextMenu(context, "ชื่อผู้ให้ข้อมูล", true),
                      _buildSizeBox(context),
                      _buildRow(context, name),
                      _buildSizeBox(context),
                      _buildTextMenu(context, "เลขที่บัตรประชาชน", true),
                      _buildSizeBox(context),
                      _buildRowIdCard(context, idCard),
                      _buildSizeBox(context),
                      _buildTextMenu(context, "เบอร์โทรศัพท์", true),
                      _buildSizeBox(context),
                      _buildRowTelNumber(context, phone),
                      _buildSizeBox(context),
                      _buildTextMenu(context, "อีเมล", false),
                      _buildSizeBox(context),
                      _buildRowEmail(context, email),
                      _buildSizeBox(context),
                      _buildTextMenu(context, "สถานที่ติดต่อกลับ", true),
                      _buildSizeBox(context),
                      _buildTextArea(context, contactLocation),
                      _buildSizeBox(context),
                      Row(
                        children: <Widget>[
                          Text(
                            "กรุณาระบุการไฟฟ้าที่ท่านต้องการให้ข้อเสนอแนะ / ข้อคิดเห็น",
                            style: TextStyle(
                              color: AppColors.color,
                              fontSize: mediaQuery(context, "w", 30),
                            ),
                          )
                        ],
                      ),
                      _buildSizeBox(context),
                      _buildTextMenu(context, "จังหวัด", true),
                      _buildSizeBox(context),
                      _buildDropDownProvince(context),
                      _buildSizeBox(context),
                      _buildTextMenu(
                          context, "การไฟฟ้า (กรุณาเลือกจังหวัดก่อน)", true),
                      _buildSizeBox(context),
                      _buildDropDownPealist(context),
                      _buildSizeBox(context),
                      _buildTextMenu(context, "สถานที่เกิดเหตุ", true),
                      _buildSizeBox(context),
                      _buildTextArea(context, locale),
                      _buildSizeBox(context),
                      _buildSizeBox(context),
                      _buildTextMenu(context, "ประเภทข้อเสนอแนะ", true),
                      _buildSizeBox(context),
                      _buildDropDownComplaintType(context),
                      _buildSizeBox(context),
                      _buildTextMenu(context, "หัวข้อ", true),
                      _buildSizeBox(context),
                      _buildDropDownSubComplaintType(context),
                      _buildSizeBox(context),
                      _buildTextMenu(context, "รายละเอียด", true),
                      _buildSizeBox(context),
                      _buildTextArea(context, details),
                      _buildSizeBox(context),
                      Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: <Widget>[
                          _buildTextMenu(context, "เอกสารแนบ", false),
                        ],
                      ),
                      _buildSizeBox(context),
                      Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: <Widget>[
                          Container(
                            height: mediaQuery(context, 'h', 110),
                            width: mediaQuery(context, 'w', 600),
                            child: TextField(
                              enabled: true,
                              controller: selectDoc,
                              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,
                              ),
                            ),
                          ),
                          ButtonTheme(
                            minWidth: mediaQuery(context, "w", 360),
                            height: mediaQuery(context, "h", 120),
                            child: FlatButton(
                              shape: RoundedRectangleBorder(
                                borderRadius: BorderRadius.circular(
                                  mediaQuery(context, "w", 50),
                                ),
                                side: BorderSide(color: AppColors.color),
                              ),
                              color: AppColors.color_gold,
                              textColor: Colors.white,
                              padding: EdgeInsets.all(
                                mediaQuery(context, "w", 10),
                              ),
                              onPressed: () {
                                print("Browse");
                                _openFileExplorer();
                              },
                              child: Text(
                                "Browse",
                                style: TextStyle(
                                  fontSize: mediaQuery(context, "h", 50),
                                  color: Colors.white,
                                ),
                              ),
                            ),
                          )
                        ],
                      ),
                      _buildSizeBox(context),
                      _buildSizeBox(context),
                      _buildSizeBox(context),
                      _buildSizeBox(context),
                      Row(
                        mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                        children: <Widget>[
                          _buildButtonCancel(context),
                          _buildButtonSave(context),
                        ],
                      ),
                    ],
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  _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: Colors.white,
        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: AppColors.color,
          ),
        ),
      ),
    );
  }

  _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: () {
          print("บันทึก");
          saveVoice(context);
        },
        child: Text(
          "บันทึก",
          style: TextStyle(
            fontSize: 14.0,
            color: Colors.white,
          ),
        ),
      ),
    );
  }

  _buildTextArea(context, TextEditingController controller) {
    return Container(
      color: Colors.white,
      child: TextField(
        controller: controller,
        maxLines: 5,
        decoration: InputDecoration(
            fillColor: Colors.white70,
            border: OutlineInputBorder(
              borderRadius: const BorderRadius.all(
                const Radius.circular(10.0),
              ),
            ),
            hintText: "",
            labelText: ''),
      ),
    );
  }

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

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

  _buildRowEmail(context, TextEditingController controller) {
    _isZero() {
      if (controller.text.length >= 0 && isEmailValid == false) {
        return mediaQuery(context, 'h', 195);
      } else {
        return mediaQuery(context, 'h', 110);
      }
    }

    return Container(
      height: _isZero(),
      width: mediaQuery(context, 'w', 1005),
      child: TextField(
        keyboardType: TextInputType.emailAddress,
        controller: controller,
        enabled: true,
        onChanged: (value) {
          isEmailValid = true;
          setState(() {});
        },
        decoration: InputDecoration(
          errorText: isEmailValid ? null : "กรุณาตรวจสอบ Email อีกครั้ง",
          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,
        ),
      ),
    );
  }

  _buildRowIdCard(context, TextEditingController controller) {
    isZero() {
      if (controller.text.length > 0 && isIdCardValid == false) {
        return mediaQuery(context, 'h', 196);
      } else if (controller.text.length == 0 && isIdCardValid == false) {
        setState(() {
          isIdCardValid = true;
        });
        return mediaQuery(context, 'h', 110);
      } else {
        return mediaQuery(context, 'h', 110);
      }
    }

    return Container(
      height: isZero(),
      width: mediaQuery(context, 'w', 1005),
      child: TextField(
        keyboardType: TextInputType.number,
        controller: controller,
        onChanged: (value) {
          isIdCardValid = true;
          var res = validator.validate(value);
          if (res != null) {
            setState(() {
              isIdCardValid = false;
            });
          } else {
            setState(() {
              isIdCardValid = true;
            });
          }
        },
        enabled: true,
        maxLength: 13,
        decoration: InputDecoration(
            errorText:
                isIdCardValid ? null : "กรุณาตรวจสอบ เลขบัตรประจำตัว อีกครั้ง",
            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),
      ),
    );
  }

  _buildRowTelNumber(context, TextEditingController controller) {
    return Container(
      height: mediaQuery(context, 'h', 110),
      width: mediaQuery(context, 'w', 1005),
      child: TextField(
        keyboardType: TextInputType.number,
        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,
        ),
      ),
    );
  }

  _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,
        ),
      ),
    );
  }

  _buildDropDownComplaintType(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: 30,
              icon: Icon(Icons.keyboard_arrow_down),
              underline: SizedBox(),
              items: _dropdownComplaintType
                  .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(() {
                  FocusScope.of(context).unfocus();
                  strComplaintTypeID = value;
                  strSubComplaintTypeID = "";
                  _dropdownSubComplaintType = [
                    KeyValueModel(key: "เลือก", value: ""),
                  ];
                  if (strComplaintTypeID != "") {
                    getVoiceComplaintSubTypeList(strComplaintTypeID);
                  }
                });
              },
              value: strComplaintTypeID,
            ),
          ),
        ),
      ],
    );
  }

  _buildDropDownSubComplaintType(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: 30,
              icon: Icon(Icons.keyboard_arrow_down),
              underline: SizedBox(),
              items: _dropdownSubComplaintType
                  .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(() {
                  FocusScope.of(context).unfocus();
                  strSubComplaintTypeID = value;
                  print(strSubComplaintTypeID);
                });
              },
              value: strSubComplaintTypeID,
            ),
          ),
        ),
      ],
    );
  }

  _buildDropDownPealist(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: 30,
              icon: Icon(Icons.keyboard_arrow_down),
              underline: SizedBox(),
              items: _dropdownPealist
                  .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(() {
                  FocusScope.of(context).unfocus();
                  strPeaCodeName = value;
                });
              },
              value: strPeaCodeName,
            ),
          ),
        ),
      ],
    );
  }

  _buildDropDownProvince(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: 30,
              icon: Icon(Icons.keyboard_arrow_down),
              underline: SizedBox(),
              items: _dropdownProvince
                  .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(() {
                  FocusScope.of(context).unfocus();
                  strProvinceID = value;
                  _dropdownPealist = [
                    KeyValueModel(key: "เลือก", value: ""),
                  ];
                  strPeaCodeName = "";
                  getVoicePealist(strProvinceID);
                });
              },
              value: strProvinceID,
            ),
          ),
        ),
      ],
    );
  }

  _buildDropDownTypeVoice(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: 30,
              icon: Icon(Icons.keyboard_arrow_down),
              underline: SizedBox(),
              items: _dropdownType
                  .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(() {
                  FocusScope.of(context).unfocus();
                  strTypeVoiceID = value;
                  strComplaintTypeID = "";
                  _dropdownComplaintType = [
                    KeyValueModel(key: "เลือก", value: ""),
                  ];
                  getVoice_ComplaintType(strTypeVoiceID);
                });
              },
              value: strTypeVoiceID,
            ),
          ),
        ),
      ],
    );
  }

  saveVoice(context) async {
    var val = "";
    if (sizeSubComplaintType == "empty") {
      setState(() {
        val = "empty";
      });
    } else if (sizeSubComplaintType == "notEmpty" &&
        strSubComplaintTypeID != "") {
      setState(() {
        val = "c";
      });
    } else if (sizeSubComplaintType == "notEmpty" &&
        strSubComplaintTypeID.isEmpty) {
      setState(() {
        val = "";
      });
    }
    if (await checkForm([
      name.text,
      idCard.text,
      phone.text,
      val,
      strProvinceID,
      strPeaCodeName,
      locale.text,
      strComplaintTypeID,
      contactLocation.text,
      details.text,
      //base64Doc,
    ])) {
      setState(() {
        isLoading = true;
      });
      Map<String, dynamic> data = {
        "authenKey": AppUrl.AuthenKey.toString(),
        "tagId": strTypeVoiceID.toString(),
        "complainerName": name.text.toString(),
        "citizenNumber": idCard.text.toString(),
        "telephoneNumber": phone.text.toString(),
        "email": email.text.toString(),
        "provinceId": strProvinceID.toString(),
        "peaCode": strPeaCodeName.split("|")[0].toString(),
        "peaName": strPeaCodeName.split("|")[1].toString(),
        "accidentLocation": locale.text.toString(),
        "caNumber": AppUrl.CA.toString(),
        "complaintTypeId": strComplaintTypeID.toString(),
        "complaintSubtypeId":
            val == "empty" ? null : strSubComplaintTypeID.toString(),
        "contactAddress": contactLocation.text.toString(),
        "detail": details.text.toString(),
        "employeeId": AppUrl.employeeEmpID.toString(),
        "files": [
          selectDoc.text != ""
              ? {
                  "ExtensionData": selectDoc.text.split(".")[1],
                  "FileContent": base64Doc.toString(),
                  "FileName": selectDoc.text.split(".")[0],
                  "MimeType": selectDoc.text.split(".")[1],
                  "Description": "",
                }
              : []
        ]
      };
      print(data);
      Voice.saveData(context, data);
      setState(() {
        isLoading = false;
      });
    } else {
      alertForm(context, "แจ้งเตือน", "กรอกข้อมูลไม่ครบ");
    }
  }
} //class

class KeyValueModel {
  String key;
  String value;

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