import 'dart:typed_data';

import 'package:fluttertoast/fluttertoast.dart';
import 'package:test_sa/controllers/api_routes/urls.dart';
import 'package:test_sa/models/device/device.dart';
import 'package:test_sa/models/engineer.dart';
import 'package:test_sa/models/fault_description.dart';
import 'package:test_sa/models/lookup.dart';
import 'package:test_sa/models/part.dart';
import 'package:test_sa/models/service_request/service_request.dart';
import 'package:test_sa/models/timer_model.dart';

class ServiceReport {
  int id;
  double operatingHours;
  DateTime visitDate;
  // DateTime endDate;
  // DateTime startDate;
  Lookup assetType;
  Lookup callLastSituation;
  Lookup currentSituation;
  Lookup repairLocation;
  Engineer engineer;
  Lookup equipmentStatus;
  Lookup type;
  Lookup reason;
  int faultDescriptionId;
  String workPreformed;

  num workingHours;
  double travelingHours;
  String invoiceNumber;
  String invoiceCode;
  List<Part> parts;
  String image;
  Device device;
  String quantity;
  String jobSheetNumber;
  TimerModel timer;
  String signatureNurse;
  String signatureEngineer;
  String comment;
  Uint8List localNurseSignature;
  Uint8List localEngineerSignature;
  num travelingExpense;
  String reviewComment;
  FaultDescription faultDescription;

  ServiceReport({
    this.id,
    this.visitDate,
    // this.endDate,
    this.assetType,
    this.equipmentStatus,
    this.type,
    this.faultDescriptionId,
    this.workingHours,
    this.travelingHours,
    this.parts,
    this.engineer,
    this.workPreformed,
    this.reason,
    this.operatingHours,
    this.callLastSituation,
    this.currentSituation,
    this.jobSheetNumber,
    this.image,
    this.device,
    this.invoiceCode,
    this.invoiceNumber,
    this.quantity = "1",
    this.timer,
    this.signatureNurse,
    this.signatureEngineer,
    this.localNurseSignature,
    this.localEngineerSignature,
    this.comment,
    this.repairLocation,
    this.travelingExpense,
    // this.startDate,
    this.reviewComment,
    this.faultDescription,
  });

  Map<String, dynamic> toMap(ServiceRequest request) {
    Map<String, dynamic> _map = {};
    if (id != null) _map["id"] = id;
    if (visitDate != null) _map["visitDate"] = visitDate.toIso8601String();
    //if(serviceType != null) _map["service_type"] = serviceType.id.toString();
    if (equipmentStatus != null) _map["equipmentStatus"] = equipmentStatus?.toMap();
    if (type != null) _map["typeOfWO"] = type?.toMap();
    if (assetType != null) _map["TypeOfWO"] = assetType?.toMap();
    //if(faultDescriptionId != null && faultDescriptionId.isNotEmpty) _map["fault_description"] = faultDescriptionId;
    //if(workHours != null && workHours.isNotEmpty) _map["working_hours"] = workHours;
    if (timer != null) {
      _map["startofWorkTime"] = timer.startAt.toIso8601String();
      _map["endofWorkTime"] = (timer.endAt ?? DateTime.now()).toIso8601String();
      _map["workingHours"] = (timer.durationInSecond / 60 / 60).toStringAsFixed(5);
    }
    if (travelingHours != null && travelingHours.toString().isNotEmpty) _map["travelingHours"] = travelingHours;
    // if(workPreformed != null && workPreformed.isNotEmpty){
    //   _map["faultDescription"] = {
    //     "id":faultDescriptionId ?? 0,
    //     "workPerformed":workPreformed
    //   };
    // }
    _map["faultDescription"] = {"id": faultDescription?.id ?? 0, "workPerformed": faultDescription?.workPerformed};
    if (travelingHours != null) _map["travelingHours"] = travelingHours;
    // if (workingHours != null) _map["workingHours"] = workingHours;
    // if (workPreformed != null && workPreformed.isNotEmpty) {
    //   _map["faultDescription"] = faultDescription.toJson();
    // }
    if (jobSheetNumber != null && jobSheetNumber.isNotEmpty) _map["job_sheet_no"] = jobSheetNumber;
    if (parts != null && parts.isNotEmpty) {
      _map["sparePartsWorkOrders"] = parts.map((e) => e.toJson()).toList();
    }
    if (device != null && device.id != null) {
      _map["callRequest"] = {
        "id": request.id,
        "asset": device?.toMap(assetType),
      };
      _map["callRequest"]["asset"]["invoiceNumber"] = invoiceNumber;
    }
    _map["AssignedEmployee"] = engineer?.toMap();
    _map["repairLocation"] = repairLocation?.toMap();
    //if(quantity != null && quantity.isNotEmpty) _map["qty"] = quantity;
    //if(endDate != null) _map["end_date"] = (endDate.millisecondsSinceEpoch ~/ 1000).toString();
    if (reason != null) _map["reason"] = reason.toMap();
    //if(operatingHours != null && operatingHours.isNotEmpty) _map["operation_hours"] = operatingHours;
    if (callLastSituation != null) _map["calllastSituation"] = callLastSituation.toMap();
    if (currentSituation != null) _map["currentSituation"] = currentSituation.toMap();
    //if(image != null) _map["image"] = image;
    //if(invoiceCode != null) _map["invoice_no"] = invoiceCode;
    //if(invoiceNumber != null) _map["invoice_code"] = invoiceNumber;
    if (image != null) {
      _map["attachmentsWorkOrder"] = [
        {"name": image}
      ];
    }
    _map["nurseSignature"] = signatureNurse;
    _map["engSignature"] = signatureEngineer;
    _map["comment"] = comment;
    _map["travelingExpenses"] = travelingExpense;
    // _map["startofWorkTime"] = startDate.toIso8601String();
    // _map["endofWorkTime"] = endDate.toIso8601String();
    // _map["workingHours"] = endDate?.difference(startDate)?.inHours ?? 0;
    if (timer?.startAt != null) _map["startofWorkTime"] = timer?.startAt?.toIso8601String();
    if (timer?.endAt != null) _map["endofWorkTime"] = timer?.endAt?.toIso8601String();
    _map["workingHours"] = workingHours;
    _map["reviewComment"] = reviewComment;
    return _map;
  }

