import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_rounded_date_picker/rounded_picker.dart';
import 'package:get/get.dart';
import 'package:intl/date_symbol_data_local.dart';
import 'package:intl/intl.dart';
import 'package:mwf_app/service/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/strings.dart';
import 'package:mwf_app/service/convert.dart';
import 'package:mwf_app/model/visit_plan.dart';
import 'package:mwf_app/set2/visiting_plan_find.dart';
import 'package:mwf_app/service/url.dart';
import 'package:mwf_app/set2/visiting_plan_list.dart';
import 'dart:convert';
import 'package:mwf_app/service/loader.dart';
import 'package:buddhist_datetime_dateformat/buddhist_datetime_dateformat.dart';

//VisitPlan model

class ListAddStaffString {
  String visitTeamId;
  String customerName;
  String customerCode;
  String description;
  String proposeTypename;

  ListAddStaffString(this.customerName, this.customerCode, this.description,
      this.proposeTypename);
}

class ListAddStaff {
  TextEditingController visitTeamId = TextEditingController();
  TextEditingController customerName = TextEditingController();
  TextEditingController customerCode = TextEditingController();
  TextEditingController description = TextEditingController();
  TextEditingController proposeTypename = TextEditingController();
// TextEditingController visitCount = TextEditingController();
// TextEditingController visitYear = TextEditingController();

  ListAddStaff(
    this.visitTeamId,
    this.customerName,
    this.customerCode,
    this.description,
    this.proposeTypename,
  );
}

class KeyValueModel {
  String key;
  String value;

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

class ListDataVisitOBJ {
  String vitsitOBJ;

  ListDataVisitOBJ(this.vitsitOBJ);
}

List<ListAddStaff> dataAddStaff = [];
List<ListAddStaffString> dataAddStaffString = [];
List<ListDataVisitOBJ> dataVisitOBJ = [];

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

String visitOBJ = "";
String strVisitDate = "";
String strVisitTime = "";
String strVisitEndDate = "";
String strVisitEndTime = "";
DateTime dateCurrent = DateTime.now();
int yearNow = 0;

class VisitingPlanSave extends StatefulWidget {
  VisitingPlanSave(
      {Key key, this.visitIdEdit, this.dataDateTime, this.employeeData})
      : super(key: key);
  String visitIdEdit;
  Map dataDateTime;
  Map employeeData;
  //VisitingPlanSave(this.visitId_edit);

  @override
  _VisitingPlanSaveState createState() => _VisitingPlanSaveState(
        // this.data,
        this.visitIdEdit,
      );
}

TextEditingController visitDate = TextEditingController();
TextEditingController visitTime = TextEditingController();
TextEditingController visitPurpose = TextEditingController();
TextEditingController visitMethod = TextEditingController();
TextEditingController visitTeamId = TextEditingController();

TextEditingController visitCount = TextEditingController();
TextEditingController visitYear = TextEditingController();
//
TextEditingController customerName = TextEditingController();
TextEditingController customerCode = TextEditingController();
TextEditingController description = TextEditingController();
TextEditingController proposeTypename = TextEditingController();

Map<String, dynamic> data1;

class _VisitingPlanSaveState extends State<VisitingPlanSave> {
  // Map<String, dynamic> data;
  String visitIdEdit;

  _VisitingPlanSaveState(
    this.visitIdEdit,
  );
  TextEditingController visitCount = TextEditingController();
  TextEditingController visitYear = TextEditingController();

  TextEditingController visitDate = TextEditingController();
  TextEditingController visitTime = TextEditingController();
  TextEditingController visitEndDate = TextEditingController();
  TextEditingController visitEndTime = TextEditingController();
  TextEditingController purposeVisit = TextEditingController();
  TextEditingController visit = TextEditingController();

  bool monVal = false;
  bool isLoading = true;
  bool isLoadPage = false;
  String visitOBJ = "";
  bool isTeamData = false;

  @override
  void initState() {
    super.initState();
    Header.routes = VisitingPlanList();
    print("visiting_plan_save");
    print(visitIdEdit);
    yearNow =
        dateCurrent.year < 2400 ? dateCurrent.year + 543 : dateCurrent.year;
    loadDataListVisitOBJ();
    Intl.defaultLocale = 'th';
    initializeDateFormatting();
    isLoading = false;
    visitMethod.text = "";
    visitTime.text = "";

    visitCount.text = "";
    visitYear.text = "";

    if (widget.dataDateTime != null) {
      setData();
    }

    if (visitIdEdit != null && widget.dataDateTime == null) {
      getDataEdit(context).then((res) {
        setState(() {
          isLoading = true;
        });
      });
    }
  }

