import 'dart:async';
import 'dart:convert' show json;

import 'package:base/model/PageDto.dart';
import 'package:equipment_manage/model/car_scan_model.dart';
import 'package:equipment_manage/model/equipment_scan_model.dart';
import 'package:equipment_manage/model/extinguish_agent_model.dart';
import 'package:equipment_manage/model/fire_agent_category_model.dart';
import 'package:sqflite/sqflite.dart';

import '../model/offline_plan_list_output.dart';
import 'dbAccess.dart';

Future<PageDto> getOfflinePlanListOutputList() async {
  Database db = await dbAccess().openDb();
  List<Map<String, dynamic>> lst = await dbAccess().getPlanInspections(db);
  try {
    PageDto pageDto;
    OfflinePlanListOutput mdl;
    pageDto = PageDto.offlinefromJson();
    print(lst);
    for (var i = 0; i < lst.length; i++) {
      var plan = lst[i];
      mdl = new OfflinePlanListOutput();
      mdl.taskPlanNum = JunMatha.parseInt(plan["taskPlanNum"].toString());
      mdl.OrgCode = plan["orgCode"].toString();
      mdl.finishStatus = JunMatha.parseInt(
          plan["finishStatus"].toString()); // 0:未开始，1：进行中，2：已结束
      mdl.batchNo = JunMatha.parseInt(plan["batchNo"].toString());
      mdl.finshNum = JunMatha.parseInt(plan["finshNum"].toString());
      mdl.planTaskId = JunMatha.parseInt(plan["planTaskId"].toString());
      mdl.taskName = plan["taskName"].toString();
      mdl.beginTime = plan["beginTime"].toString();
      mdl.endTime = plan["endTime"].toString();
      mdl.checkDate = ""; //item[""];
      mdl.userId = JunMatha.parseInt(plan["userId"].toString());
      mdl.omission = "";
      mdl.unqualified = "";
      mdl.unplan = "";
      mdl.inOrder = plan["inOrder"].toString();
      // 计划相关点信息
      mdl.points = new List();
      List<Map<String, dynamic>> pointlst =
          await dbAccess().getPlanInspectionPoints(db, mdl.planTaskId);
      for (var j = 0; j < pointlst.length; j++) {
        var mdlPoint = new Point();
        var point = pointlst[j];
        mdlPoint.pointId = point["pointId"].toString();
        mdlPoint.name = point["name"].toString();
        mdlPoint.pointNO = point["pointNO"].toString();
        mdlPoint.offline = point["offline"].toString();
        mdlPoint.status = point["status"].toString(); // 0：未开始，
        mdlPoint.isFixed = point["isFixed"].toString();
        mdlPoint.planTaskId = point["planTaskId"].toString();
        mdlPoint.orderNo = JunMatha.parseInt(point["orderNo"].toString());
        // 冗余计划相关字段
        var planTask = new OfflinePlanTask();
        planTask.beginTime = JunMatha.parseInt(mdl.beginTime);
        planTask.endTime = JunMatha.parseInt(mdl.endTime);
        planTask.planName = mdl.taskName;
        planTask.pointName = mdlPoint.name;
        planTask.pointNo = mdlPoint.pointNO;
        mdlPoint.planTask = planTask;

        // 处理检查项
        mdlPoint.inputItems = new List();
        var jsonItems = json.decode(point["inputItems"]);
        for (var item in jsonItems) {
          var mdlItem = new InputItem();
          mdlItem.id = item["id"].toString();
          mdlItem.createDate = item["createDate"].toString();
          mdlItem.catalogId = item["catalogId"].toString();
          mdlItem.createBy = item["createBy"].toString();
          mdlItem.dataJson = item["dataJson"].toString();
          mdlItem.defaultValue = item["defaultValue"].toString();
          mdlItem.inputJson = item["inputJson"].toString();
          mdlItem.isMultiline = item["isMultiline"].toString();
          mdlItem.isMust = item["isMust"].toString();
          mdlItem.isScore = item["isScore"].toString();
          mdlItem.itemType = item["itemType"].toString();
          mdlItem.name = item["name"].toString();
          mdlItem.orderNo = item["orderNo"].toString();
          mdlItem.orgCode = item["orgCode"].toString();
          mdlItem.pictureJson = item["pictureJson"].toString();
          mdlItem.remark = item["remark"].toString();
          mdlItem.isDelete = item["isDelete"].toString();
          mdlItem.pOrderNo = item["pOrderNo"].toString();
          mdlItem.pointItemId = item["pointItemId"].toString();
          mdlItem.classifyNames = item["classifyNames"].toString();
          mdlItem.classifyIds = item["classifyIds"].toString();
          mdlItem.riskDesc = item["riskDesc"].toString();
          // 放到point
          mdlPoint.inputItems.add(mdlItem);
        }

        // 处理检查项分类
        mdlPoint.classifis = new List();
        var jsonClassify = json.decode(point["classify"]);
        for (var cls in jsonClassify) {
          if (cls != null) {
            var mdlCls = new Classify();
            mdlCls.id = cls["id"].toString();
            mdlCls.name = cls["name"].toString();
            mdlCls.pointId = cls["pointId"].toString();
            mdlCls.orderNo = cls["orderNo"].toString();
            // 放到point
            mdlPoint.classifis.add(mdlCls);
          }
        }
        // 放到计划中
        mdl.points.add(mdlPoint);
      }
      pageDto.content.add(mdl);
    }
    print(pageDto);
    return pageDto;
  } catch (e) {
    throw e;
  }
}

