import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:mwf_app/service/alert.dart';
import 'package:mwf_app/service/color.dart';
import 'package:mwf_app/service/header.dart';
import 'package:mwf_app/service/loader.dart';
import 'package:mwf_app/service/screen.dart';
import 'package:mwf_app/service/url.dart';
import 'package:autocomplete_textfield/autocomplete_textfield.dart';
import 'package:mwf_app/set2/visiting_plan_add.dart';
import 'package:mwf_app/service/api.dart';
import 'package:mwf_app/service/shadow.dart';
import 'package:mwf_app/set2/visiting_plan_save.dart';

List<VisitPlanEmployee> listEmployee = List<VisitPlanEmployee>();

//VisitPlan_model ใช้ model นี้
class VisitingPlanFind extends StatefulWidget {
  final Map data;

  VisitingPlanFind({this.data});

  @override
  _VisitingPlanFindState createState() => _VisitingPlanFindState();
}

TextEditingController customerName = TextEditingController(); // ชื่อ - นามสกุล
TextEditingController customerCode = TextEditingController(); // รหัสพนักงาน
TextEditingController customerPhone = TextEditingController();

class _VisitingPlanFindState extends State<VisitingPlanFind> {
  TextEditingController _radioValueCustomerCode = TextEditingController();
  TextEditingController _radioValueCustomerName = TextEditingController();
  String _radioValueResult;
  TextEditingController description = TextEditingController(); //หัวหข้าคณะ
  TextEditingController proposeTypename =
      TextEditingController(); //เยี่ยมเยือนในฐานนะ
  bool monVal = false;
  int _radioValue;
  String strStartDate;
  String strEndDate;
  String startTime;
  String endTime;
  String visitId;
  String visitObj;
  String visitCount;
  String visitYear;
  String page;

  bool isLoading = false;
  @override
  void initState() {
    super.initState();
    print("Find");
    print(widget.data);
    VisitPlanAddEmployee.dataEmployee = [];
    loadData();
  }

  void onReady() {
    print('Screen is ready! plan find');
  }

  void onResume() {
    print('Screen is resumed plan find!');
  }

  void onPause() {
    print('Screen is paused! plan find');
  }

  loadData() async {
    customerName.clear();
    customerCode.clear();
    proposeTypename.text = "รผก.";
    strStartDate = widget.data['strStartDate'];
    strEndDate = widget.data['strEndDate'];
    startTime = widget.data['strStartTime'];
    endTime = widget.data['strEndTime'];
    visitId = widget.data['visitId'];
    visitObj = widget.data['visitObj'];
    visitCount = widget.data['visitcount'];
    visitYear = widget.data['visityear'];
    page = widget.data['page'];
    print("Data From : " + page + " page.");
  }

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

