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/style.dart';
import 'package:mwf_app/service/url.dart';
import 'package:mwf_app/model/customer_contact.dart';
import 'package:nextflow_thai_personal_id/nextflow_thai_personal_id.dart';

class CustomerRepresentativeAdd extends StatefulWidget {
  @override
  _CustomerRepresentativeAddState createState() =>
      _CustomerRepresentativeAddState();
}

class _CustomerRepresentativeAddState extends State<CustomerRepresentativeAdd> {
  TextEditingController name = TextEditingController(); // ชื่อผู้ติดต่อ
  TextEditingController lastName = TextEditingController(); // นามสกุล
  TextEditingController position = TextEditingController(); // ตำแหน่ง
  TextEditingController phone = TextEditingController(); // เบอร์โทรศัพท์
  TextEditingController personCardId = TextEditingController(); // เบอร์โทรศัพท์
  TextEditingController contact =
      TextEditingController(); // ช่องทางการติดต่ออื่น ๆ
  bool isLoading = false;
  bool isIdCardValid = true;
  ThaiIdValidator validator = ThaiIdValidator();

  @override
  void initState() {
    super.initState();
  }

  @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 GestureDetector(
      onTap: (){
        FocusScope.of(context).unfocus();
      },
      child: Material(
        color: AppColors.bgColor,
        child: Stack(
          children: <Widget>[
            Header.header1(context),
            Header.mainMenu(context),
            Container(
              margin: EdgeInsets.only(
                top: mediaQuery(context, 'h', 950),
              ),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: <Widget>[
                  Text(
                    "รายชื่อผู้แทนลูกค้า",
                    style: AppStyle.headTextStyle(context),
                  )
                ],
              ),
            ),
            Container(
                //color: Colors.red,
                width: _width,
                //height: mediaQuery(context, 'h', 2277),
                height: mediaQuery(context, 'h', 1150),
                margin: EdgeInsets.only(
                  top: mediaQuery(context, 'h', 1050),
                  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, "ชื่อผู้ติดต่อ"),
                        _buildSizeBox(context),
                        Row(
                          children: <Widget>[
                            _buildRow(context, name),
                          ],
                        ),
                        _buildSizeBox(context),
                        _buildTextMenu(context, "นามสกุล"),
                        _buildSizeBox(context),
                        Row(
                          children: <Widget>[
                            _buildRow(context, lastName),
                          ],
                        ),
                        _buildSizeBox(context),
                        _buildTextMenuNotRequred(context, "ตำแหน่ง"),
                        _buildSizeBox(context),
                        Row(
                          children: <Widget>[
                            _buildRow(context, position),
                          ],
                        ),
                        _buildSizeBox(context),
                        _buildTextMenu(context, "หมายเลขโทรศัพท์"),
                        _buildSizeBox(context),
                        Row(
                          children: <Widget>[
                            _buildRowTelNumber(context, phone),
                          ],
                        ),
                        _buildSizeBox(context),
                        _buildTextMenuNotRequred(context, "ช่องทางติดต่ออื่นๆ"),
                        _buildSizeBox(context),
                        _buildTextArea(context),
                        _buildSizeBox(context),
                        _buildTextMenuNotRequred(context, "หมายเลขบัตรประชาชน"),
                        _buildSizeBox(context),
                        Row(
                          children: <Widget>[
                            _buildRowIdCard(context, personCardId),
                          ],
                        ),
                        _buildSizeBox(context),
                        _buildSizeBox(context),
                        _buildSizeBox(context),
                        Row(
                          mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                          children: <Widget>[
                            _buildButtonCancel(
                              context,
                            ),
                            _buildButtonSave(
                              context,
                            ),
                          ],
                        ),
                        SizedBox(
                          height: mediaQuery(context, 'h', 40),
                        )
                      ],
                    ),
                  ),
              ),
          ],
        ),
      ),
    );
  }

  _buildTextArea(context) {
    return TextField(
      controller: contact,
      maxLines: 4,
      decoration: InputDecoration(
        filled: true,
        fillColor: Colors.white,
        border: new OutlineInputBorder(
          borderRadius: const BorderRadius.all(
            const Radius.circular(10.0),
          ),
        ),
        hintText: "",
        labelText: '',
      ),
    );
  }

  _buildButtonCancel(context) {
    return ButtonTheme(
      minWidth: mediaQuery(context, "w", 477),
      height: mediaQuery(context, "h", 120),
      child: FlatButton(
        shape: new RoundedRectangleBorder(
            borderRadius: new 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('ยกเลิก');
          Navigator.of(context).pop(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: new RoundedRectangleBorder(
            borderRadius: new 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: () {
          setState(() {
            isLoading = true;
          });
          saveCustomerContact(context);
        },
        child: Text(
          'บันทึก',
          style: TextStyle(
            fontSize: 14.0,
            color: Colors.white,
          ),
        ),
      ),
    );
  }

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

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

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

  saveCustomerContact(context) async {
    if (await checkForm([
          name.text,
          lastName.text,
          phone.text,
        ]) ==
        false) {
      setState(() {
        isLoading = false;
      });
      alertForm(context, "แจ้งเตือน", "กรอกข้อมูลไม่ครบ");
    } else {
      Map<String, dynamic> data = {
//        "EmployeeID": "934023",
//        "CustomerName": "สหการประมูล",
//        "CA": "020000039829",
//        "CustomerAddress": "ต.บ้านใหม่ อ.อรัญประเทศ จ.สระแก้ว 27120",
//        "EmployeeID": AppUrl.EmpID,
//        "CustomerName":  AppStrings.serviceCompanyName,
//        "CA":  AppStrings.serviceElectricityUserNumberName,
//        "CustomerAddress": AppStrings.serviceElectricityUserAddress,
//        "Employeename": name.text,
//        "EmployeeSurname": lastName.text,
//        "EmployeePosition": position.text,
//        "EmployeePhone": phone.text,
        "customerId": AppUrl.CustomerID.toString(),
        "firstName": name.text.toString(),
        "lastName": lastName.text.toString(),
        "position": position.text.toString(),
        "contactTel": phone.text.toString(),
        "contactEtc": contact.text.toString(),
        "citizenNumber": personCardId.text,
        "authenKey": AppUrl.AuthenKey.toString()
      };
      print(data);
      await new Future.delayed(const Duration(milliseconds: 1000));
      CustomerContact.saveData(context, data);
    }
  }
}