Future<OfflinePlanListOutput> getOfflinePlanListOutputById(int planId) async {
  Database db = await dbAccess().openDb();
  Map<String, dynamic> plan =
      await dbAccess().getPlanInspectionById(db, planId);
  if (null == plan) {
    return null;
  }
  try {
    OfflinePlanListOutput mdl;
    mdl = new OfflinePlanListOutput();
    mdl.taskPlanNum = JunMatha.parseInt(plan["taskPlanNum"].toString());
    mdl.OrgCode = plan["orgCode"].toString();
    mdl.finishStatus =
        JunMatha.parseInt(plan["finishStatus"].toString()); // 0:未开始，1：进行中，2：已结束
    mdl.batchNo = JunMatha.parseInt(plan["batchNo"].toString());
    mdl.finshNum = JunMatha.parseInt(plan["finshNum"].toString());
    mdl.planTaskId = JunMatha.parseInt(plan["planTaskId"].toString());
    mdl.taskName = plan["taskName"].toString();
    mdl.beginTime = plan["beginTime"].toString();
    mdl.endTime = plan["endTime"].toString();
    mdl.checkDate = ""; //item[""];
    mdl.userId = JunMatha.parseInt(plan["userId"].toString());
    mdl.omission = "";
    mdl.unqualified = "";
    mdl.unplan = "";
    mdl.inOrder = plan["inOrder"].toString();
    // 计划相关点信息
    mdl.points = new List();
    List<Map<String, dynamic>> pointlst =
        await dbAccess().getPlanInspectionPoints(db, mdl.planTaskId);
    for (var j = 0; j < pointlst.length; j++) {
      var mdlPoint = new Point();
      var point = pointlst[j];
      mdlPoint.pointId = point["pointId"].toString();
      mdlPoint.name = point["name"].toString();
      mdlPoint.pointNO = point["pointNO"].toString();
      mdlPoint.offline = point["offline"].toString();
      mdlPoint.status = point["status"].toString(); // 0：未开始，
      mdlPoint.isFixed = point["isFixed"].toString();
      mdlPoint.orderNo = JunMatha.parseInt(point["orderNo"].toString());
      mdlPoint.planTaskId = point["planTaskId"].toString();

      List<dynamic> params = new List<dynamic>();
      params.add(mdlPoint.pointNO);
      // 根据点编号查询点信息
      List<Map<String,dynamic>> points = await dbAccess().queryData("select * from Point where pointNo = ?;", params);
      if(points.length != 0) {
        for (var point in points) {
          mdlPoint.shotMinNumber = point["shotMinNumber"].toString();
          mdlPoint.shotMaxNumber = point["shotMaxNumber"].toString();
        }
      }

      // 冗余计划相关字段
      var planTask = new OfflinePlanTask();
      planTask.beginTime = JunMatha.parseInt(mdl.beginTime);
      planTask.endTime = JunMatha.parseInt(mdl.endTime);
      planTask.planName = mdl.taskName;
      planTask.pointName = mdlPoint.name;
      planTask.pointNo = mdlPoint.pointNO;
      mdlPoint.planTask = planTask;

      // 处理检查项
      mdlPoint.inputItems = new List();
      var jsonItems = json.decode(point["inputItems"]);
      for (var item in jsonItems) {
        var mdlItem = new InputItem();
        mdlItem.id = item["id"].toString();
        mdlItem.createDate = item["createDate"].toString();
        mdlItem.catalogId = item["catalogId"].toString();
        mdlItem.createBy = item["createBy"].toString();
        mdlItem.dataJson = item["dataJson"].toString();
        mdlItem.defaultValue = item["defaultValue"].toString();
        mdlItem.inputJson = item["inputJson"].toString();
        mdlItem.isMultiline = item["isMultiline"].toString();
        mdlItem.isMust = item["isMust"].toString();
        mdlItem.isScore = item["isScore"].toString();
        mdlItem.itemType = item["itemType"].toString();
        mdlItem.name = item["name"].toString();
        mdlItem.orderNo = item["orderNo"].toString();
        mdlItem.orgCode = item["orgCode"].toString();
        mdlItem.pictureJson = item["pictureJson"].toString();
        mdlItem.remark = item["remark"].toString();
        mdlItem.isDelete = item["isDelete"].toString();
        mdlItem.pOrderNo = item["pOrderNo"].toString();
        mdlItem.pointItemId = item["pointItemId"].toString();
        mdlItem.classifyNames = item["classifyNames"].toString();
        mdlItem.classifyIds = item["classifyIds"].toString();
        mdlItem.riskDesc = item["riskDesc"].toString();
        // 放到point
        mdlPoint.inputItems.add(mdlItem);
      }

      // 处理检查项分类
      mdlPoint.classifis = new List();
      var jsonClassify = json.decode(point["classify"]);
      for (var cls in jsonClassify) {
        if (cls != null) {
          var mdlCls = new Classify();
          mdlCls.id = cls["id"].toString();
          mdlCls.name = cls["name"].toString();
          mdlCls.pointId = cls["pointId"].toString();
          mdlCls.orderNo = cls["orderNo"].toString();
          // 放到point
          mdlPoint.classifis.add(mdlCls);
        }
      }
      // 放到计划中
      mdl.points.add(mdlPoint);
    }
    return mdl;
  } catch (e) {
    throw e;
  }
}