    return Material(
      color: AppColors.bgColor,
      child: WillPopScope(
        onWillPop: () async {
          page == "edit"
              ? Navigator.of(context).pushReplacement(
                  MaterialPageRoute(
                    settings:
                        const RouteSettings(name: '/visitPlanSaveWithoutId'),
                    builder: (context) => VisitingPlanSave(
                      dataDateTime: {
                        'strStartDate': strStartDate,
                        'strEndDate': strEndDate,
                        'strStartTime': startTime,
                        'strEndTime': endTime,
                        'visitId': visitId,
                        'visitObj': visitObj,
                        'visitcount': visitCount,
                        'visityear': visitYear,
                      },
                    ),
                  ),
                )
              : Navigator.of(context).pushReplacement(
                  MaterialPageRoute(
                    settings: const RouteSettings(name: '/visitPlanAdd'),
                    builder: (context) => VisitingPlanAdd(
                      dataDateTime: {
                        'strStartDate': strStartDate,
                        'strEndDate': strEndDate,
                        'strStartTime': startTime,
                        'strEndTime': endTime,
                        'visitId': visitId,
                        'visitObj': visitObj,
                        'visitcount': visitCount,
                        'visityear': visitYear,
                      },
                    ),
                  ),
                );
          return false;
        },
        child: Stack(
          children: <Widget>[
            Header.header2(context),
            Header.mainMenu(context),
            Container(
              margin: EdgeInsets.only(
                top: mediaQuery(context, "h", 370),
              ),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: <Widget>[
                  Text(
                    "แผนการเยี่ยมเยือน",
                    style: TextStyle(
                      fontSize: mediaQuery(context, "h", 60),
                      color: AppColors.color_gold,
                    ),
                  ),
                ],
              ),
            ),
            Container(
              width: _width,
              height: mediaQuery(context, 'h', 1750),
              margin: EdgeInsets.only(
                top: mediaQuery(context, 'h', 460),
                left: mediaQuery(context, 'w', 60),
                right: mediaQuery(context, 'w', 60),
              ),
              child: SingleChildScrollView(
                child: Column(
                  children: <Widget>[
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: <Widget>[
                        _buildTextMenu(context, "ชื่อ - นามสกุล")
                      ],
                    ),
                    _buildSizeBox(context),
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: <Widget>[
                        _buildRow(context, customerName),
//                      _buildRowAuto(context, customerName)
                      ],
                    ),
                    _buildSizeBox(context),
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: <Widget>[
                        _buildTextMenu(context, "รหัสพนักงาน"),
                      ],
                    ),
                    _buildSizeBox(context),
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: <Widget>[
                        Container(
                          height: mediaQuery(context, 'h', 110),
                          width: mediaQuery(context, 'w', 600),
                          child: TextField(
                            enabled: true,
                            controller: customerCode,
                            maxLength: 6,
                            keyboardType: TextInputType.number,
                            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", 110),
                          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("ค้นหา");
                              setState(() {
                                findStaff();
                              });
                            },
                            child: Text(
                              "ค้นหา",
                              style: TextStyle(
                                fontSize: mediaQuery(context, "h", 50),
                                color: Colors.white,
                              ),
                            ),
                          ),
                        )
                      ],
                    ),
                    _buildSizeBox(context),

                    //=======================================================================================================
                    //                                    Result Search
                    //=======================================================================================================
                    if (VisitPlanAddEmployee.dataEmployee != null &&
                        VisitPlanAddEmployee.dataEmployee.length > 0)
                      _buildItemCustCard(),

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

                    _buildSizeBox(context),
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: <Widget>[
                        _buildTextMenu(context, "หัวหน้าคณะ"),
                      ],
                    ),
                    _buildSizeBox(context),

                    Row(
                      children: <Widget>[
                        SizedBox(
                          height: mediaQuery(context, 'h', 80),
                          child: Checkbox(
                            value: monVal,
                            onChanged: (bool value) {
                              if (value == true) {
                                setState(() {
                                  monVal = value;
                                  description.text = "หัวหน้าคณะ";
                                });
                              } else {
                                setState(() {
                                  monVal = value;
                                  description.text = "";
                                });
                              }
                            },
                          ),
                        ),
                        Text(
                          'หัวหน้าคณะ',
                          style: TextStyle(
                            color: AppColors.color_text,
                            fontSize: mediaQuery(context, 'h', 42),
                          ),
                        ),
                      ],
                    ),
                    _buildSizeBox(context),
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: <Widget>[
                        _buildTextMenu(context, "เยี่ยมเยือนในฐานะ"),
                      ],
                    ),
                    _buildSizeBox(context),
                    _buildRadio(context, "รผก.", 0),
                    _buildRadio(context, "อข.", 1),
                    _buildRadio(context, "ผจก. กฟฟ.", 2),
                    _buildRadio(context, "KAM", 3),
                    _buildRadio(context, "ทีมงานอื่นๆ", 4),
                    _buildRadio(context, "อื่นๆ", 5),
                    _buildSizeBox(context),
                    _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),
                          ],
                        ),
                      ],
                    ),
                  ],
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  List<Widget> list(double width) {
    List<Widget> list = List();
    for (var i = 0; i < VisitPlanAddEmployee.dataEmployee.length.toInt(); i++) {
      list.add(
        _buildRadio(
            context, VisitPlanAddEmployee.dataEmployee[i].employeeFullName, i),
      );
      list.add(
        Container(
          height: 0,
        ),
      );
    }
    return list;
  }

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

  _buildItemCustCard() {
    return Container(
      decoration: BoxDecoration(
        borderRadius: BorderRadius.all(
          Radius.circular(
            mediaQuery(context, 'h', 20),
          ),
        ),
        boxShadow: [
          appShadow(),
        ],
        color: Colors.white,
      ),
      height: VisitPlanAddEmployee.dataEmployee.length == 0
          ? 0
          : VisitPlanAddEmployee.dataEmployee.length == 1
              ? mediaQuery(context, 'h', 300)
              : VisitPlanAddEmployee.dataEmployee.length == 2
                  ? 145
                  : 250,
      child: ListView.separated(
        padding: const EdgeInsets.all(8),
        itemCount: VisitPlanAddEmployee.dataEmployee.length,
        separatorBuilder: (BuildContext context, int index) => const Divider(
          height: 1,
        ),
        itemBuilder: (BuildContext context, int index) {
          VisitPlanAddEmployee item = VisitPlanAddEmployee.dataEmployee[index];
          return Container(
            height: mediaQuery(context, 'h', 300),
            color: Colors.white,
            padding: const EdgeInsets.all(8),
            child: Row(
              children: <Widget>[
                Container(
                  width: mediaQuery(context, 'w', 760),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: <Widget>[
                      Row(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: <Widget>[
                          Text(
                            'ลำดับ : ',
                            style: TextStyle(
                              color: AppColors.color_text,
                              fontSize: mediaQuery(context, 'h', 42),
                            ),
                          ),
                          Text(
                            (index + 1).toString(),
                            style: TextStyle(
                              color: AppColors.color_text,
                              fontSize: mediaQuery(context, 'h', 40),
                            ),
                          ),
                        ],
                      ),
                      Row(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: <Widget>[
                          Text(
                            'ชื่อ : ',
                            style: TextStyle(
                              color: AppColors.color_text,
                              fontSize: mediaQuery(context, 'h', 42),
                            ),
                          ),
                          Text(
                            item.employeeFullName != null
                                ? item.employeeFullName
                                : "",
                            style: TextStyle(
                              color: AppColors.color_text,
                              fontSize: mediaQuery(context, 'h', 40),
                            ),
                          ),
                        ],
                      ),
                      Row(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: <Widget>[
                          Text(
                            'รหัสพนักงาน : ',
                            style: TextStyle(
                              color: AppColors.color_text,
                              fontSize: mediaQuery(context, 'h', 42),
                            ),
                          ),
                          Text(
                            item.employeeNumber != null
                                ? item.employeeNumber
                                : "",
                            style: TextStyle(
                              color: AppColors.color_text,
                              fontSize: mediaQuery(context, 'h', 40),
                            ),
                          ),
                        ],
                      ),
                    ],
                  ),
                ),
                _radioValue_Customer(
                  item.employeeNumber,
                  item.employeeFullName,
                ),
              ],
            ),
          );
        },
      ),
    );
  }

  _buildRadio(context,String text, int value) {
    double _width = MediaQuery.of(context).size.width;

    return SizedBox(
      width: _width,
      height: 30,
      child: Row(
        children: <Widget>[
          Radio(
            value: value,
            groupValue: _radioValue,
            onChanged: _handleRadioValueChange,
          ),
          Text(
            text,
            style: TextStyle(
              fontSize: mediaQuery(context, 'h', 38),
            ),
          )
        ],
      ),
    );
  }

  void _handleRadioValueChange(int value) {
    setState(() {
      _radioValue = value;
      if (_radioValue == 0) {
        proposeTypename.text = "รผก.";
      }
      if (_radioValue == 1) {
        proposeTypename.text = "อข.";
      }
      if (_radioValue == 2) {
        proposeTypename.text = "ผจก. กฟฟ.";
      }
      if (_radioValue == 3) {
        proposeTypename.text = "KAM";
      }
      if (_radioValue == 4) {
        proposeTypename.text = "ทีมงานอื่นๆ";
      }
      if (_radioValue == 5) {
        proposeTypename.text = "อื่นๆ";
      }
    });
  }

  _buildRowAuto(context, controller) {
    return Scaffold(
      body: Column(
        children: [
          SizedBox(
            height: 20,
          ),
          // ignore: missing_required_param
          AutoCompleteTextField<VisitPlanEmployee>(
            controller: controller,
            clearOnSubmit: false,
            suggestions: VisitPlanEmployee.getListEmployee(),
            style: TextStyle(color: Colors.black, fontSize: 16.0),
            decoration: InputDecoration(
              contentPadding: EdgeInsets.fromLTRB(10.0, 30.0, 10.0, 20.0),
              hintText: "Search Car Maker",
              hintStyle: TextStyle(color: Colors.black),
            ),
            itemFilter: (item, query) {
              return item.employeeFullName
                  .toLowerCase()
                  .startsWith(query.toLowerCase());
            },
            itemSorter: (a, b) {
              return a.employeeFullName.compareTo(b.employeeFullName);
            },
            itemSubmitted: (item) {
              controller.text = item.employeeFullName;
            },
//          itemBuilder: (context, item) {
//          // ui for the autocomplete row
//          return row(item);
//        },
          ),
        ],
      ),
    );
  }

  Widget row(VisitPlanAddEmployee maker) {
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children: <Widget>[
        Text(
          maker.employeeFullName,
          style: TextStyle(color: Colors.blue),
        ),
        SizedBox(
          width: 5,
        ),
      ],
    );
  }

  _buildRow(context, 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,
        ),
      ),
    );
  }

  //===============================================================================================
  //                           Radio _radioValue_Customer
  //===============================================================================================

  _radioValue_Customer(String custCode, custName) {
    if (custCode == null) {
      custCode = "";
    }
    if (custName == null) {
      custName = "";
    }
    print(custCode + " " + custName);
    return SizedBox(
      child: Row(
        children: <Widget>[
          Radio(
            value: custCode + "|" + custName,
            groupValue: _radioValueResult,
            onChanged: (value) {
              setState(() {
                _radioValueResult = value;
                customerName.text = custName;
                customerCode.text = custCode;
              });
            },
          ),
        ],
      ),
    );
  }

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

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

  _buildTextMenu(context, text) {
    return Row(
      mainAxisAlignment: MainAxisAlignment.start,
      children: <Widget>[
        Text(
          text + " :",
          style: TextStyle(
              fontSize: mediaQuery(context, 'h', 38), 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: () {
          if (text == "บันทึก") {
            saveStaff();
          }
          if (text == "ยกเลิก") {
            page == "edit"
                ? Navigator.of(context).pushReplacement(
                    MaterialPageRoute(
                      settings:
                          const RouteSettings(name: '/visitPlanSaveWithoutId'),
                      builder: (context) => VisitingPlanSave(
                        dataDateTime: {
                          'strStartDate': strStartDate,
                          'strEndDate': strEndDate,
                          'strStartTime': startTime,
                          'strEndTime': endTime,
                          'visitId': visitId,
                          'visitObj': visitObj,
                          'visitcount': visitCount,
                          'visityear': visitYear,
                        },
                        // employeeData: data,
                      ),
                    ),
                  )
                : Navigator.of(context).pushReplacement(
                    MaterialPageRoute(
                      settings: const RouteSettings(name: '/visitPlanAdd'),
                      builder: (context) => VisitingPlanAdd(
                        dataDateTime: {
                          'strStartDate': strStartDate,
                          'strEndDate': strEndDate,
                          'strStartTime': startTime,
                          'strEndTime': endTime,
                          'visitId': visitId,
                          'visitObj': visitObj,
                          'visitcount': visitCount,
                          'visityear': visitYear,
                        },
                        // employeeData: data,
                      ),
                    ),
                  );
          }
        },
        child: Text(
          text,
          style: TextStyle(
            fontSize: 14.0,
            color: fontColor,
          ),
        ),
      ),
    );
  }

  saveStaff() async {
    if (_radioValueResult != null) {
      bool chk = await checkForm([
        _radioValueCustomerCode.text = _radioValueResult.split("|")[0],
        _radioValueCustomerName.text = _radioValueResult.split("|")[1],
      ]);
      print(chk.toString());
      if (chk == false) {
        alertForm(context, "แจ้งเตือน", "กรอกข้อมูลไม่ครบ");
      } else {
        setState(() {
          isLoading = true;
        });
        var data = {
          "customerCode": _radioValueCustomerCode.text, // รหัสพนักงาน
          "customerName": _radioValueCustomerName.text, //  ชื่อ - นามสกุล
          "description": description.text, //หัวหข้าคณะ
          "proposeTypename": proposeTypename.text, //เยี่ยมเยือนในฐานนะ
        };

        print(data);
        List<dynamic> mylist = [];

        await Future.delayed(const Duration(milliseconds: 1000));
        page == "edit"
            ? Navigator.of(context).pushReplacement(
                MaterialPageRoute(
                  settings:
                      const RouteSettings(name: '/visitPlanSaveWithoutId'),
                  builder: (context) => VisitingPlanSave(
                    visitIdEdit: null,
                    dataDateTime: {
                      'strStartDate': strStartDate,
                      'strEndDate': strEndDate,
                      'strStartTime': startTime,
                      'strEndTime': endTime,
                      'visitId': visitId,
                      'visitObj': visitObj,
                      'visitcount': visitCount,
                      'visityear': visitYear,
                    },
                    employeeData: data,
                  ),
                ),
              )
            : Navigator.of(context).pushReplacement(
                MaterialPageRoute(
                  settings: const RouteSettings(name: '/visitPlanAdd'),
                  builder: (context) => VisitingPlanAdd(
                    visitIdEdit: null,
                    dataDateTime: {
                      'strStartDate': strStartDate,
                      'strEndDate': strEndDate,
                      'strStartTime': startTime,
                      'strEndTime': endTime,
                      'visitId': visitId,
                      'visitObj': visitObj,
                      'visitcount': visitCount,
                      'visityear': visitYear,
                    },
                    employeeData: data,
                  ),
                ),
              );

        setState(() {
          isLoading = false;
        });
      }
    } else {
      alertForm(context, "แจ้งเตือน", "กรุณาเลือกพนักงาน");
    }
  }

  //==================================================================================================
  //                                       ค้นหาพนักงาน
  //==================================================================================================

  findStaff() async {
    bool accept = false;

    print("name : " + customerName.text);
    print("code : " + customerCode.text);

    if (customerName.text == "" && customerCode.text == "") {
      alertForm(context, "แจ้งเตือน", "กรอกข้อมูลไม่ครบ");
    } else {
      if (customerCode.text.isNotEmpty && customerName.text.isEmpty) {
        if (customerCode.text.length == 6) {
          customerCode.text = customerCode.text;
          accept = true;
        } else {
          accept = false;
          alertForm(context, "แจ้งเตือน", "รหัสพนักงานต้องมี 6 ตัว");
        }
      }

      if (customerName.text.isNotEmpty && customerCode.text.isEmpty) {
        if (customerName.text.trim().length > 3) {
          customerName.text = customerName.text;
          accept = true;
        } else {
          accept = false;
          alertForm(context, "แจ้งเตือน", "ชื่อ หรือ สกุล ต้อง 4 หลัก ขึ้นไป");
        }
      }

      if (customerName.text.isNotEmpty && customerCode.text.isNotEmpty) {
        if (customerName.text.length > 3 && customerCode.text.length == 6) {
          customerName.text = customerName.text;
          customerCode.text = customerCode.text;
          accept = true;
        } else if (customerName.text.length < 4 &&
            customerCode.text.length != 6) {
          accept = false;
          alertForm(context, "แจ้งเตือน",
              "ชื่อ หรือ สกุล ต้อง 4 หลัก ขึ้นไป \n รหัสพนักงานต้องมี 6 ตัว");
        } else if (customerName.text.length < 4 &&
            customerCode.text.length == 6) {
          accept = false;
          alertForm(context, "แจ้งเตือน", "ชื่อ หรือ สกุล ต้อง 4 หลัก ขึ้นไป");
        } else if (customerName.text.length > 3 &&
            customerCode.text.length != 6) {
          accept = false;
          alertForm(context, "แจ้งเตือน", "รหัสพนักงานต้องมี 6 ตัว");
        }
      }
    }

    if (accept) {
      setState(() {
        isLoading = true;
      });
      try {
        await Future.delayed(const Duration(milliseconds: 1000));
        final resultSearch = await VisitPlanAddEmployee.getEmployeeAll();
        print(resultSearch);
        VisitPlanAddEmployee.dataEmployee.clear(); //clear data

        if (resultSearch.isNotEmpty) {
          setState(() {
            resultSearch.forEach((v) {
              final dataList = VisitPlanAddEmployee.fromJson(v);
              VisitPlanAddEmployee.dataEmployee.add(dataList);
              setState(() {
                _radioValueResult = "";
              });
              if (VisitPlanAddEmployee.dataEmployee.length == 1) {
                customerName.text =
                    VisitPlanAddEmployee.dataEmployee[0].employeeFullName;
                customerCode.text =
                    VisitPlanAddEmployee.dataEmployee[0].employeeNumber;
                setState(() {
                  _radioValueResult =
                      customerCode.text + "|" + customerName.text;
                });
              }
            });
          });

          setState(() {
            customerName.text = "";
            customerCode.text = "";
            isLoading = false;
          });
        } else {
          VisitPlanAddEmployee.dataEmployee.clear();
          AppLoader.showInfo("ไม่พบข้อมูล");
          accept = false;
          customerName.text = "";
          customerCode.text = "";
          await Future.delayed(const Duration(milliseconds: 500));
          setState(() {
            isLoading = false;
          });
        }
      } catch (e) {
        setState(() {
          isLoading = false;
        });
        accept = false;
        customerName.text = "";
        customerCode.text = "";
        await Future.delayed(const Duration(milliseconds: 500));
        AppLoader.showInfo("ไม่พบข้อมูล");
        print(e);
      }
    }
  }
} //class

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

// Model
class VisitPlanAddEmployee {
  String employeeNumber;
  String employeeFullName;

  VisitPlanAddEmployee({
    this.employeeNumber,
    this.employeeFullName,
  });

  VisitPlanAddEmployee.fromJson(Map<String, dynamic> json) {
    employeeNumber = json['EmployeeNumber'];
    employeeFullName = json['EmployeeFullName'];
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = Map<String, dynamic>();
    data['EmployeeNumber'] = this.employeeNumber;
    data['EmployeeFullName'] = this.employeeFullName;

    return data;
  }

  static List<VisitPlanAddEmployee> dataEmployee = [];

  static getEmployeeAll() async {
    print(
      AppUrl.VisitPlanEmployee_Search +
          "?EmployeeNumber=" +
          customerCode.text /*AppUrl.EmpID*/ +
          "&EmployeeFullname=" +
          customerName.text +
          "&authenKey=" +
          AppUrl.AuthenKey,
    );
    final response = await AppApi.apiGetRequest(
      AppUrl.VisitPlanEmployee_Search +
          "?EmployeeNumber=" +
          customerCode.text.trim() /*AppUrl.EmpID*/ +
          "&EmployeeFullname=" +
          customerName.text.trim() +
          "&authenKey=" +
          AppUrl.AuthenKey,
    ); // เรียกใช้ api

    return response;
  }
}

class VisitPlanEmployee {
  String employeeNumber;
  String employeeFullName;

  VisitPlanEmployee(
    this.employeeNumber,
    this.employeeFullName,
  );

  static List<VisitPlanEmployee> getListEmployee() {
    List<VisitPlanEmployee> list = List<VisitPlanEmployee>();
    for (var i = 0; i < VisitPlanAddEmployee.dataEmployee.length; i++) {
      list.add(
        VisitPlanEmployee(
          VisitPlanAddEmployee.dataEmployee[i].employeeNumber.toString(),
          VisitPlanAddEmployee.dataEmployee[i].employeeFullName.toString(),
        ),
      );
    }
    return list;
  }
}
