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

//CustomerList model
class ResponsibleElectric extends StatefulWidget {
  @override
  _ResponsibleElectricState createState() => _ResponsibleElectricState();
}

class _ResponsibleElectricState extends State<ResponsibleElectric> {
  TextEditingController numberCustomer = TextEditingController();
  TextEditingController companyName = TextEditingController();
  TextEditingController branchName = TextEditingController();
  bool isLoading = false;
  String electric = 'เลือก';
  String customerSelect = "";
  List<String> electricList = ['เลือก', 'One', 'Two', 'Three', 'Four'];

  String branchPEASelect = ''; // การไฟฟ้า

  @override
  void initState() {
    super.initState();
    CustomerList.dataSearch = [];
  }

  Map<String, dynamic> listS;

  searchData() async {
    setState(() {
        isLoading = true;
      });
    try{
      final listSearch = await CustomerList.customerListSearchData(
        numberCustomer.text,
        companyName.text,
        branchName.text,
      ); //  ไปเรียกฟังชั่นดึงข้อมูลจาก api และเะิ่ม Parameter ค้นห้าด้วย

      setState(() {
        listSearch.forEach((v) {
          final customerNewList = CustomerList.fromJsonSearch(v);
          CustomerList.dataSearch.add(customerNewList);
        });
        isLoading = false;
      });
    }catch(e){
      setState(() {
        isLoading = false;
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    if (isLoading == true) {
      AppLoader.show();
    }
    if (isLoading == false) {
      AppLoader.hide();
    }
    double _width = MediaQuery.of(context).size.width;
    return Material(
      color: AppColors.bgColor,
      child: Stack(
        children: <Widget>[
          Header.header2(context),
          Header.mainMenu(context),
          Container(
            width: _width,
            height: mediaQuery(context, 'h', 1800),
            margin: EdgeInsets.only(
              top: mediaQuery(context, 'h', 400),
              left: mediaQuery(context, 'w', 40),
              right: mediaQuery(context, 'w', 40),
            ),
            child: SingleChildScrollView(
              child: Column(
                children: <Widget>[
                  Container(
                    margin: EdgeInsets.only(
                      top: mediaQuery(context, 'h', 30),
                      bottom: mediaQuery(context, 'h', 50),
                    ),
                    child: Text(
                      'การไฟฟ้าที่รับผิดชอบ',
                      textAlign: TextAlign.center,
                      style: TextStyle(
                        color: Color(0xFFB58E38),
                        fontSize: mediaQuery(context, 'h', 50),
                      ),
                    ),
                  ),
                  Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: <Widget>[
                      Text(
                        'หมายเลขผู้ใช้ไฟฟ้า (CA) :',
                        textAlign: TextAlign.center,
                        style: TextStyle(
                          fontSize: mediaQuery(context, 'h', 34),
                          color: Color(0xFF383838),
                        ),
                      ),
                      SizedBox(
                        height: mediaQuery(context, 'h', 20),
                      ),
                      SizedBox(
                        height: mediaQuery(context, 'h', 195),
                        child: TextField(
                          maxLength: 12,
                          keyboardType: TextInputType.number,
                          controller: numberCustomer,
                          enabled: true,
                          decoration: InputDecoration(
                            contentPadding: const EdgeInsets.symmetric(
                                vertical: 30.0, horizontal: 15.0),
                            border: OutlineInputBorder(
                              borderRadius: const BorderRadius.all(
                                const Radius.circular(50.0),
                              ),
                            ),
                            filled: true,
                            hintStyle: TextStyle(color: Colors.grey[800]),
                            fillColor: Colors.white70,
                          ),
                        ),
                      ),
                    ],
                  ),
                  SizedBox(
                    height: mediaQuery(context, 'h', 10),
                  ),
                  Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: <Widget>[
                      Text(
                        'ชื่อบริษัท :',
                        textAlign: TextAlign.center,
                        style: TextStyle(
                          fontSize: mediaQuery(context, 'h', 34),
                          color: Color(0xFF383838),
                        ),
                      ),
                      SizedBox(
                        height: mediaQuery(context, 'h', 20),
                      ),
                      SizedBox(
                        height: mediaQuery(context, 'h', 130),
                        child: TextField(
                          controller: companyName,
                          enabled: true,
                          decoration: InputDecoration(
                              contentPadding: const EdgeInsets.symmetric(
                                  vertical: 10.0, horizontal: 15),
                              border: OutlineInputBorder(
                                borderRadius: const BorderRadius.all(
                                  const Radius.circular(50.0),
                                ),
                              ),
                              filled: true,
                              hintStyle: TextStyle(color: Colors.grey[800]),
                              fillColor: Colors.white70),
                        ),
                      ),
                    ],
                  ),
                  SizedBox(
                    height: mediaQuery(context, 'h', 70),
                  ),
                  Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: <Widget>[
                      Text(
                        'การไฟฟ้า :',
                        textAlign: TextAlign.center,
                        style: TextStyle(
                          fontSize: mediaQuery(context, 'h', 34),
                          color: Color(0xFF383838),
                        ),
                      ),
                      SizedBox(
                        height: mediaQuery(context, 'h', 20),
                      ),
                      SizedBox(
                        height: mediaQuery(context, 'h', 130),
                        child: TextField(
                          controller: branchName,
                          enabled: true,
                          decoration: InputDecoration(
                              contentPadding: const EdgeInsets.symmetric(
                                  vertical: 10.0,
                                  horizontal:
                                      15), //ปรับตำแหน่งcursor เริ่มต้นในช่องข้อความ
                              border: OutlineInputBorder(
                                borderRadius: const BorderRadius.all(
                                  const Radius.circular(50.0),
                                ),
                              ),
                              filled: true,
                              hintStyle: TextStyle(color: Colors.grey[800]),
                              fillColor: Colors.white70),
                        ),
                      ),
                    ],
                  ),
                  SizedBox(
                    height: mediaQuery(context, 'h', 90),
                  ),
                  GestureDetector(
                    // ปุ่มค้นหา
                    onTap: () async {
                      search();
                    },
                    child: Container(
                      width: mediaQuery(context, 'w', 1005),
                      height: mediaQuery(context, 'h', 150),
                      decoration: BoxDecoration(
                        borderRadius: BorderRadius.all(
                          Radius.circular(
                            mediaQuery(context, 'h', 100),
                          ),
                        ),
                        boxShadow: [
                          appShadow(),
                        ],
                        color: AppColors.color_gold,
                      ),
                      child: Center(
                        child: Text(
                          'ค้นหา',
                          textAlign: TextAlign.center,
                          style: TextStyle(
                            fontSize: mediaQuery(context, 'h', 50),
                            color: Colors.white,
                          ),
                        ),
                      ),
                    ),
                  ),
                  SizedBox(
                    height: mediaQuery(context, 'h', 40),
                  ),
                  Column(
                      children: List.generate(CustomerList.dataSearch.length,
                          (index) {
                    customerSelect = CustomerList.dataSearch[index].customerId;

                    return _buildContent(
                      context,
                      (index + 1).toString(),
                      CustomerList.dataSearch[index].ca,
                      CustomerList.dataSearch[index].customerName,
                      CustomerList.dataSearch[index].address,
                      CustomerList.dataSearch[index].customerId,
                    );
                  })),
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }

  search() async {
    if (numberCustomer.text.length == 12 && numberCustomer.text.isNotEmpty ||
        companyName.text.isNotEmpty ||
        branchName.text.length > 0) {
      searchData();
    } else {
      alertForm(context, "แจ้งเตือน", "กรอกข้อมูลไม่ครบ");
    }
  }

  _buildContent(
    context,
    number,
    cA,
    company,
    electric,
    userId,
  ) {
    return GestureDetector(
      onTap: () async {
//        Nav.push(context, saveData(context, user_id),);
      },
      child: Container(
        width: mediaQuery(context, 'w', 1005),
        //      height: mediaQuery(context, 'h', 380),
        padding: EdgeInsets.all(
          mediaQuery(context, 'h', 50),
        ),
        margin: EdgeInsets.only(
          bottom: mediaQuery(context, 'h', 40),
        ),
        decoration: BoxDecoration(
          borderRadius: BorderRadius.all(
            Radius.circular(
              mediaQuery(context, 'h', 20),
            ),
          ),
          boxShadow: [
            appShadow(),
          ],
          color: Colors.white,
        ),
        child: Row(
          children: <Widget>[
            Container(
              width: mediaQuery(context, 'w', 810),
              child: Column(
                children: <Widget>[
                  Row(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: <Widget>[
                      Text(
                        'ลำดับ : ',
                        style: TextStyle(
                          color: AppColors.color_text,
                          fontSize: mediaQuery(context, 'h', 42),
                        ),
                      ),
                      Text(
                        number,
                        style: TextStyle(
                          color: AppColors.color_text,
                          fontSize: mediaQuery(context, 'h', 40),
                        ),
                      ),
                    ],
                  ),
                  Row(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: <Widget>[
                      Text(
                        'หมายเลขผู้ใช้ไฟฟ้า (CA) : ',
                        style: TextStyle(
                          color: AppColors.color_text,
                          fontSize: mediaQuery(context, 'h', 42),
                        ),
                      ),
                      Text(
                        cA,
                        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),
                        ),
                      ),
                      Flexible(
                        child: Text(
                          company,
                          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),
                        ),
                      ),
                      Flexible(
                        child: Text(
                          electric,
                          style: TextStyle(
                            color: AppColors.color_text,
                            fontSize: mediaQuery(context, 'h', 40),
                          ),
                        ),
                      ),
                    ],
                  ),
                ],
              ),
            ),
            Container(
              width: mediaQuery(context, 'w', 100),
              alignment: Alignment.centerRight,
              child: GestureDetector(
                onTap: () {
                  if (customerSelect.isNotEmpty) {
                    setState(() {
                      customerSelect = userId;
                      print(" Select :: " + customerSelect);
                    });
                    CustomerList.saveDataNewCustom(context, customerSelect);
                  }
                },
                child: Icon(
                  Icons.add_circle_outline,
                  size: mediaQuery(context, 'h', 80),
                  color: AppColors.color,
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
} //class

class KeyValueModel {
  String key;
  String value;

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

class AddCustomer {
  String saleInfoId;
  String customerId;
  String authenKey;

  AddCustomer({
    this.saleInfoId,
    this.customerId,
    this.authenKey,
  });

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = Map<String, dynamic>();
    data['saleInfoId'] = AppUrl.EmpID;
    data['customerId'] = this.customerId;
    data['authenKey'] = AppUrl.AuthenKey;
    return data;
  }
}
