import 'package:flutter/material.dart';
import 'package:mwf_app/service/api.dart';
import 'package:mwf_app/service/color.dart';
import 'package:mwf_app/service/loader.dart';
import 'package:mwf_app/service/navigator.dart';
import 'package:mwf_app/service/screen.dart';
import 'package:mwf_app/service/url.dart';
import 'package:mwf_app/home.dart';
import 'package:mwf_app/set2/list_customer.dart';

class CustomerList {
  String customerSaleInfoId;
  String customerId;
  String ca;
  String customerName;
  String address;
  String peaRegionText;
  String saleInfoId;
  String authenKey;

  CustomerList({
    this.customerSaleInfoId,
    this.customerId,
    this.ca,
    this.customerName,
    this.address,
    this.peaRegionText,
    this.saleInfoId,
    this.authenKey,
  });

  static getBranchPEA() async {
    final response = await AppApi.apiGetRequest(
        'http://202.6.26.23/PEACRM.WebAPI/api/MobileWorkforce/Voice_Electricity_ReadList?authenKey=4df7b5c8-f643-4936-baff-9fb69671c07a'); // เรียกใช้ api
    return response;
  }

  static customerListSearchData(
      String ca, String customerName, String peaRegion) async {
    print("---- CA: " +
        ca +
        " Name: " +
        customerName +
        " Branch: " +
        peaRegion +
        " EMID : " +
        AppUrl.userID);
    final response = await AppApi.apiGetRequest(
      AppUrl.CustomerList_Search +
          "?ca=" +
          ca +
          "&customerName=" +
          customerName +
          "&peaRegion=" +
          peaRegion +
          "&authenKey=" +
          AppUrl.AuthenKey,
    ); // เรียกใช้ api
    //print(response);
    dataSearch.clear();
    return response;
  }

  static getData() async {
    final response = await AppApi.apiGetRequest(
      AppUrl.CustomerList_ReadList +
          "?saleInfoId=" +
          AppUrl.userID +
          "&AuthenKey=" +
          AppUrl.AuthenKey,
    ); // เรียกใช้ api
    data.clear(); // เคลียข้อมูลเดิมออกก่อน
    return response;
  }

  static saveData(context, Map<String, dynamic> data) async {
    final response =
        await AppApi.post(AppUrl.CustomerList_Create, data); // เรียกใช้ api
    print(response);
    if (response['statusCode'] == 200) {
      //Nav.push(context, Schedule());
    }
  }

  /*
   {
     "saleInfoId":"saleInfoId", คือ  AppUrl.EmpID
     "customerId":"customerId", คือ customerId ส่งมาจากการเลือก ลูกค้า
     "authenKey":"authenKey"
   }
   */
  static saveDataNewCustom(context, customerId) async {
//    Map<String, dynamic> data = {
//      "saleInfoId": AppUrl.EmpID,
//      "customerId":customerId,
//      "authenKey": AppUrl.AuthenKey
//    };

    Map<String, dynamic> data = {
      "SaleInfoId": AppUrl.userID.toString(),
      "CustomerId": customerId.toString(),
      "AuthenKey": AppUrl.AuthenKey.toString()
    };

    final response = await AppApi.postWithMap(
        AppUrl.CustomerList_Create, data); // เรียกใช้ api
    print(response);
    if (response['statusCode'] == 200) {
      //Nav.push(context, Schedule());
//      alertConfirm(context, "แจ้งเตือน", "เพิ่มรายชื่อลูกค้าเรียบร้อย");
      AppLoader.showSuccess('เพิ่มรายชื่อลูกค้าเรียบร้อย');
      Navigator.of(context).pop(true);
      Nav.push(context, ListCustomer());
    } else {
//      alertConfirm(context, "แจ้งเตือน", "เพิ่มรายชื่อลูกค้าเไม่สำเร็จ");
      AppLoader.showError('เพิ่มรายชื่อลูกค้าไม่สำเร็จเนื่องจาก มีพนักงานดูแลลูกค้าในช่วงเวลานี้อยู่แล้ว');
    }
  }

  static deleteData(
    context,
    String customerSaleInfoId,
    int index,
  ) async {
    Map<String, dynamic> data = {
      "CustomerSaleInfoId": customerSaleInfoId.toString(),
      "AuthenKey": AppUrl.AuthenKey.toString()
    };
    final response = await AppApi.postWithMap(
        AppUrl.CustomerCare_Delete, data); // เรียกใช้ api

    if (response['statusCode'] == 200) {
//      getListCustomerAPI();
      AppLoader.showSuccess('ลบสำเร็จ');
      CustomerList.dataContact.removeAt(index);
      await Future.delayed(const Duration(seconds: 2));
      Navigator.pushReplacement(
          context, MaterialPageRoute(builder: (context) => HomePage()));
      return true;
    } else {
      return false;
    }
  }