  setData() {
    isLoadPage = true;
    var item;
    setState(() {
      visitCount.text = widget.dataDateTime['visitcount'] ?? "";
      visitYear.text = widget.dataDateTime['visityear'] ?? "";
      visitIdEdit = widget.dataDateTime['visitId'];

      visitDate.text = widget.dataDateTime['strStartDate'] == null
          ? ""
          : widget.dataDateTime['strStartDate'];
      strVisitDate =
          visitDate.text != "" && visitDate.text != null ? AppConvert.dateThaiToEng(visitDate.text) : "";

      visitTime.text = widget.dataDateTime['strStartTime'] == null
          ? ""
          : widget.dataDateTime['strStartTime'];
      visitEndTime.text = widget.dataDateTime['strEndTime'] == null
          ? null
          : widget.dataDateTime['strEndTime'];
      strVisitTime = visitTime.text;
      visitEndDate.text = widget.dataDateTime['strEndDate'] == null
          ? ""
          : widget.dataDateTime['strEndDate'];
      strVisitEndDate = visitEndDate.text != "" && visitEndDate.text != null
          ? AppConvert.dateThaiToEng(visitEndDate.text)
          : "";

      strVisitEndTime = visitEndTime.text;

      visitOBJ = widget.dataDateTime['visitObj'] == null
          ? ""
          : widget.dataDateTime['visitObj'];
      if (dataAddStaff.isNotEmpty ){
        setState(() => isTeamData = true);
      }else{
        setState(() => isTeamData = false);
      }
      if (widget.employeeData != null) {
        item = widget.employeeData;

        TextEditingController _customerName = TextEditingController();
        TextEditingController _customerCode = TextEditingController();
        TextEditingController _description = TextEditingController();
        TextEditingController _proposeTypename = TextEditingController();
        TextEditingController _visitTeamId = TextEditingController();

        _visitTeamId.text = isTeamData == true ? "" : visitIdEdit;
        _customerName.text = item['customerName'];
        _customerCode.text = item['customerCode'];
        _description.text =
            (item['description'].isNotEmpty ? "หัวหน้าคณะ" : "");
        _proposeTypename.text = item['proposeTypename'].toString();
        var listStaff = ListAddStaff(
          _visitTeamId,
          _customerName,
          _customerCode,
          _description,
          _proposeTypename,
        );

        dataAddStaff.add(listStaff);
      }
    });
    isLoadPage = false;
  }

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

    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(
              margin: EdgeInsets.only(
                top: mediaQuery(context, "h", 950),
              ),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: <Widget>[
                  Text(
                    "แผนการเยี่ยมเยือน",
                    style: TextStyle(
                      fontSize: mediaQuery(context, "h", 60),
                      color: AppColors.color_gold,
                    ),
                  ),
                ],
              ),
            ),
            Container(
              width: _width,
//            color: Colors.red.shade800,
              height: mediaQuery(context, 'h', 1100),
              margin: EdgeInsets.only(
                top: mediaQuery(context, 'h', 1080),
                left: mediaQuery(context, 'w', 60),
                right: mediaQuery(context, 'w', 60),
              ),
              child: SingleChildScrollView(
                child: Column(
                  children: <Widget>[
                    _buildTextMenuTwoColumn_2(
                        context, "ครั้งที่เยี่ยมเยียน", "ปี", 220.0),

                    Row(
                      children: <Widget>[
                        _buildTextFieldVisitCountYear(
                            context, visitCount, visitYear),
                      ],
                    ),

                    _buildTextMenuTwoColumn_3(
                        context,
                        AppStrings.VisitingPlanSave_date,
                        AppStrings.VisitingPlanSave_time,
                        220.0),

                    _buildSizeBox(context),

                    Row(
                      children: <Widget>[
                        _buildTextFieldTwoColumn(context, visitDate, visitTime),
                      ],
                    ),

                    _buildSizeBox(context),

                    _buildTextMenuTwoColumn(
                        context,
                        AppStrings.EndVisitingPlanSave_date,
                        AppStrings.EndVisitingPlanSave_time,
                        220.0),

                    _buildSizeBox(context),

                    Row(
                      children: <Widget>[
                        _buildTextFieldTwoColumnEnd(
                            context, visitEndDate, visitEndTime),
                      ],
                    ),

                    _buildSizeBox(context),

                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: <Widget>[
                        _buildTextMenu(context, "จุดประสงค์การเยี่ยมเยือน")
                      ],
                    ),
                    _buildSizeBox(context),

                    //======================================
                    //
                    //======================================
                    Row(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: <Widget>[
                        Container(
                          width: mediaQuery(context, "w", 1005),
                          height: mediaQuery(context, "h", 120),
                          padding: EdgeInsets.symmetric(horizontal: 10.0),
                          decoration: BoxDecoration(
                            borderRadius: BorderRadius.circular(53.0),
                            border: Border.all(
                                color: AppColors.color_border,
                                style: BorderStyle.solid,
                                width: 0.80),
                          ),
                          child: DropdownButtonHideUnderline(
                            child: DropdownButton(
                              style: TextStyle(
                                color: AppColors.Black,
                                fontSize: mediaQuery(context, "w", 30),
                              ),
                              items: _dropdownVisitOdj
                                  .map(
                                    (data) => DropdownMenuItem<String>(
                                      child: Container(
                                        child: Text(
                                          data.key,
                                          style: TextStyle(
                                            fontSize:
                                                mediaQuery(context, "h", 50),
                                          ),
                                          textScaleFactor: 0.7,
                                        ),
                                      ),
                                      value: data.value,
                                    ),
                                  )
                                  .toList(),
                              onChanged: (value) {
                                setState(() {
                                  visitOBJ = value;
                                });
                              },
                              isExpanded: true,
                              value: visitOBJ,
                            ),
                          ),
                        ),
                      ],
                    ),
                    _buildSizeBox(context),
                    GestureDetector(
                      onTap: () {
                        Navigator.of(context).pushReplacement(
                          MaterialPageRoute(
                            settings:
                                const RouteSettings(name: '/visitPlanFind'),
                            builder: (context) => VisitingPlanFind(data: {
                              'strStartDate': visitDate.text,
                              'strEndDate': visitEndDate.text,
                              'strStartTime': visitTime.text,
                              'strEndTime': visitEndTime.text,
                              'visitObj': visitOBJ,
                              'visityear': visitYear.text,
                              'visitcount': visitCount.text,
                              'visitId': visitIdEdit,
                              'page': "edit"
                            }),
                          ),
                        );
                      },
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.end,
                        children: <Widget>[
                          Icon(
                            Icons.add_circle_outline,
                            color: AppColors.color,
                            size: 36.0,
                          ),
                          SizedBox(
                            width: 10,
                          ),
                          Text(AppStrings.VisitingPlanSave_addStaff)
                        ],
                      ),
                    ),
                    _buildSizeBox(context),
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: <Widget>[
                        _buildTextMenu(context, "รายชื่อพนักงาน")
                      ],
                    ),
                    _buildSizeBox(context),
                    Column(
                      children: List.generate(
                        dataAddStaff.length,
                        (index) {
                          return _buildTextFieldIcon(
                            context,
                            index,
                            dataAddStaff[index].customerName.text +
                                " :" +
                                dataAddStaff[index].description.text +
                                " :" +
                                dataAddStaff[index].proposeTypename.text,
                          );
                        },
                      ),
                    ),

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

                    _buildSizeBox(context),
                    _buildSizeBox(context),
                    Row(
                      children: <Widget>[
                        Row(
                          mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                          children: <Widget>[
                            _buildButton(context, "ยกเลิก", Colors.white,
                                AppColors.color),
                            SizedBox(
                              width: 10,
                            ),
                            _buildButton(context, "บันทึก", AppColors.color,
                                Colors.white),
                          ],
                        ),
                      ],
                    ),
                  ],
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

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

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

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

//===============================================================================================
  //                                      Dropdown List Problame
  //===============================================================================================