Future<List> getOfflinePointList(List<Map<String, dynamic>> lst) async {
  try {
    List<Point> plist = new List();
    for (var point in lst) {
      var mdlPoint = new Point();
      mdlPoint.pointId = point["pointId"].toString();
      mdlPoint.name = point["pointName"].toString();
      mdlPoint.pointNO = point["pointNo"].toString();
      mdlPoint.shotMinNumber = point["shotMinNumber"].toString();
      mdlPoint.shotMaxNumber = point["shotMaxNumber"].toString();
      mdlPoint.offline = point["offline"].toString();
      mdlPoint.status = point["status"].toString();
      mdlPoint.isFixed = point["isFiexed"].toString();
      mdlPoint.level = point["level"].toString();
      mdlPoint.remark = point['remark'].toString();
      if (null != point["routeName"] && point["routeName"] != "null") {
        mdlPoint.routeName = point["routeName"].toString();
      } else {
        mdlPoint.routeName = "";
      }

      if (null != point["classifyNames"] && point["classifyNames"] != "null") {
        mdlPoint.classifyNames = point["classifyNames"].toString();
      } else {
        mdlPoint.classifyNames = "";
      }

      if (null != point["departmentName"] &&
          point["departmentName"] != "null") {
        mdlPoint.departmentName = point["departmentName"].toString();
      } else {
        mdlPoint.departmentName = "";
      }

      if (null != point["chargePerson"] && point["chargePerson"] != "null") {
        mdlPoint.chargePerson = point["chargePerson"].toString();
      } else {
        mdlPoint.chargePerson = "";
      }
      mdlPoint.inputItems = new List();
      var jsonItems = json.decode(point["inputItems"]);
      for (var item in jsonItems) {
        var mdlItem = new InputItem();
        mdlItem.id = item["id"].toString();
        mdlItem.createDate = item["createDate"].toString();
        mdlItem.catalogId = item["catalogId"].toString();
        mdlItem.createBy = item["createBy"].toString();
        mdlItem.dataJson = item["dataJson"].toString();
        mdlItem.defaultValue = item["defaultValue"].toString();
        mdlItem.inputJson = item["inputJson"].toString();
        mdlItem.isMultiline = item["isMultiline"].toString();
        mdlItem.isMust = item["isMust"].toString();
        mdlItem.isScore = item["isScore"].toString();
        mdlItem.itemType = item["itemType"].toString();
        mdlItem.name = item["name"].toString();
        mdlItem.orderNo = item["orderNo"].toString();
        mdlItem.orgCode = item["orgCode"].toString();
        mdlItem.pictureJson = item["pictureJson"].toString();
        mdlItem.remark = item["remark"].toString();
        mdlItem.isDelete = item["isDelete"].toString();
        mdlItem.pOrderNo = item["pOrderNo"].toString();
        mdlItem.pointItemId = item["pointItemId"].toString();
        mdlItem.classifyNames = item["classifyNames"].toString();
        mdlItem.classifyIds = item["classifyIds"].toString();
        mdlItem.riskDesc = item["riskDesc"].toString();
        mdlPoint.inputItems.add(mdlItem);
      }
      mdlPoint.classifis = new List();
      var jsonClassify = json.decode(point["classify"]);
      for (var cls in jsonClassify) {
        var mdlCls = new Classify();
        mdlCls.id = cls["classifyId"].toString();
        mdlCls.name = cls["classifyName"].toString();
        mdlCls.pointId = cls["pointId"].toString();
        mdlPoint.classifis.add(mdlCls);
      }
      plist.add(mdlPoint);
    }
    return plist;
  } catch (e) {
    throw e;
  }
}

