import 'package:get/get.dart';
import 'package:flutter/material.dart';
import 'package:flutter/cupertino.dart';
import 'package:font_awesome_flutter/font_awesome_flutter.dart';

import 'package:mwf_app/service/url.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/service/strings.dart';
import 'package:mwf_app/service/navigator.dart';
import 'package:mwf_app/service/notification_count.dart';

import 'package:mwf_app/model/customer_list_model.dart';

import 'package:mwf_app/home.dart';
import 'package:mwf_app/set1/serve_customers.dart';
import 'package:mwf_app/set2/responsible_electric.dart';

class ListCustomer extends StatefulWidget {
  @override
  _ListCustomerState createState() => _ListCustomerState();
}

class _ListCustomerState extends State<ListCustomer> {
  bool isLoading = false;

  @override
  void initState() {
    super.initState();
    Header.routes = HomePage();
    print("ListCustomer screen");
    print("AppUrl.EmpID : " + AppUrl.EmpID.toString());
    print("AppUrl.EmployeeID : " + NotificationCount.getPrefString('EmployeeID'));
    print("AppStrings.userID : " + AppStrings.userID.toString());
    print("AppStrings.empID : " + AppStrings.empID.toString());
    print("AppUrl.employeeEmpID : " + AppUrl.employeeEmpID.toString());
    print("Full name : " + AppStrings.profileFullName);
    loadData();
  }

  loadData() async {
    try {
      isLoading = true;
      final listCus = await CustomerList.getListCustomerAPI();
      setState(() {
        listCus.forEach((v) {
          final employeeList = CustomerList.fromJson(v);
          CustomerList.dataContact.add(employeeList);
        });
      });

      setState(() {
        isLoading = false;
      });
    } catch (e) {
      setState(() {
        isLoading = false;
      });
      print(e);
    }
  }