  loadDataListVisitOBJ() async {
    final listLocationType = await DataListVisitOBJ.getDataListVitsitOBJ();
    dataVisitOBJ = null;

    _dropdownVisitOdj = [
      KeyValueModel(key: "เลือก", value: ""),
    ];

    for (var i = 0; i < listLocationType.length; i++) {
      //print(listLocationType);

      setState(() {
        _dropdownVisitOdj.add(
          KeyValueModel(
            key: listLocationType[i]['VisitObjectiveName']
                .toString(), // key คือค่าที่แสดง
            value: listLocationType[i]['VisitObjectiveId'].toString(),
          ),
        );
      });
    }
  }

  _buildTextFieldVisitCountYear(context, TextEditingController controller1,
      TextEditingController controller2) {
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceEvenly,
      children: <Widget>[
        Container(
          height: mediaQuery(context, 'h', 105),
          width: mediaQuery(context, 'w', 180),
          margin: EdgeInsets.only(
            right: mediaQuery(context, 'w', 25),
          ),
          child: Stack(
            children: <Widget>[
              TextField(
                controller: visitCount,
                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),
              ),
            ],
          ),
        ),
        Container(
          height: mediaQuery(context, 'h', 105),
          width: mediaQuery(context, 'w', 280),
          child: Stack(
            children: <Widget>[
              TextField(
                controller: visitYear,
                enabled: true,
                decoration: InputDecoration(
//                                  prefixIcon: Icon(Icons.search),
                    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),
              ),
            ],
          ),
        ),
      ],
    );
  }

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

  _buildTextFieldTwoColumn(context, TextEditingController controller1,
      TextEditingController controller2) {
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceEvenly,
      children: <Widget>[
        Container(
          height: mediaQuery(context, 'h', 105),
          width: mediaQuery(context, 'w', 490),
          margin: EdgeInsets.only(
            right: mediaQuery(context, 'w', 25),
          ),
          child: Stack(
            children: <Widget>[
              TextField(
                controller: visitDate,
                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 startdatePicker(context);
                  if (date != null) {
                    setState(() {
                      var formatter = DateFormat.yMd();
                      var showDate =
                          formatter.formatInBuddhistCalendarThai(date);
                      visitDate.text = showDate;
                      strVisitDate = date.toString().split(" ")[0];
                      print("start date: " + strVisitDate);
                    });
                  }
                },
                child: Container(
                  margin: EdgeInsets.only(
                    top: mediaQuery(context, 'h', 10),
                    left: mediaQuery(context, 'w', 400),
                  ),
                  child: Icon(
                    Icons.calendar_today,
                    color: Colors.grey,
                  ),
                ),
              ),
            ],
          ),
        ),
        Container(
          height: mediaQuery(context, 'h', 105),
          width: mediaQuery(context, 'w', 490),
          child: Stack(
            children: <Widget>[
              TextField(
                controller: visitTime,
                enabled: false,
                decoration: InputDecoration(
//                                  prefixIcon: Icon(Icons.search),
                    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 {
                  TimeOfDay newTime = await showTimePicker(
                    context: context,
                    initialTime: visitTime.text != ""
                        ? TimeOfDay(
                            hour: CheckTime.getHour(visitTime),
                            minute: CheckTime.getMin(visitTime))
                        : TimeOfDay.now(),
                    builder: (context, child) {
                      return Column(children: <Widget>[
                        MediaQuery(
                            data: MediaQuery.of(context)
                                .copyWith(alwaysUse24HourFormat: true),
                            child: child),
                        Theme(
                          data: Theme.of(context).copyWith(
                            primaryColor: AppColors.color,
                            accentColor: AppColors.color_gold,
                            colorScheme: ColorScheme.light(
                              primary: AppColors.color,
                            ),
                            buttonTheme: ButtonThemeData(
                              textTheme: ButtonTextTheme.primary,
                            ),
                          ),
                          child: Container(
                            height: 0,
                            width: 0,
                            child: child,
                          ),
                        ),
                      ]);
                    },
                  );

                  if (newTime != null) {
                    String hourBeforeConvert = newTime.hour.toString();
                    String minBeforeConvert = newTime.minute.toString();
                    var timeAfterConvert = AppConvert.fillZeroTime(
                        newTime, hourBeforeConvert, minBeforeConvert);
                    String hour = (newTime.hour - 7).toString();
                    String min = newTime.minute.toString();
                    var time = AppConvert.fillZeroTime(newTime, hour, min);
                    print(timeAfterConvert);
                    setState(() {
                      visitTime.text = timeAfterConvert;
                      strVisitTime = time;
                    });
                    print("Call Time : " + newTime.toString());
                  }
                },
                child: Container(
                  margin: EdgeInsets.only(
                    top: mediaQuery(context, 'h', 10),
                    left: mediaQuery(context, 'w', 400),
                  ),
                  child: Icon(
                    Icons.expand_more,
                    color: Colors.grey,
                  ),
                ),
              ),
            ],
          ),
        ),
      ],
    );
  }

  _buildTextFieldTwoColumnEnd(context, TextEditingController controller1,
      TextEditingController controller2) {
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceEvenly,
      children: <Widget>[
        Container(
          height: mediaQuery(context, 'h', 105),
          width: mediaQuery(context, 'w', 490),
          margin: EdgeInsets.only(
            right: mediaQuery(context, 'w', 25),
          ),
          child: Stack(
            children: <Widget>[
              TextField(
                controller: visitEndDate,
                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 endDatePicker(context);
                  if (date != null) {
                    setState(() {
                      var formatter = DateFormat.yMd();
                      var showDate =
                          formatter.formatInBuddhistCalendarThai(date);
                      visitEndDate.text = showDate;
                      strVisitEndDate = date.toString().split(" ")[0];
                      print("end date: " + strVisitEndDate);
                    });
                  }
                },
                child: Container(
                  margin: EdgeInsets.only(
                    top: mediaQuery(context, 'h', 10),
                    left: mediaQuery(context, 'w', 400),
                  ),
                  child: Icon(
                    Icons.calendar_today,
                    color: Colors.grey,
                  ),
                ),
              ),
            ],
          ),
        ),
        Container(
          height: mediaQuery(context, 'h', 105),
          width: mediaQuery(context, 'w', 490),
          child: Stack(
            children: <Widget>[
              TextField(
                controller: visitEndTime,
                enabled: false,
                decoration: InputDecoration(
//                                  prefixIcon: Icon(Icons.search),
                    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 {
                  TimeOfDay newTime = await showTimePicker(
                    context: context,
                    initialTime: visitEndTime.text != ""
                        ? TimeOfDay(
                            hour: CheckTime.getHour(visitEndTime),
                            minute: CheckTime.getMin(visitEndTime))
                        : TimeOfDay.now(),
                    builder: (context, child) {
                      return Column(children: <Widget>[
                        MediaQuery(
                            data: MediaQuery.of(context)
                                .copyWith(alwaysUse24HourFormat: true),
                            child: child),
                        Theme(
                          data: Theme.of(context).copyWith(
                            primaryColor: AppColors.color,
                            accentColor: AppColors.color_gold,
                            colorScheme: ColorScheme.light(
                              primary: AppColors.color,
                            ),
                            buttonTheme: ButtonThemeData(
                              textTheme: ButtonTextTheme.primary,
                            ),
                          ),
                          child: Container(
                            height: 0,
                            width: 0,
                            child: child,
                          ),
                        ),
                      ]);
                    },
                  );

                  if (newTime != null) {
                    String hourBeforeConvert = newTime.hour.toString();
                    String minBeforeConvert = newTime.minute.toString();
                    var timeAfterConvert = AppConvert.fillZeroTime(
                        newTime, hourBeforeConvert, minBeforeConvert);
                    String hour = (newTime.hour - 7).toString();
                    String min = newTime.minute.toString();
                    var time = AppConvert.fillZeroTime(newTime, hour, min);
                    setState(() {
                      //time.text = timeStr;
                      visitEndTime.text = timeAfterConvert;
                      strVisitEndTime = time;
                    });
                    print("Call Time : " + timeAfterConvert.toString());
                  }
                },
                child: Container(
                  margin: EdgeInsets.only(
                    top: mediaQuery(context, 'h', 10),
                    left: mediaQuery(context, 'w', 400),
                  ),
                  child: Icon(
                    Icons.expand_more,
                    color: Colors.grey,
                  ),
                ),
              ),
            ],
          ),
        ),
      ],
    );
  }

  startdatePicker(context) async {
    DateTime endtDate = DateTime(DateTime.now().year + 10);
    DateTime initDate = DateTime.now();

    if (visitEndDate.text.isNotEmpty) {
      String endDateStr =
          DateFormat('dd/MM/yyyy', Locale('th', 'TH').scriptCode)
              .parse(visitEndDate.text)
              .toString();
      endDateStr = endDateStr.replaceAll(
          DateFormat('dd/MM/yyyy', Locale('th', 'TH').scriptCode)
              .parse(visitEndDate.text)
              .year
              .toString(),
          (DateFormat('dd/MM/yyyy', Locale('th', 'TH').scriptCode)
                      .parse(visitEndDate.text)
                      .year -
                  543)
              .toString());
      endtDate = DateTime.parse(endDateStr);

      initDate = endtDate;
    }

    if (visitDate.text.isNotEmpty) {
      String startDateStr =
          DateFormat('dd/MM/yyyy', Locale('th', 'TH').scriptCode)
              .parse(visitDate.text)
              .toString();
      startDateStr = startDateStr.replaceAll(
          DateFormat('dd/MM/yyyy', Locale('th', 'TH').scriptCode)
              .parse(visitDate.text)
              .year
              .toString(),
          (DateFormat('dd/MM/yyyy', Locale('th', 'TH').scriptCode)
                      .parse(visitDate.text)
                      .year -
                  543)
              .toString());
      initDate = DateTime.parse(startDateStr);
    }

    DateTime newDate = await showRoundedDatePicker(
      context: context,
      initialDate: initDate,
      firstDate: DateTime(DateTime.now().year - 10),
      lastDate: DateTime(DateTime.now().year + 10),
      locale: Locale('th', 'TH'),
      era: EraMode.BUDDHIST_YEAR,
      theme: ThemeData(primarySwatch: Colors.deepPurple),
      height: 280,
      textActionButton: "ลบวันที่และเวลา",
        onTapActionButton: (){
          setState(() {
            visitDate.clear();
            visitTime.clear();
            strVisitDate = "";
            strVisitTime = "";
          });
      },
    );

    return newDate;
  }

  endDatePicker(context) async {
    DateTime startDate = DateTime(DateTime.now().year - 10);
    DateTime initDate = DateTime.now();

    if (visitDate.text.isNotEmpty) {
      String startDateStr =
          DateFormat('dd/MM/yyyy', Locale('th', 'TH').scriptCode)
              .parse(visitDate.text)
              .toString();
      startDateStr = startDateStr.replaceAll(
          DateFormat('dd/MM/yyyy', Locale('th', 'TH').scriptCode)
              .parse(visitDate.text)
              .year
              .toString(),
          (DateFormat('dd/MM/yyyy', Locale('th', 'TH').scriptCode)
                      .parse(visitDate.text)
                      .year -
                  543)
              .toString());
      startDate = DateTime.parse(startDateStr);
      initDate = startDate;
    }

    if (visitEndDate.text.isNotEmpty) {
      String endDateStr =
          DateFormat('dd/MM/yyyy', Locale('th', 'TH').scriptCode)
              .parse(visitEndDate.text)
              .toString();
      endDateStr = endDateStr.replaceAll(
          DateFormat('dd/MM/yyyy', Locale('th', 'TH').scriptCode)
              .parse(visitEndDate.text)
              .year
              .toString(),
          (DateFormat('dd/MM/yyyy', Locale('th', 'TH').scriptCode)
                      .parse(visitEndDate.text)
                      .year -
                  543)
              .toString());
      initDate = DateTime.parse(endDateStr);
    }

    DateTime newDate = await showRoundedDatePicker(
      context: context,
      initialDate: initDate,
      firstDate: DateTime(DateTime.now().year - 10),
      lastDate: DateTime(DateTime.now().year + 10),
      locale: Locale('th', 'TH'),
      era: EraMode.BUDDHIST_YEAR,
      theme: ThemeData(primarySwatch: Colors.deepPurple),
      height: 280,
      textActionButton: "ลบวันที่และเวลา",
        onTapActionButton: (){
          setState(() {
            visitEndDate.clear();
            visitEndTime.clear();
            strVisitEndDate = "";
            strVisitEndTime = "";
          });
      },
    );

    return newDate;
  }

  timePicker(context, TextEditingController controller2) async {
    TimeOfDay newTime = await showTimePicker(
      context: context,
      initialTime: visitTime.text != ""
          ? TimeOfDay(
              hour: CheckTime.getHour(visitTime) - 7,
              minute: CheckTime.getMin(visitTime))
          : TimeOfDay.now(),
      builder: (context, child) {
        return Column(children: <Widget>[
          MediaQuery(
              data:
                  MediaQuery.of(context).copyWith(alwaysUse24HourFormat: true),
              child: child),
          Theme(
            data: Theme.of(context).copyWith(
              primaryColor: AppColors.color,
              accentColor: AppColors.color_gold,
              colorScheme: ColorScheme.light(
                primary: AppColors.color,
              ),
              buttonTheme: ButtonThemeData(
                textTheme: ButtonTextTheme.primary,
              ),
            ),
            child: Container(
              height: 0,
              width: 0,
              child: child,
            ),
          ),
        ]);
      },
    );
    // setState(() {
    //   controller2.text = time.toString();
    // });
    if (newTime != null) {
      String timeStr =
          newTime.hour.toString() + ":" + newTime.minute.toString();
      setState(() {
        //time.text = timeStr;
        strVisitTime = timeStr;
        controller2.text = timeStr.toString();
      });
    }
    print("Time : " + strVisitTime.toString());
    return newTime.hour.toString() + ":" + newTime.minute.toString();
  }