//// 巡检点检查详情
//Future<CheckPointDetail> queryCheckPointDetail(num id) async{
//  CheckPointDetail resultData;
//  List<CheckInput> checkInputs = List();
//  List<String> pointImgUrls = List();
//  var data = await HttpUtil().get(ApiAddress.GET_QUERY_CHECK_POINT_DETAIL,data:{"checkId":id});
//  if(data["result"] == "SUCCESS"){
//    var dataList = data["dataList"];
//    var _checkInputs = dataList["checkInput"];
//    if(_checkInputs != null){
//      for(var d in _checkInputs){
//        checkInputs.add(CheckInput.fromJson(d));
//      }
//    }
//
//    var _pointImgUrls = dataList["pointImgUrls"];
//    if(_pointImgUrls != null){
//      for(var d in _pointImgUrls){
//        pointImgUrls.add(d.toString());
//      }
//    }
//
//    resultData = CheckPointDetail.fromJson(dataList);
//    resultData.checkInputs = checkInputs;
//    resultData.pointImgUrls = pointImgUrls;
//    return resultData;
//  }else{
//    return resultData;
//  }
//}
//

//Future<PlanTaskDetail> ById(num id) async{
//  PlanTaskDetail resultData;
//  List<Point> points = List();
//  var data = await HttpUtil().get(ApiAddress.QUERYPLANTASKBYID,data:{"planTaskId":id});
//  if(data["result"] == "SUCCESS"){
//    var dataList = data["dataList"];
//    var _points = dataList["points"];
//    for(var d in _points){
//      points.add(Point.fromJson(d));
//    }
//    resultData = PlanTaskDetail.fromJson(dataList["planTask"]);
//    resultData.points = points;
//    return resultData;
//  }else{
//    return resultData;
//  }
//}

//
//// 未开始巡检点，点击获取巡检点详情
//Future<CheckPointDetail> queryPointPlanTaskDetail(num planTaskId,num pointId) async{
//  var data = await HttpUtil().get(ApiAddress.QUERY_POINT_PLANTASK_DETAIL,
//      data:{"planTaskId":planTaskId,"pointId":pointId});
//  print(data);
//  if (data["result"] == "SUCCESS" ) {
//    CheckPointDetail rst = CheckPointDetail.fromJson(data["dataList"]);
//    List<CheckInput> checkInputs = List();
//    for(var c in data["dataList"]["checkInput"]){
//      checkInputs.add(CheckInput.fromJson(c));
//    }
//    rst.checkInputs = checkInputs;
//    return rst;
//  }
//  return null;
//}

class JunMatha {
  static int parseInt(String str) {
    try {
      if (str == null) return 0;
      if (str == "null") return 0;
      return int.parse(str);
    } catch (e) {
      return 0;
    }
  }
}

/**
 * 装备离线
 */