  @override
  Widget build(BuildContext context) {
    Header.currentPage = "";
    if (isLoading == true) {
      AppLoader.show();
    }
    if (isLoading == 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.header2ListPage(context),
            Header.mainMenu(context),
            Container(
              width: _width,
              height: mediaQuery(context, 'h', 1800),
              margin: EdgeInsets.only(
                top: mediaQuery(context, 'h', 400),
                left: mediaQuery(context, 'w', 60),
                right: mediaQuery(context, 'w', 60),
              ),
              child: SingleChildScrollView(
                child: Column(
                  children: <Widget>[
                    Container(
                      alignment: Alignment.center,
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: <Widget>[
                          Container(
                            width: mediaQuery(context, 'w', 200),
                          ),
                          GestureDetector(
                            onTap: () {
                              saveData(context);
                            },
                            child: Text(
                              'รายชื่อลูกค้า',
                              style: TextStyle(
                                color: Color(0xFFB58E38),
                                fontSize: mediaQuery(context, 'h', 58),
                              ),
                            ),
                          ),
                          GestureDetector(
                            onTap: () {
                              Nav.push(
                                context,
                                ResponsibleElectric(),
                              );
                            },
                            child: Row(
                              children: <Widget>[
                                Icon(
                                  Icons.add_circle_outline,
                                  size: mediaQuery(context, 'h', 80),
                                  color: AppColors.color,
                                ),
                                SizedBox(
                                  width: mediaQuery(context, 'w', 14),
                                ),
                                Text(
                                  'เพิ่มลูกค้า',
                                  style: TextStyle(
                                    color: AppColors.color,
                                    fontSize: mediaQuery(context, 'h', 34),
                                  ),
                                ),
                              ],
                            ),
                          )
                        ],
                      ),
                    ),
                    Container(
                      height: mediaQuery(context, 'h', 1700),
                      child: ListView(
                        shrinkWrap: true,
                        padding: EdgeInsets.only(
                          top: mediaQuery(context, 'h', 40),
                        ),
                        children: <Widget>[
                          Column(
                            children: listCustomer(_width),
                          ),
                        ],
                      ),
                    ),
                  ],
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  List<Widget> listCustomer(double width) {
    List<Widget> list = new List();

    for (var i = 0; i < CustomerList.dataContact.length.toInt(); i++) {
      list.add(
        GestureDetector(
          onTap: () async {
            String idNull = "00000000-0000-0000-0000-000000000000";
            if (CustomerList.dataContact[i].customerId == idNull) {
              alertForm(context, "แจ้งเตือน", "ไม่มีข้อมูล");
              return;
            }
            final headCustomer = await CustomerList.getCustomerHead(
                CustomerList.dataContact[i].customerId);
            // print(CustomerList.dataContact[i].address);
            if (headCustomer[0]['customerName'] == null ||
                headCustomer[0]['customerName'] == null ||
                headCustomer[0]['ca'] == null ||
                headCustomer[0]['customerAddress'] == null) {
              AppStrings.serviceCompanyName = "";
              AppStrings.serviceElectricityUserNumberName = "";
              AppStrings.serviceElectricityUserAddress = "";
              AppStrings.serviceElectricityUserTSICDetail =
                  ""; //headCustomer[0]['TSICID'].toString() + " | " + headCustomer[0]['TSICName'].toString();
              AppStrings.serviceElectricityNameDetail =
                  ""; //headCustomer[0]['BranchID'].toString() + " | " + headCustomer[0]['Branchname'].toString();
              AppStrings.customerID = "";
            } else {
              AppStrings.serviceCompanyName = headCustomer[0]['customerName'];
              AppStrings.serviceElectricityUserNumberName =
                  headCustomer[0]['ca'];
              AppStrings.serviceElectricityUserAddress =
                  CustomerList.dataContact[i].address;
              AppStrings.serviceElectricityUserTSICDetail =
                  headCustomer[0]['TSICID'].toString() +
                      " | " +
                      headCustomer[0]['TSICName'].toString();
              AppStrings.serviceElectricityNameDetail =
                  headCustomer[0]['BranchID'].toString() +
                      " | " +
                      headCustomer[0]['Branchname'].toString();
              AppStrings.customerID = headCustomer[0]['customerId'];
              AppUrl.CustomerID = AppStrings.customerID;
              AppUrl.CA = AppStrings.serviceElectricityUserNumberName;
            }

            Nav.push(
              context,
              ServeCustomer(),
            );
          },
          child: Container(
//            width: mediaQuery(context, 'w', 1005),
            padding: EdgeInsets.all(
              mediaQuery(context, 'h', 50),
            ),
            margin: EdgeInsets.only(
              bottom: mediaQuery(context, 'h', 40),
            ),
            decoration: BoxDecoration(
              borderRadius: new BorderRadius.all(
                Radius.circular(
                  mediaQuery(context, 'h', 20),
                ),
              ),
              boxShadow: [
                appShadow(),
              ],
              color: Colors.white,
            ),
            child: Row(
              children: <Widget>[
                Container(
                  width: mediaQuery(context, 'w', 800),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: <Widget>[
                      Text(
                        CustomerList.dataContact[i].ca ?? "ไม่มีข้อมูล",
//                        employeeLists[i].id,
                        style: TextStyle(
                          color: AppColors.color_text,
                          fontSize: mediaQuery(context, 'h', 50),
                        ),
                      ),
                      Text(
//                        employeeLists[i].id,
                        CustomerList.dataContact[i].customerName ??
                            "ไม่มีข้อมูล",
                        style: TextStyle(
                          color: AppColors.color_text,
                          fontSize: mediaQuery(context, 'h', 40),
                        ),
                      ),
                      Container(
                        width: mediaQuery(context, "w", 700),
                        child: Text(
//                          employeeLists[i].id,
                          CustomerList.dataContact[i].address ?? "ไม่มีข้อมูล",
                          style: TextStyle(
                            color: AppColors.color_text,
                            fontSize: mediaQuery(context, 'h', 40),
                          ),
                        ),
                      )
                    ],
                  ),
                ),
                Container(
                  width: mediaQuery(context, 'w', 3),
                  height: mediaQuery(context, 'h', 200),
                  color: Color(0xFFD3DADC),
                ),
                Container(
                  width: mediaQuery(context, 'w', 100),
                  alignment: Alignment.centerRight,
                  child: GestureDetector(
                    onTap: () {
                      setState(() {
                        isLoading = true;
                      });
                      setState(() {
                        String idNull = "00000000-0000-0000-0000-000000000000";
                        CustomerList.dataContact[i].customerSaleInfoId != idNull
                            ? CustomerList.del(
                                context,
                                i,
                                CustomerList.dataContact[i].customerSaleInfoId
                                    .toString())
                            : alertForm(context, "แจ้งเตือน", "ไม่มีข้อมูล");
                      });

                      setState(() {
                        isLoading = false;
                      });
                    },
                    child: Icon(
                      FontAwesomeIcons.trashAlt,
                      color: AppColors.color_gold,
                    ),
                  ),
                ),
              ],
            ),
          ),
        ),
      );
    }

    return list;
  }

  saveData(context) async {
    Map<String, dynamic> data = {
      "customerListID": "1234",
      "employeeID": "5678",
      "cA": "91012",
      "customerName": "testAddData",
      "province": "chan",
      "authenKey": "4df7b5c8-f643-4936-baff-9fb69671c07a",
      "address": "25 กรุงเพท"
    };
    final listCus = await CustomerList.saveData(context, data);
    print(listCus);
  }
} //class

showConfirm(context, title, message, textConfirm, action) {
  return showDialog(
    barrierDismissible: false,
    context: context,
    builder: (BuildContext context) {
      return Center(
        child: AlertDialog(
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.all(
              Radius.circular(
                mediaQuery(context, 'h', 50),
              ),
            ),
          ),
          title: Column(
            children: <Widget>[
              Container(
                child: Image.asset(
                  'assets/images/question.png',
                  width: mediaQuery(context, 'w', 200),
                  height: mediaQuery(context, 'h', 200),
                ),
              ),
            ],
          ),
          content: Container(
            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: <Widget>[
                Text(
                  title,
                  style: TextStyle(
                    fontWeight: FontWeight.bold,
                    fontSize: mediaQuery(context, 'h', 60),
                  ),
                  textAlign: TextAlign.center,
                ),
                SizedBox(
                  height: mediaQuery(context, 'h', 10),
                ),
                Text(
                  message,
                  style: TextStyle(
                    fontSize: mediaQuery(context, 'h', 46),
                  ),
                  textAlign: TextAlign.center,
                ),
                SizedBox(
                  height: mediaQuery(context, 'h', 40),
                ),
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: <Widget>[
                    ButtonTheme(
                      minWidth: mediaQuery(context, 'h', 320),
                      height: mediaQuery(context, 'h', 120),
                      child: RaisedButton(
                        color: Colors.white,
                        shape: new RoundedRectangleBorder(
                          borderRadius: new BorderRadius.circular(
                            mediaQuery(context, 'h', 50),
                          ),
                          side: BorderSide(
                            color: AppColors.color.withOpacity(0.51),
                          ),
                        ),
                        onPressed: () {},
                        splashColor: AppColors.color,
                        child: Text(
                          textConfirm,
                          style: TextStyle(
                            color: AppColors.color,
                            fontSize: mediaQuery(context, 'h', 46),
                          ),
                        ),
                      ),
                    ),
                    SizedBox(
                      width: mediaQuery(context, 'w', 20),
                    ),
                    ButtonTheme(
                      minWidth: mediaQuery(context, 'h', 320),
                      height: mediaQuery(context, 'h', 120),
                      child: RaisedButton(
                        color: Colors.white,
                        shape: new RoundedRectangleBorder(
                          borderRadius: new BorderRadius.circular(
                            mediaQuery(context, 'h', 50),
                          ),
                          side: BorderSide(
                            color: AppColors.color.withOpacity(0.51),
                          ),
                        ),
                        onPressed: () {
                          Navigator.of(context).pop(false);
                        },
                        splashColor: AppColors.color,
                        child: Text(
                          "ยกเลิก",
                          style: TextStyle(
                            color: AppColors.color,
                            fontSize: mediaQuery(context, 'h', 46),
                          ),
                        ),
                      ),
                    ),
                  ],
                ),
              ],
            ),
          ),
        ),
      );
    },
  );
}