//====================================================================================================
//                                    Get Data Edit
//====================================================================================================
  getDataEdit(context) async {
    print("=======EDIT=========");
    isLoadPage = true;
    dataAddStaff.clear();
    final list = await VisitPlanCreate.getDataEdit(visitIdEdit);
    print(list);
    try {
      setState(() {
        final dataList = VisitPlanCreate.fromJson(list);
        VisitPlanCreate.data.add(dataList); // loop เก็บข้อมูล

        visitCount.text = VisitPlanCreate.data[0].visitNumber != null ?
          VisitPlanCreate.data[0].visitNumber : "";
        visitYear.text = VisitPlanCreate.data[0].visitYear != null  ?
          VisitPlanCreate.data[0].visitYear : "";

        visitDate.text = VisitPlanCreate.data[0].visitPlanStartDate == null
            ? ""
            : VisitPlanCreate.data[0].visitPlanStartDate.split(" ")[0];
        strVisitDate = AppConvert.dateThaiToEng(visitDate.text);
       
        visitTime.text = VisitPlanCreate.data[0].visitPlanStartDate == null
            ? null
            : VisitPlanCreate.data[0].visitPlanStartDate.split(" ")[1];
        var startHourTime =
            (int.parse(visitTime.text.split(":")[0]) - 7).toString();
        var startMinTime = (int.parse(visitTime.text.split(":")[1])).toString();
        var timeConvert =
            AppConvert.fillZeroTime("newTime", startHourTime, startMinTime);

        strVisitTime = timeConvert;
        visitEndDate.text = VisitPlanCreate.data[0].visitPlanEndDate == null
            ? ""
            : VisitPlanCreate.data[0].visitPlanEndDate.split(" ")[0];

        strVisitEndDate = AppConvert.dateThaiToEng(visitEndDate.text);

        visitEndTime.text = VisitPlanCreate.data[0].visitPlanEndDate == null
            ? null
            : VisitPlanCreate.data[0].visitPlanEndDate.split(" ")[1];

        var startHourEndTime =
            (int.parse(visitEndTime.text.split(":")[0]) - 7).toString();
        var startMinEndTime =
            (int.parse(visitEndTime.text.split(":")[1])).toString();
        var endTimeConvert = AppConvert.fillZeroTime(
            "newTime", startHourEndTime, startMinEndTime);
        strVisitEndTime = endTimeConvert;

        visitOBJ = VisitPlanCreate.data[0].visitObjectiveId == null
            ? ""
            : VisitPlanCreate.data[0].visitObjectiveId;
        print(
            "team info : " + VisitPlanCreate.data[0].visitTeamInfo.toString());
        var dataLists = VisitPlanCreate.data[0].visitTeamInfo.isEmpty
            ? ""
            : VisitPlanCreate.data[0].visitTeamInfo;
        print(dataLists);
        if(dataLists != ""){
          setState(() {
            isTeamData = true;
          });
        }
        if(dataLists != ""){
          for (var item in dataLists) {
            TextEditingController _customerName = TextEditingController();
            TextEditingController _customerCode = TextEditingController();
            TextEditingController _description = TextEditingController();
            TextEditingController _proposeTypename = TextEditingController();
            TextEditingController _visitTeamId = TextEditingController();

            _visitTeamId.text = item['VisitTeamId'];
            _customerName.text = item['DisplayName'];
            _customerCode.text = item['EmployeeNumber'].toString();
            _description.text = (item['IsLeader'] == true ? "หัวหน้าคณะ" : "");
            _proposeTypename.text = item['PositionTeam'].toString();

            var _list = ListAddStaff(
              _visitTeamId,
              _customerName,
              _customerCode,
              _description,
              _proposeTypename,
            );
            dataAddStaff.add(_list);
          }
        }
        isLoadPage = false;
      }); //End setState
    } catch (e) {
      setState(() {
        isLoadPage = false;
      });
      await Future.delayed(const Duration(seconds: 1));
      AppLoader.showError("ไม่สามารถโหลดข้อมูลได้");
      print("getData_Edit Error (visiting_plan_save)");
      await Future.delayed(const Duration(seconds: 2));
    }
  }