//获取建筑树
Future<List> getOfflineWarehouse() async {
  Database db = await dbAccess().openDb();
  List plan = await dbAccess().getWarehouse(db);
  if (null == plan) {
    return null;
  }
  List list = [];
  List lista = [];
  for (var map in plan) {
    if (map['parentId'] == '0') {
      list.add(map);
    } else {
      lista.add(map);
    }
  }

  if (lista.length > 0) {
    return childrenList(list, lista);
  } else {
    return list;
  }
}

Future<List> childrenList(List list, List plan) async {
  for (var item in list) {
    List iuyt = [];
    plan.forEach((element) {
      if (item["id"].toString() == element['parentId']) {
        iuyt.add(element);
      }
    });
    item['children'] = iuyt;
  }
  for (var itema in list) {
    List ser = itema['children'];
    for (var sdf in ser) {
      List iuyt = [];
      plan.forEach((element) {
        if (sdf["id"].toString() == element['parentId']) {
          iuyt.add(element);
        }
      });
      sdf['children'] = iuyt;
    }
  }
  for (var itema in list) {
    List ser = itema['children'];
    for (var sdfa in ser) {
      List safas = sdfa['children'];
      for (var sdf in safas) {
        List iuyt = [];
        plan.forEach((element) {
          if (sdf["id"].toString() == element['parentId']) {
            iuyt.add(element);
          }
        });
        sdf['children'] = iuyt;
      }
    }
  }
  return list;
}

Future<Map> childrenParentList(List plan, Map elem) async {
  plan.forEach((element) {
    List list = List();
    if (elem["id"].toString() == element['parentId']) {
      bool fac = true;
      plan.forEach((elem) {
        if (element["id"].toString() == elem['parentId']) {
          fac = false;
        }
      });
      if (fac) {
        list.add(childrenParentList(plan, element));
      }
      elem['children'] = list;
      //list.add(element);
    }
  });
  return elem;
}

//装备、灭火药剂扫码
Future<EquipmentScanModel> getOfflineEquipment(String type,
    {String qrCode, String equipDetaId, String stockDetailId}) async {
  Database db = await dbAccess().openDb();
  Map<String, dynamic> plan;

  if (qrCode != null && qrCode.isNotEmpty && qrCode != 'null') {
    plan = await dbAccess().getEquipment(db, qrCode);
  } else if (equipDetaId != 'null' &&
      equipDetaId != null &&
      equipDetaId.isNotEmpty) {
    plan = await dbAccess().getEquipmentIDsum(db, equipDetaId);
  } else if (stockDetailId != null &&
      stockDetailId.isNotEmpty &&
      stockDetailId != 'null') {
    plan = await dbAccess().getEquipmentsum(db, stockDetailId);
  }

  if (null == plan) {
    return null;
  }
  try {
    EquipmentScanModel model = new EquipmentScanModel();
    model.equipmentDetailId =
        plan["equipmentSpecificEquipmentDetailId"].toString();
    model.qrCode = plan["equipmentSpecificQrCode"].toString();
    model.singleOrDouble =
        plan["equipmentSpecificSingle"].toString() == 'false' ? false : true;
    model.equipName = plan["equipmentDetailName"].toString();
    model.equipmentId = plan["equipmentId"].toString();
    model.equipmentCode = plan["equipmentCode"].toString();
    model.equipCategoryCode = plan['categoryCode'].toString();
    model.equipmentId = plan['equipmentId'].toString();
    if (plan["stockDetailAmount"] == 'null') {
      model.amount = 0;
    } else {
      if (int.parse(type) > 30) {
        model.amount = double.parse(plan["stockDetailAmount"]);
      } else {
        model.amount = double.parse(plan["stockDetailAmount"]).round();
      }
    }
    model.stockDetailId = plan["stockDetailId"].toString();
    //plan["stockDetailAmount"].toDouble();
    model.description = plan["warehouseStructureName"].toString() +
        (plan["description"] == 'null' ? '' : plan["description"].toString());
    model.unit = plan["unitName"].toString();
    String status = '';
    if (plan["stockDetailStatus"].toString() == 'null') {
      status = '未入库';
    } else if (plan["stockDetailStatus"].toString() == '1') {
      status = '在位';
    } else if (plan["stockDetailStatus"].toString() == '3') {
      status = '维修';
    } else if (plan["stockDetailStatus"].toString() == '6') {
      status = '退役';
    } else if (plan["stockDetailStatus"].toString() == '7') {
      status = '报废';
    } else if (plan["stockDetailStatus"].toString() == '10') {
      status = '车载';
    }
    model.status = status;
    //List spefic= await dbAccess().getSpecific(db, plan["equipmentSpecificId"].toString());
    model.equProperties = new List();
    //var jsonItems = json.decode(point["inputItems"]);
    // for (var item in spefic) {
    //   var equmodel = new EquProperty();
    //   equmodel.textLine=item["perfQuotaName"].toString()+item["value"].toString()+item["unitName"].toString();
    //   model.equProperties.add(equmodel);
    // }
    return model;
  } catch (e) {
    throw e;
  }
}