  Future<bool> validate() async {
    print("visitDate:$visitDate");
    print("equipmentStatus:${equipmentStatus?.toMap()}");
    print("callLastSituation:${callLastSituation?.toMap()}");
    print("parts:$parts");
    print("reason:${reason?.toMap()}");
    if (visitDate == null) {
      await Fluttertoast.showToast(msg: "Visit Date Required");
      return false;
    }
    //if(serviceType == null) return false;
    if (equipmentStatus == null) return false;
    //if (type == null && assetType == null) return false;
    // if (engineer == null) return false;
    if (callLastSituation == null) return false;
    if (callLastSituation?.value == 12) {
      //  if(invoiceCode != null || invoiceCode?.isEmpty == true) return false;
      if (invoiceNumber != null || invoiceNumber?.isEmpty == true) return false;
    }
    if (parts == null) return false;
    //if(endDate == null) return false;
    if (reason == null) return false;
    //todo uncoment this line
    //if((device?.id == null || device.id.isEmpty) && type?.id != 1) return false;
    //if(quantity == null || quantity.isEmpty) return false;
    //if(image == null) return false;
    return true;
  }

  factory ServiceReport.fromJson(Map<String, dynamic> parsedJson, int id) {
    List<Part> _parts = [];
    if (parsedJson["sparePartsWorkOrders"] != null) {
      if ((parsedJson["sparePartsWorkOrders"] as List).isNotEmpty && parsedJson["sparePartsWorkOrders"][0]["id"] != null) {
        List partsList = parsedJson["sparePartsWorkOrders"];
        _parts = partsList.map((e) => Part.fromJson(e["sparePart"], reportJson: e)).toList();
      }
    }
    return ServiceReport(
      id: id,
      assetType: Lookup.fromJson(parsedJson["assetType"]),
      callLastSituation: Lookup.fromJson(parsedJson["calllastSituation"]),
      currentSituation: Lookup.fromJson(parsedJson["currentSituation"]),
      repairLocation: Lookup.fromJson(parsedJson["repairLocation"]),
      reason: Lookup.fromJson(parsedJson["reason"]),
      equipmentStatus: Lookup.fromJson(parsedJson["equipmentStatus"]),
      type: Lookup.fromJson(parsedJson["typeOfWO"]),
      faultDescription: parsedJson['faultDescription'] != null ? FaultDescription.fromJson(parsedJson['faultDescription']) : null,

      //  faultDescription: parsedJson["faultDescription"],
      // startDate: DateTime.tryParse(parsedJson["startofWorkTime"] ?? ""),
      // endDate: DateTime.tryParse(parsedJson["endofWorkTime"] ?? ""),
      //invoiceCode: parsedJson["invoice_code"],
      //invoiceNumber: parsedJson["invoice_no"],
      //jobSheetNumber: parsedJson["job_sheet_no"],
      // workingHours: parsedJson["workingHours"],
      engineer: Engineer.fromJson(parsedJson["assignedEmployee"]),
      parts: _parts,
      //quantity: parsedJson["nid"],
      travelingHours: parsedJson["travelingHours"],
      travelingExpense: parsedJson["travelingExpenses"],
      visitDate: DateTime.tryParse(parsedJson["visitDate"]),
      workingHours: parsedJson["workingHours"],
      timer: TimerModel(
        startAt: DateTime.tryParse(parsedJson["startofWorkTime"] ?? ""),
        endAt: DateTime.tryParse(parsedJson["endofWorkTime"] ?? ""),
        durationInSecond: ((parsedJson["workingHours"] ?? 0) * 60 * 60).toInt(),
        stopped: parsedJson["workingHours"] == null ? null : true,
      ),
      //workPreformed: parsedJson["work_performed"],
      device: Device.fromJson(parsedJson["callRequest"]["asset"]),
      signatureNurse: URLs.getFileUrl(parsedJson["nurseSignature"]),
      signatureEngineer: URLs.getFileUrl(parsedJson["engSignature"]),
      comment: parsedJson['comment'],
      reviewComment: parsedJson['reviewComment'],
    );
  }

// static getDate(String date){
//   return date == null || date.isEmpty
//       ? null : DateTime.fromMillisecondsSinceEpoch(int.tryParse(date) * 1000);
// }
}