//====================================================================================================
//
//====================================================================================================
  _buildTextFieldIcon(context, index, val) {
    TextEditingController _val = TextEditingController();
    _val.text = val;
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceEvenly,
      children: <Widget>[
        Container(
          height: mediaQuery(context, 'h', 110),
          width: mediaQuery(context, 'w', 1005),
          child: Stack(
            children: <Widget>[
              TextField(
                enabled: false,
                controller: _val,
                decoration: InputDecoration(
                    //hintText: 'Enter a search term',
//              prefixIcon: Icon(Icons.search),
                    border: OutlineInputBorder(
                      borderRadius: const BorderRadius.all(
                        const Radius.circular(50.0),
                      ),
                    ),
                    filled: true,
                    hintStyle: TextStyle(color: Colors.grey[800]),
                    counterText: "",
                    contentPadding: EdgeInsets.fromLTRB(13.0, 0.0, 20.0, 10.0),
                    fillColor: Colors.white70),
              ),
              GestureDetector(
                onTap: () {
                  setState(() {
                    print(index.toString());
                    dataAddStaff.removeAt(index);
                  });
                },
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.end,
                  children: <Widget>[
                    Container(
                      margin: EdgeInsets.only(
                        top: mediaQuery(context, 'h', 10),
                        right: mediaQuery(context, 'w', 20),
                      ),
                      child: Icon(
                        Icons.delete,
                        color: AppColors.color_gold,
                      ),
                    ),
                  ],
                ),
              ),
            ],
          ),
        ),
      ],
    );
  }

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

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

  _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 == "บันทึก") {
            setState(() {
              isLoadPage = true;
            });
            saveData();
          } else {
            // Nav.push(context, VisitingPlanList('','','','',''));
            Navigator.of(context)..pop();
          }
        },
        child: Text(
          text,
          style: TextStyle(
            fontSize: 14.0,
            color: fontColor,
          ),
        ),
      ),
    );
  }

  saveData() async {
    bool chk = await checkForm([
      visitDate.text,
      visitTime.text,
      visitOBJ,
      visitCount.text,
      visitYear.text
    ]);

    if (chk == false) {
      alertForm(context, "แจ้งเตือน", "กรอกข้อมูลไม่ครบ");
    } else {
      var _result = [];
      _result.clear();
      var _list;
      print("____________ Via ----  EDIT ______________");
      for (var item in dataAddStaff) {
        _list = {
          "VisitTeamId": item.visitTeamId.text,
          "EmployeeNumber": item.customerCode.text,
          "DisplayName": item.customerName.text,
          "PositionTeam": item.proposeTypename.text,
          "IsLeader": item.description.text != "" ? true : false,
        };
        _result.add(_list);
      }

      var _data = jsonEncode({
        "visitYear": visitYear.text,
        "visitNumber": visitCount.text,
        "customerId": AppUrl.CustomerID,
        "visitId": visitIdEdit,
        "visitPlanStartDate":
            AppConvert.dateEngToThai(strVisitDate) + " " + visitTime.text,
        "visitPlanEndDate":
            AppConvert.dateEngToThai(strVisitEndDate) + " " + visitEndTime.text,
        "companyRepresentativeFullName": "",
        "visitObjectiveId": visitOBJ, //dropdown value
        "VisitTeamInfo": _result, //List Staff
        "authenKey": AppUrl.AuthenKey
      });

      bool acceptCondition = false;
      var startDate = DateTime.parse(strVisitDate);

      if (visitEndDate.text.isNotEmpty && visitEndTime.text.isNotEmpty) {
        var endDate = DateTime.parse(strVisitEndDate);
        if (startDate.isBefore(endDate)) {
          acceptCondition = true;
        } else if ((startDate == endDate || startDate.isBefore(endDate)) &&
            CheckTime.checkTime(visitTime, visitEndTime)) {
          acceptCondition = true;
        } else {
          alertForm(context, "แจ้งเตือน",
              "กรุณาตรวจสอบ วันหรือเวลา เริ่มต้น และสิ้นสุดอีกครั้ง");
        }
      } else if (visitEndDate.text.isNotEmpty && visitEndTime.text.isEmpty) {
        var endDate = DateTime.parse(strVisitEndDate);
        if (startDate == endDate || startDate.isBefore(endDate)) {
          acceptCondition = true;
        } else {
          alertForm(context, "แจ้งเตือน",
              "กรุณาตรวจสอบ วันที่เริ่มต้น และสิ้นสุดอีกครั้ง");
        }
      } else if (visitEndDate.text.isEmpty && visitEndTime.text.isNotEmpty) {
        if (CheckTime.checkTime(visitTime, visitEndTime)) {
          acceptCondition = true;
        } else {
          alertForm(context, "แจ้งเตือน",
              "กรุณาตรวจสอบ เวลา เริ่มต้น และสิ้นสุดอีกครั้ง");
        }
      } else {
        acceptCondition = true;
      }
      if (acceptCondition) {
        print("Update");
        print(_data);
        //Update
        await VisitPlanCreate.visitPlanUpdate(context, _data);
      }
      setState(() {
        isLoadPage = false;
      });
    }
    //}
  }
} //class