  static updateData(
    context,
    String customerSaleInfoId,
    String customerId,
    String cA,
    String customerName,
    String peaRegionText,
    String saleInfoId,
    String authenKey,
    String address,
  ) async {
    Map<String, dynamic> data = {
      "CustomerSaleInfoId": customerSaleInfoId,
      "CustomerId": customerId,
      "CA": cA,
      "CustomerName": customerName,
      "PeaRegionText": peaRegionText,
      "saleInfoId": saleInfoId,
      "Address": address,
      "AuthenKey": AppUrl.AuthenKey
    };
    final response =
        await AppApi.post(AppUrl.CustomerList_Update, data); // เรียกใช้ api

    if (response['statusCode'] == 200) {
      return true;
    } else {
      return false;
    }
  }

  static List<CustomerList> dataSearch = []; // ตัวแปรที่จะเรียกใช้งาน

  CustomerList.fromJsonSearch(Map<String, dynamic> json) {
    customerSaleInfoId = json['CustomerSaleInfoId'];
    customerId = json['CustomerId'];
    ca = json['Ca'];
    customerName = json['CustomerName'];
    address = json['Address'];
    peaRegionText = json['PeaRegionText'];
//    saleInfoId = json['saleInfoId'];
//    authenKey = json['authenKey'];
  }
  static List<CustomerList> data = []; // ตัวแปรที่จะเรียกใช้งาน

  CustomerList.fromJson(Map<String, dynamic> json) {
    customerSaleInfoId = json['CustomerSaleInfoId'];
    customerId = json['CustomerId'];
    ca = json['Ca'];
    customerName = json['CustomerName'];
    address = json['Address'];
    peaRegionText = json['PeaRegionText'];
//    saleInfoId = json['saleInfoId'];
//    authenKey = json['authenKey'];
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = Map<String, dynamic>();
    data['CustomerSaleInfoId'] = this.customerSaleInfoId;
    data['CustomerId'] = this.customerId;
    data['Ca'] = this.ca;
    data['CustomerName'] = this.customerName;
    data['Address'] = this.address;
    data['PeaRegionText'] = this.peaRegionText;
//    data['saleInfoId'] = this.saleInfoId;
//    data['authenKey'] = this.authenKey;
    return data;
  }

  static List<CustomerList> dataContact = [];
  static getListCustomerAPI() async {
//    final response = await AppApi.apiGetRequest(AppUrl.CustomerList_ReadList);
    print(AppUrl.CustomerList_ReadList +
        "?SaleInfoId=" +
        AppUrl.userID +
        "&AuthenKey=" +
        AppUrl.AuthenKey);
    final response = await AppApi.apiGetRequest(AppUrl.CustomerList_ReadList +
        "?SaleInfoId=" +
        AppUrl.userID +
        "&AuthenKey=" +
        AppUrl.AuthenKey); // เรียกใช้ api
    CustomerList.dataContact.clear();

    return response;
  }

//  api ดึงรายละเอียดหน้า header
  static getCustomerHead(customerID) async {
    final response = await AppApi.apiGetRequest(AppUrl.Customer_Read +
        "?customerId=" +
        customerID +
        "&authenKey=" +
        AppUrl.AuthenKey); // เรียกใช้ api " + customerID + "
    AppUrl.CustomerID = customerID;
    return response;
  }

  static del(context, index, customerId) {
    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(
                    'ลบข้อมูล',
                    style: TextStyle(
                      fontWeight: FontWeight.bold,
                      fontSize: mediaQuery(context, 'h', 60),
                    ),
                    textAlign: TextAlign.center,
                  ),
                  SizedBox(
                    height: mediaQuery(context, 'h', 10),
                  ),
                  Text(
                    'คุณแน่ใจว่าต้องการลบ?',
                    style: TextStyle(
                      fontSize: mediaQuery(context, 'h', 46),
                    ),
                    textAlign: TextAlign.center,
                  ),
                  SizedBox(
                    height: mediaQuery(context, 'h', 40),
                  ),
                  Row(
                    mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                    children: <Widget>[
                      ButtonTheme(
                        minWidth: mediaQuery(context, 'h', 320),
                        height: mediaQuery(context, 'h', 120),
                        child: RaisedButton(
                          color: Colors.white,
                          shape: RoundedRectangleBorder(
                            borderRadius: BorderRadius.circular(
                              mediaQuery(context, 'h', 50),
                            ),
                            side: BorderSide(
                              color: AppColors.color.withOpacity(0.51),
                            ),
                          ),
                          onPressed: () {
                            print(AppUrl.EmpID);

                            deleteData(context, customerId, index);
//                            dataContact.removeAt(index);
                            //Navigator.pop(context);
                          },
                          splashColor: AppColors.color,
                          child: Text(
                            'ตกลง',
                            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: RoundedRectangleBorder(
                            borderRadius: 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),
                            ),
                          ),
                        ),
                      ),
                    ],
                  ),
                ],
              ),
            ),
          ),
        );
      },
    );
  }
}