//车辆列表
Future<List> getOfflineCarList() async {
  Database db = await dbAccess().openDb();
  List plan = await dbAccess().getCar(db, '');
  List list = List();
  for (var parame in plan) {
    if (parame["carState"] == '1') {
      list.add({
        "cid": parame["cid"],
        "carId": parame["id"],
        "name": parame["name"],
        "carNum": parame["carNum"],
        "carState": parame["carState"],
        "qrCode": parame["qrCode"]
      });
    }
  }
  if (null == list) {
    return null;
  }
  return list;
}

//获取报废原因
Future<List> getReason() async {
  Database db = await dbAccess().openDb();
  List plan = await dbAccess().getReason(db);
  List list = List();
  for (var parame in plan) {
    list.add({
      "cid": parame["cid"],
      "id": parame["id"],
      "createDate": parame["createDate"],
      "code": parame["code"],
      "name": parame["name"],
      "type": parame["type"],
      "remark": parame["remark"]
    });
  }
  if (null == list) {
    return null;
  }
  return list;
}

//车辆扫码
Future<CarScanModel> getOfflineCarDetal(String qrCode) async {
  Database db = await dbAccess().openDb();
  List plan = await dbAccess().getCar(db, qrCode);
  if (null == plan) {
    return null;
  }
  try {
    CarScanModel model = CarScanModel();
    dynamic carplan = plan[0];
    model.qrCode = carplan["qrCode"].toString();
    model.carNum = carplan["carNum"].toString();
    model.carId = carplan["id"].toString();
    model.equipName = carplan["name"].toString();
    model.unit = '辆';
    model.amount = 1;
    model.equProperties = [];
    model.Status = carplan["carState"].toString();
    return model;
  } catch (e) {
    throw e;
  }
  //return plan;
}

//车辆Id查数据
Future<CarScanModel> getOfflineCarDetalsum(String carId) async {
  if (carId.isEmpty) {
    return null;
  }
  Database db = await dbAccess().openDb();
  List plan = await dbAccess().getCarsum(db, carId);
  if (null == plan || plan.length == 0) {
    return CarScanModel();
  }
  try {
    CarScanModel model = CarScanModel();
    dynamic carplan = plan[0];
    model.qrCode = carplan["qrCode"].toString();
    model.carNum = carplan["carNum"].toString();
    model.carId = carplan["id"].toString();
    model.equipName = carplan["name"].toString();
    model.amount = 1;
    model.unit = '辆';
    model.equProperties = [];
    model.Status = carplan["carState"].toString();
    return model;
  } catch (e) {
    throw e;
  }
  //return plan;
}
//灭火药剂

Future<List<ExtinguishAgentModel>> getOfflineAgentshList(String carId,
    {String type}) async {
  Database db = await dbAccess().openDb();
  List carList = await dbAccess().getsunhaoequipidList(db, carId);
  List<ExtinguishAgentModel> plan = [];
  for (var map in carList) {
    List list = await dbAccess().getAgentsh(db,
        Id: map["equipmentDetailId"], stId: map["stockDetailId"]);

    // pamer['amount']=map['amount'];
    if (list.length > 0) {
      dynamic pamer = list[0];
      String str = pamer['categoryCode'];
      if (str[0] == '4') {
        ExtinguishAgentModel model = ExtinguishAgentModel();

        model.amount = double.parse(map['amount'].toString());
        model.unitName = pamer["unitName"].toString();
        model.carId = carId;
        model.equipmentDetailId =
            pamer["equipmentSpecificEquipmentDetailId"].toString();
        model.equipmentName = pamer["equipmentDetailName"].toString();

        if (model.amount > 0) {
          plan.add(model);
        }
      }
    }
  }
  if (null == plan || plan.length == 0) {
    return List();
  }

  return plan;
}

Future<List<FireAgentCategoryModel>> getOfflineAgentList(String warId,
    {String type}) async {
  Database db = await dbAccess().openDb();
  List plan = await dbAccess().getAgent(db, warId);
  // var sql = new StringBuffer();
  //  sql.write("select ");
  //  sql.write("* ");
  //  sql.write("from EquipmentOnCar  ");
  //  print(sql.toString());
  //  List<Map<String, dynamic>> lste = await db.rawQuery(sql.toString());
  //List plan =[];
  //if(type=='34'){
  List lists = [];
  for (var mod in plan) {
    // plan.removeWhere((mod) {
    if (mod['stockDetailStatus'] == '1') {
      lists.add(mod);
      //return true;
    }
    // });
  }
  // }//else{plan==plans;}
  if (null == lists || lists.length == 0) {
    return List();
  }
  List<FireAgentCategoryModel> list = List();
  for (var element in lists) {
    EquipmentDetail eqmodel = EquipmentDetail();
    eqmodel.id = element["equipmentSpecificId"].toString();
    eqmodel.name = element["equipmentDetailName"].toString();
    eqmodel.code = element["equipmentSpecificCode"].toString();
    eqmodel.equipmentId =
        element["equipmentSpecificEquipmentDetailId"].toString();
    eqmodel.categoryName = element["categoryCode"].toString();
    eqmodel.unitId = element["unitId"].toString();
    eqmodel.unitName = element["unitName"].toString();
    FireAgentCategoryModel model = FireAgentCategoryModel();
    model.id = element["equipmentSpecificId"].toString();
    //model.createDate=element["createDate"].toString();
    model.amount = element["stockDetailAmount"];
    model.id = element["stockDetailId"].toString();
    model.warehouseStructureId =
        element["stockDetailWarehouseStructureId"].toString();
    // model.rfid=element["equipmentDetailName"].toString();
    model.equipmentDetailId =
        element["equipmentSpecificEquipmentDetailId"].toString();
    model.warehouseId = element["stockDetailWarehouseId"].toString();
    model.qrCode = element["equipmentSpecificQrCode"].toString();
    model.status = element["stockDetailStatus"].toString();
    // model.companyName=element[""].toString();
    //model.orgCode=element[""].toString();
    model.departmentName = element["equipmentDetailName"].toString();
    //model.departmentOrgcode=element["equipmentDetailName"].toString();
    model.equipmentDetail = eqmodel;
    if (type == '33') {
      if (double.parse(model.amount) > 0) {
        list.add(model);
      }
    } else {
      list.add(model);
    }
  }

  return list;
}

//入账
Future<bool> getInStockCar(dynamic pamare, String type) async {
  Database db = await dbAccess().openDb();
  bool plan = await dbAccess().getInStockCar(db, pamare, type);
  if (!plan) {
    return plan;
  }
  try {
    bool pla = await getInStockEquipment(pamare["equipments"], type,
        shelfCellCode: pamare['shelfCellCode']);
    return pla;
  } catch (e) {
    throw e;
    return false;
  }
}

//入账
Future<bool> getInStockEquipment(List pamare, String type,
    {String shelfCellCode}) async {
  Database db = await dbAccess().openDb();
  bool plan = await dbAccess()
      .getInStockEquipments(db, pamare, type, shelfCellCode: shelfCellCode);
  return plan;
}

//报废入账
Future<bool> getScrapPostBill(dynamic pamare, String type) async {
  Database db = await dbAccess().openDb();
  bool plan = await dbAccess().getScrapPostBill(db, pamare, type);
  return plan;
}
// Future<List<CheckRecord>> getoffequipList(String glcarId) async{
//   List list=List();
//   List equiplist=List();
//   var sql = new StringBuffer();
//   sql.write("select ");
//   sql.write("* ");
//   sql.write("from SunminEquipments where glcarId=$glcarId;");
//   var lstRd = await dbAccess().queryData(sql.toString());
//   list=lstRd;
//
//   return equiplist;
// }
//
// Future<bool> getupdateEquipments(List pamare, String type) async {
//   Database db = await dbAccess().openDb();
//   bool plan = await dbAccess().updateEquipments(db,pamare,type);;
//   return plan;
//
// }
