import 'dart:convert' show json;
import 'dart:io';
import 'package:amos_flutter_utils/amos_flutter_utils.dart';
import 'package:amos_flutter_ui/amos_flutter_ui.dart';
import 'package:amos_flutter_api/logutils.dart';

import 'package:base/consts/color.dart';
import 'package:base/services/api_address.dart';
import 'package:base/utils/GetConfig.dart';
import 'package:base/utils/HttpUtil.dart';
import 'package:base/utils/request.dart';
import 'package:base/widgets/JunCommon.dart';
import 'package:base/widgets/completedialog.dart';
import 'package:base/widgets/faildialoge.dart';
import 'package:base/widgets/loadingdialoge.dart';
import 'package:dio/dio.dart';
import 'package:equipment_manage/model/CheckRecord.dart';
import 'package:equipment_manage/model/car_scan_model.dart';
import 'package:equipment_manage/model/equipment_scan_model.dart';
import 'package:flutter/material.dart';
import 'package:flutter_image_compress/flutter_image_compress.dart';
import 'package:http_parser/http_parser.dart';
import 'package:path_provider/path_provider.dart' as path_provider;
import 'package:safe_control/model/CheckRecordDto.dart';
import 'package:safe_control/services/CheckRecordServices.dart';
import 'package:shared_preferences/shared_preferences.dart';

import '../services/dbAccess.dart';
import '../services/offline_plan_inspection_services.dart';

class OfflineRecordPage extends StatefulWidget {
  @override
  _OfflineRecordPageState createState() => _OfflineRecordPageState();
}

class _OfflineRecordPageState extends State<OfflineRecordPage> {
  var issaving = false;
  List<CheckRecord> listData;
  List<Map<String, dynamic>> list;
  List<Map<String, dynamic>> listTask;
  List<CheckRecord> listbaofei;
  List<CheckRecord> carSum = [];
  List<Map<String, dynamic>> equipSum = [];
  bool isOffline = false;
  String theme = "";
  int successCount = 0;
  List<CheckRecord> shibaiList = [];

  @override
  initState() {
    super.initState();

    getData();
  }

  getData() async {
    await SharedPreferences.getInstance().then((sp) {
      if (sp.getBool("offline") != null) {
        setState(() {
          isOffline = sp.getBool("offline");
          this.theme = sp.getString("theme") ?? KColorConstant.DEFAULT_COLOR;
        });
      }
    });

    var sql = new StringBuffer();
    sql.write("select ");
    sql.write("* ");
    sql.write("from CheckReord;");
    var lstRd = await dbAccess().queryData(sql.toString());
    sql = new StringBuffer();
    sql.write(" select * ");
    sql.write(" from FeedbackTask;");
    var lstTask = await dbAccess().queryData(sql.toString());
    sql = new StringBuffer();
    sql.write(" select * ");
    sql.write(" from SunminCar;");
    var carsum = await dbAccess().queryData(sql.toString());
    sql = new StringBuffer();
    sql.write(" select * ");
    sql.write(" from SunminEquipments;");
    var equipsum = await dbAccess().queryData(sql.toString());
    sql = new StringBuffer();
    sql.write("select * from scrapPostBill;");
    var baofei = await dbAccess().queryData(sql.toString());
    listData = new List();
    list = new List();
    listbaofei = new List();
    // setState(() async {
    //--离线巡检---------------------------
    if (null != lstRd) {
      list = lstRd;
      for (var item in list) {
        var jsonRecord = json.decode(item["recordJson"]);
        listData.add(CheckRecord.fromParams(
            planName: jsonRecord["planName"],
            userName: jsonRecord["executor"],
            finishStatus: jsonRecord["finishStatus"],
            checkTime: jsonRecord["checkTime"]));
      }
    }

    //--离线任务---------------------------
    if (lstTask != null) {
      listTask = lstTask;
      for (var map in lstTask) {
        listData.add(CheckRecord.fromParams(
            planName: map["title"],
            userName: map["executor"],
            finishStatus: map["status"],
            checkTime: DateUtils.timestampToDate(
                JunMath.parseInt(map["publishTime"]))));
      }
    }

    if (baofei != null) {
      List baofeilist = baofei;
      for (var map in baofeilist) {
        CarScanModel carmodel = CarScanModel();
        EquipmentScanModel model = EquipmentScanModel();

        var carlists = json.decode(map['jsonString'].toString());
        List<CheckRecord> list = [];
        for (var pon in carlists) {
          if (map['type'] == '26') {
            carmodel = CarScanModel.fromJson(pon);
            list.add(CheckRecord.fromParams(carModel: carmodel));
          } else if (map['type'] == '15') {
            model = EquipmentScanModel.fromJson(pon);
            list.add(CheckRecord.fromParams(equipModel: model));
          } else {
            list.add(CheckRecord.fromParams(agent: pon));
          }
        }
        listbaofei.add(CheckRecord.fromParams(
            scrapId: map['scrapId'],
            createDate: map['createDate'],
            equipList: list,
            imageUrl: map['imageUrl'],
            reason: map['reason'],
            type: map['type'],
            cid: map['cid']));
      }
    }

    if (carsum != null) {
      List carList = carsum;
      for (var map in carList) {
        List list = List();
        list = await getequipList(map["carId"].toString());
        //     .then((value) => {
        //   list=value,
        // });
        CarScanModel model = await getOfflineCarDetalsum(map["carId"]);

        carSum.add(CheckRecord.fromParams(
            carId: map["carId"],
            shelfCellCode: map["shelfCellCode"],
            type: map["type"],
            createDate: map["createDate"].toString(),
            warehouseId: '0',
            carModel: model,
            equipList: list,
            cid: map['cid'],
            area: map['area']));
      }
    }
    if (equipsum != null) {
      equipSum = equipsum;
      for (var map in equipSum) {
        print(map["stockDetailId"].toString());
        print(map["qrCode"].toString());
        EquipmentScanModel model = await getOfflineEquipment(map['type'],
            qrCode: map["qrCode"].toString(),
            equipDetaId: (map["equipmentDetailId"].toString()),
            stockDetailId: map["stockDetailId"].toString());
        CarScanModel carmodel = await getOfflineCarDetalsum(
            map["glcarId"].toString().isEmpty ? map["carId"] : map["glcarId"]);
        listData.add(CheckRecord.fromParams(
          qrCode: map["qrCode"],
          amount: map["amount"],
          carId: map["carId"],
          glcarId: map["glcarId"],
          equipmentDetailId: map["equipmentDetailId"],
          warehouseId: map["warehouseId"],
          reason: map["reason"],
          warehouseStructureId: map["warehouseStructureId"],
          description: map["description"],
          stockDetailId: map["stockDetailId"],
          type: map["type"],
          createDate: map["createDate"],
          total: map["total"],
          equipModel: model,
          carModel: carmodel,
          cid: map['cid'],
          shelfCellCode: map['shelfCellCode'],
          area: map['area'],
        ));
      }
    }
    //});
    setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    if (null == listData || listData.length == 0) {
      return Scaffold(
          backgroundColor: Color.fromRGBO(242, 246, 249, 1),
          appBar: new AppBar(
            backgroundColor: Colors.white,
            elevation: 0.2,
            leading: IconButton(
                icon: Icon(
                  Icons.arrow_back_ios,
                  color: GetConfig.getColor(theme),
                ),
                onPressed: () {
                  Navigator.pop(context);
                }),
            //backgroundColor: KColorConstant.floorTitleColor,

            title: Text(
              '我的信息',
              style: new TextStyle(
                color: Colors.black,
                fontWeight: FontWeight.bold,
              ),
            ),
            centerTitle: true,
            actions: <Widget>[
              IconButton(
                icon: Text(
                  '提交',
                  style: new TextStyle(
                    color: GetConfig.getColor(theme),
                    fontWeight: FontWeight.bold,
                    fontSize: 16.0,
                  ),
                ),
                onPressed: _submit,
              ),
            ],
          ));
    } else {
      return Scaffold(
          backgroundColor: Color.fromRGBO(242, 246, 249, 1),
          appBar: new AppBar(
            backgroundColor: Colors.white,
            elevation: 0.2,
            leading: IconButton(
                icon: Icon(
                  Icons.arrow_back_ios,
                  color: GetConfig.getColor(theme),
                ),
                onPressed: () {
                  Navigator.pop(context);
                }),
            //backgroundColor: KColorConstant.floorTitleColor,
            title: Text(
              '我的信息',
              style: new TextStyle(
                color: Colors.black,
                fontWeight: FontWeight.bold,
              ),
            ),
            centerTitle: true,
            actions: <Widget>[
              IconButton(
                icon: Text(
                  '提交',
                  style: new TextStyle(
                    color: GetConfig.getColor(theme),
                    fontWeight: FontWeight.bold,
                    fontSize: 16.0,
                  ),
                ),
                onPressed: _submit,
              ),
            ],
          ),
          body: new Center(
              child: new ListView.builder(
                  //ListView的Item
                  itemCount: listData.length,
                  itemBuilder: (BuildContext context, int index) {
                    return listData[index].type == null
                        ? getListViewCard(listData[index])
                        : AddDetailCard(listData[index]);
                  }))
          //      body: CustomScrollView(
          //        slivers: <Widget>[
          //      // 如果不是Sliver家族的Widget，需要使用SliverToBoxAdapter做层包裹
          //      SliverToBoxAdapter(
          //      child: Container(
          //        height:40,
          //        color: Colors.green,
          //        child: Text('HeaderView',style: TextStyle(color: Colors.red,fontSize: 20),),
          //      ),
          //    ),
          //  // 当列表项高度固定时，使用 SliverFixedExtendList 比 SliverList 具有更高的性能
          //  SliverFixedExtentList(
          //  delegate: SliverChildBuilderDelegate(_buildListItem, childCount: 18),
          //  itemExtent: 80.0
          //  ),
          // ]),
          );
    }
  }

  _submit() async {
    successCount = 0;
    if (null == listData || listData.length == 0) {
      showDialog<Null>(
          context: context, //BuildContext对象
          barrierDismissible: false,
          builder: (BuildContext context) {
            return new AlertDialog(
              title: new Text("提示"),
              //调用对话框
              content: new Text("暂无数据"),
            );
          });
      //关闭loading
      new Future.delayed(Duration(seconds: 2), () {
        Navigator.pop(context);
      });
      return;
    }
    showDialog<Null>(
        context: context, //BuildContext对象
        barrierDismissible: false,
        builder: (BuildContext context) {
          return new LoadingDialog(
            //调用对话框
            text: '记录上传...',
          );
        });

    var dir = await path_provider.getTemporaryDirectory();

    if (null != list && list.length > 0) {
      for (var map in list) {
        try {
          var cid = map["cid"].toString();
          var jsonRecord = json.decode(map["recordJson"].toString());
          //CheckRecordDto checkRecord=CheckRecordDto.fromJson(jsonRecord);
          // List<dynamic> localFileData = json.decode(
          //     map["filePaths"].toString());
          var pointId = jsonRecord["pointId"];
          List checkRecordImg = jsonRecord["checkRecordImg"];
          List checkItems = jsonRecord["checkItems"];
          List imgurl = [];
          if (checkRecordImg != null) {
            imgurl = await uploadImage(checkRecordImg);
            if (imgurl == null) {
              new Future.delayed(Duration(seconds: 2), () {
                Navigator.pop(context);
              });
              showDialog<Null>(
                  context: context, //BuildContext对象
                  barrierDismissible: false,
                  builder: (BuildContext context) {
                    return new FailDialog(
                      //调用对话框
                      text: '图片上传失败',
                    );
                  });
              new Future.delayed(Duration(seconds: 2), () {
                Navigator.pop(context);
              });
              getData();
              return;
            }
          }
          jsonRecord['checkRecordImg'] = imgurl;
          for (var chechItem in checkItems) {
            List img = chechItem['checkInputImg'];
            List imgurl = [];
            if (img != null) {
              imgurl = await uploadImage(img);
              if (imgurl == null) {
                new Future.delayed(Duration(seconds: 2), () {
                  Navigator.pop(context);
                });
                showDialog<Null>(
                    context: context, //BuildContext对象
                    barrierDismissible: false,
                    builder: (BuildContext context) {
                      return new FailDialog(
                        //调用对话框
                        text: '图片上传失败',
                      );
                    });
                new Future.delayed(Duration(seconds: 2), () {
                  Navigator.pop(context);
                });
                getData();
                return;
              }
            }
            chechItem['checkInputImg'] = imgurl;
          }
          //List<Attachment> fileData = new List();
          // 处理图片信息
//           if (null != localFileData && localFileData.length > 0) {
//             for (var _detail in localFileData) {
//               File f = File.fromUri(Uri.file(_detail["filePath"]));
//               // 压缩图片
//               File result = await FlutterImageCompress.compressAndGetFile(
//                 f.absolute.path,
// //                Directory.systemTemp.absolute.path + "/"+ f.path.substring(f.path.lastIndexOf("/")),
//                 dir.absolute.path + "/" +
//                     f.path.substring(f.path.lastIndexOf("/")),
//                 minWidth: 1024,
//                 minHeight: 768,
//                 quality: 94,
// //                rotate: 180,
//               );
//               if (null != _detail["itemId"]) {
//                 fileData.add(Attachment.fromParams(file: result,
//                     itemId: _detail["itemId"],
//                     name: _detail["name"]));
//               } else {
//                 fileData.add(Attachment.fromParams(file: result));
//               }
//             }
//           }

          // 统计成功数量
          await saveCheckRecordData(cid, pointId, jsonRecord).then((result) {
            if (null != result && result) {
              successCount = successCount + 1;
            }
          });
        } catch (e) {
          print("提交失败：" + e.toString());
        }
      }
    }

    // 提交任务处理记录
    if (listTask != null && listTask.length > 0) {
      for (var task in listTask) {
        try {
          var jsonDto = json.decode(task['jsonData'].toString());
          var jsonPics = json.decode(task['jsonPictures'].toString());
          List imageurl = [];
          if (jsonPics != null) {
            imageurl = await uploadImage(jsonPics);
            if (imageurl == null) {
              new Future.delayed(Duration(seconds: 2), () {
                Navigator.pop(context);
              });
              showDialog<Null>(
                  context: context, //BuildContext对象
                  barrierDismissible: false,
                  builder: (BuildContext context) {
                    return new FailDialog(
                      //调用对话框
                      text: '图片上传失败',
                    );
                  });
              new Future.delayed(Duration(seconds: 2), () {
                Navigator.pop(context);
              });
              getData();
              return;
            }
          }

          jsonDto['imgbase64'] = imageurl;
          await HttpUtil().post(ApiAddress.TASK_FEEDBACKTASK, data: jsonDto);
          await dbAccess().excuteSql(
              "delete from FeedbackTask where cid = ?", [task['cid']]);
          print("提交任务：任务ID---》${task['id']}成功！");
          successCount = successCount + 1;
        } catch (e) {
          print("提交失败：" + e);
        }
      }
    }
    //装备数据分类上传
    if (listData.length > listTask.length + list.length) {
      submitStockIn().then((val) {
        //关闭loading
        new Future.delayed(Duration(seconds: 2), () {
          Navigator.pop(context);
        });

        var total = listData.length;
        // 全部成功
        if (successCount >= total) {
          new Future.delayed(Duration(seconds: 2), () {
            showDialog<Null>(
                context: context, //BuildContext对象
                barrierDismissible: false,
                builder: (BuildContext context) {
                  return new CompleteDialog(
                    //调用对话框
                    text: '上传成功',
                  );
                });
            new Future.delayed(Duration(seconds: 2), () {
              getData();
              Navigator.pop(context); //关闭对话框
            });
          });
        } else {
          new Future.delayed(Duration(seconds: 2), () {
            showDialog<Null>(
                context: context, //BuildContext对象
                barrierDismissible: false,
                builder: (BuildContext context) {
                  return new FailDialog(
                    //调用对话框
                    text: '处理完成，' +
                        (listData.length - successCount).toString() +
                        '条上传失败',
                  );
                });
            new Future.delayed(Duration(seconds: 2), () {
              getData();
              Navigator.pop(context); //关闭对话框
            });
          });
        }

        // 延迟两秒,保证事务提交
        // new Future.delayed(Duration(seconds: 2), () {
        //
        // });
      });
    } else {
      //关闭loading
      new Future.delayed(Duration(seconds: 2), () {
        Navigator.pop(context);
      });

      var total = listData.length;
      // 全部成功
      if (successCount == total) {
        new Future.delayed(Duration(seconds: 2), () {
          showDialog<Null>(
              context: context, //BuildContext对象
              barrierDismissible: false,
              builder: (BuildContext context) {
                return new CompleteDialog(
                  //调用对话框
                  text: '上传成功',
                );
              });
          new Future.delayed(Duration(seconds: 2), () {
            getData();
            Navigator.pop(context); //关闭对话框
          });
        });
      } else {
        new Future.delayed(Duration(seconds: 2), () {
          showDialog<Null>(
              context: context, //BuildContext对象
              barrierDismissible: false,
              builder: (BuildContext context) {
                return new FailDialog(
                  //调用对话框
                  text: '处理完成，' +
                      (listData.length - successCount).toString() +
                      '条上传失败',
                );
              });
          new Future.delayed(Duration(seconds: 2), () {
            getData();
            Navigator.pop(context); //关闭对话框
          });
        });
      }
    }
  }

  Future submitStockIn() async {
    try {
      List<CheckRecord> insko = List();
      List baofeilist = List();
      for (CheckRecord model in listData) {
        if (model.type == '11') {
          insko.add(model);
        }
      }
      for (CheckRecord model in listData) {
        if (model.type == '15') {
          baofeilist.add(model);
        } else if (model.type == '26') {
          baofeilist.add(model);
        } else if (model.type == '34') {
          baofeilist.add(model);
        }
      }
      if (insko.length > 0) {
        await equipStockIn(insko);
      }
      if (listData.length > baofeilist.length + insko.length) {
        await update();
      }
      if (baofeilist.length > 0) {
        await baofei();
      }
      // if(insko.length>0) {
      //   await equipStockIn(insko).then((val) {
      //     if(listData.length>baofeilist.length+insko.length) {
      //       update().then((val) {
      //         if(baofeilist.length>0){
      //           baofei();
      //         }
      //       });
      //     }else if(baofeilist.length>0){
      //       baofei();
      //     }
      //   });
      // }else{
      //   if(listData.length>baofeilist.length+insko.length) {
      //    await update().then((val) {
      //       if(baofeilist.length>0){
      //         baofei();
      //       }
      //     });
      //   }else if(baofeilist.length>0){
      //    await baofei();
      //   }
      // }
      return true;
    } catch (e) {
      print(e);
    }
  }

  Future<bool> update() async {
    //try{
    int i = 0;
    for (CheckRecord model in listData) {
      bool res = false;
      // for(CheckRecord mod in shibaiList){
      //   // if(mod.equipmentDetailId!=null||mod.equipmentDetailId!='null'){
      //   //   if(mod.equipmentDetailId==model.equipmentDetailId){
      //   //     res=true;
      //   //   }
      //   // }
      //   if(mod.stockDetailId!=null||mod.stockDetailId!='null'){
      //     if(mod.stockDetailId==model.stockDetailId){
      //       res=true;
      //     }
      //   }
      //   if(mod.carId!=null||mod.carId!='null'){
      //     if(mod.carId==model.carId){
      //       res=true;
      //     }
      //   }
      // }
      i++;
      if (!res) {
        if (model.type == '12') {
          await equipHandle([model], "maintain");
        } else if (model.type == '13') {
          await equipHandle([model], "repair");
        } else if (model.type == '14') {
          await equipHandle([model], "repaired");
        } else if (model.type == '21') {
          await loadingOrUnloadEquip(model, 'car_load');
        } else if (model.type == '22') {
          await loadingOrUnloadEquip(model, 'car_uninstall');
        } else if (model.type == '23') {
          await carMaintain([model]);
        } else if (model.type == '24') {
          await carRepair([model]);
        } else if (model.type == '25') {
          await carRepairComplete([model]);
        } else if (model.type == '31') {
          await fireAgentInStock([model]);
        } else if (model.type == '32') {
          await loadingExtinguishantSubmit(model);
        } else if (model.type == '33') {
          await lossExtinguishantsSubmit(model);
        }
      }
    }
    if (i == listData.length) {
      return true;
    }
  }

  Future baofei() async {
    int i = 0;
    for (CheckRecord cmodel in listbaofei) {
      bool res = false;
      // for (CheckRecord model in cmodel.equipList) {
      //   for (CheckRecord mod in shibaiList) {
      //     // if (mod.equipmentDetailId != null || mod.equipmentDetailId != 'null') {
      //     //   if (mod.equipmentDetailId == model.equipModel.equipmentDetailId) {
      //     //     res = true;
      //     //   }
      //     // }
      //     if (mod.stockDetailId != null || mod.stockDetailId != 'null') {
      //       if (mod.stockDetailId == model.equipModel.stockDetailId) {
      //         res = true;
      //       }
      //       if (model.agent != null || model.agent != 'null') {
      //         if (model.agent.containsKey('stockDetailId')) {
      //           if (mod.stockDetailId == model.agent['stockDetailId']) {
      //             res = true;
      //           }
      //         }
      //       }
      //     }
      //
      //     if (mod.carId != null || mod.carId != 'null') {
      //       if (mod.carId == model.carModel.carId) {
      //         res = true;
      //       }
      //     }
      //   }
      // }
      i++;
      if (!res) {
        if (cmodel.type == '15') {
          await zhuangbeibaofei(cmodel);
        } else if (cmodel.type == '26') {
          await cheliangbaofei(cmodel);
        } else if (cmodel.type == '34') {
          await mhyjbaofei(cmodel);
        }
      }
      if (i == listData.length) {
        return true;
      }
    }
    // for (CheckRecord model in listData) {
    //   if (model.type == '15') {
    //    await equipHandle([model], "scraped");
    //   } else if (model.type == '26') {
    //    await carCreateScrap([model]);
    //   } else if (model.type == '34') {
    //    await createScrapSubmit([model]);
    //   }
    // }
  }

  Future<bool> zhuangbeibaofei(CheckRecord cmodel) async {
    String id = await baofeiequipHandle(cmodel);
    if (id.length > 16) {
      await baofeisawe(id, cmodel);
      // await baofeiuploadImage(cmodel.imageUrl).then((images){ baofeiScrapPostBill(images, id)} );
      // if(images!=null&&images.length>0) {
      //   await baofeiScrapPostBill(images, id);
      // }
      return true;
    } else {
      return false;
    }
  }

  Future<bool> mhyjbaofei(CheckRecord cmodel) async {
    String id = await createScrapSubmit(cmodel);
    if (id.length > 16) {
      await baofeisawe(id, cmodel);
      // List<String> images = await baofeiuploadImage(cmodel.imageUrl);
      // if(images!=null&&images.length>0) {
      //   await baofeiScrapPostBill(images, id);
      // }
      return true;
    } else {
      return false;
    }
  }

  Future<bool> baofeisawe(String id, CheckRecord model) async {
    if (id.length > 16) {
      List images = await baofeiuploadImage(model.imageUrl);
      dbAccess().excuteSql(
          'update scrapPostBill set scrapId=$id ,imageUrl=${json.encode(images)} where cid = ${model.cid};');
      if (images != null) {
        await baofeiScrapPostBill(images, id, model);
        dbAccess()
            .excuteSql('delete from scrapPostBill where cid = ${model.cid};');
      }

      return true;
    } else {
      return false;
    }
  }

  Future<bool> cheliangbaofei(CheckRecord cmodel) async {
    String id = await carCreateScrap(cmodel);
    if (id.length > 16) {
      await baofeisawe(id, cmodel);
      //await baofeiuploadImage(cmodel.imageUrl).then((images) => baofeiScrapPostBill(images, id));
      // List<String> images = await baofeiuploadImage(cmodel.imageUrl);
      // if(images!=null&&images.length>0) {
      //   await baofeiScrapPostBill(images, id);
      // }
      return true;
    } else {
      return false;
    }
  }

  Future<bool> baofeiScrapPostBill(
      List image, String scrapId, CheckRecord model) async {
    String att = image.join(",");
    // final scrapId = widget.routeModel.extension["id"];
    final params = {"id": scrapId, "attachment": att};
    HttpRequest.scrapExec(params: params).then((res) {
      if (res["status"] == 200) {
        getdelete(model.cid,
            stockDetailId: model.stockDetailId,
            type: model.type,
            carId: model.carId);
        return true;
      } else {
        return false;
      }
    }).catchError((err) {
      return false;
    });
  }

  Future<bool> equipStockIn(List<CheckRecord> list) async {
    List equips = [];
    for (CheckRecord model in list) {
      equips.add({
        "amount": model.amount,
        "equipmentDetailId": model.equipmentDetailId,
        "qrCode": model.qrCode,
        "warehouseId": model.warehouseId,
        "warehouseStructureId": model.warehouseStructureId,
        "description": model.description.isEmpty ? ' ' : model.description,
        "createDate": model.createDate
      });
    }
    LogUtil.d(equips);
    List lista;
    await HttpRequest.equipStockIn(params: equips).then((res) async {
      if (res["status"] == 200) {
        successCount = successCount + equips.length;
        List lists = res['result']['stockData'];
        lista = lists;
        for (var asd in lists) {
          for (CheckRecord care in listData) {
            if (care.equipModel.equipmentDetailId.toString() ==
                asd['equipmentDetailId'].toString()) {
              care.stockDetailId = asd['stockDetailId'].toString();

              care.equipModel.stockDetailId = asd['stockDetailId'].toString();
            }
          }
          for (CheckRecord care in listbaofei) {
            if (care.type == '15') {
              for (CheckRecord assd in care.equipList) {
                if (assd.equipModel.equipmentDetailId.toString() ==
                    asd['equipmentDetailId'].toString()) {
                  care.stockDetailId = asd['stockDetailId'].toString();

                  assd.equipModel.stockDetailId =
                      asd['stockDetailId'].toString();
                }
              }
            }
          }
          //equipmentOnCar

          //   dbAccess().excuteSql(
          //       "update equipmentOnCar set  stockDetailId = ${asd['stockDetailId'].toString()}   where equipmentDetailId = ${asd['equipmentDetailId']}  ");
          // }

          // }
        }
        for (var asd in lista) {
          await dbAccess().excuteSql(
              "update Equipment set  stockDetailId = ${asd['stockDetailId'].toString()}   where equipmentSpecificQrCode = ${asd['qrCode']}  ");
          await dbAccess().excuteSql(
              "delete from SunminEquipments where qrCode = ${asd['qrCode']}");
        }
        return true;
      } else {
        shibaiList.addAll(list);
        return false;
      }
    }).catchError((err) {
      return false;
    });
  }

  Future<bool> equipHandle(List<CheckRecord> list, String item) async {
    List equips = [];
    for (CheckRecord model in list) {
      if (item == 'scraped') {
        equips.add({
          "stockDetailId": model.equipModel.stockDetailId,
          "reason": model.reason,
          "amount": model.amount,
          "createDate": model.createDate
        });
      } else {
        equips.add({
          "stockDetailId": model.equipModel.stockDetailId,
          "amount": model.amount,
          "createDate": model.createDate
        });
      }
    }

    return await HttpRequest.equipHandle(item, params: equips).then((res) {
      if (res["status"] == 200) {
        successCount = successCount + equips.length;
        for (CheckRecord model in list) {
          getdelete(model.cid,
              stockDetailId: model.equipModel.stockDetailId,
              time: model.createDate);
        }
        return true;
      } else {
        shibaiList.addAll(list);
        return false;
      }
    }).catchError((err) {
      return false;
    });
  }

  Future<String> baofeiequipHandle(CheckRecord cmodel) async {
    List equips = [];
    for (CheckRecord model in cmodel.equipList) {
      equips.add({
        "stockDetailId": model.equipModel.stockDetailId,
        "reason": cmodel.reason,
        "amount": model.equipModel.amount,
        "createDate": cmodel.createDate
      });
    }

    return await HttpRequest.equipHandle('scraped', params: equips).then((res) {
      if (res["status"] == 200) {
        successCount = successCount + 1;
        final result = res["result"];
        String spId = result["id"];
        successCount = successCount + equips.length;
        for (CheckRecord model in cmodel.equipList) {
          getdelete(model.cid,
              stockDetailId: model.equipModel.stockDetailId, type: '15');
        }
        return spId;
      } else {
        return res["status"].toString();
      }
    }).catchError((err) {
      return err;
    });
  }

  Future<bool> loadingOrUnloadEquip(CheckRecord model, String car_load) async {
    //List equips = [];
    /// for (CheckRecord model in list) {
    List equiplist = [];
    //model.equipList.forEach((element) {
    equiplist.add({
      "qrCode": model.equipModel.qrCode,
      "amount": model.amount,
      "carId": model.carId,
      "equipmentDetailId": model.equipModel.equipmentDetailId,
      "warehouseId": '0'
    });
    // });
    final params = {
      "warehouseId": model.warehouseId,
      "type": car_load,
      "equipments": equiplist,
      "shelfCellCode": model.shelfCellCode,
      "area": model.area
    };
    return await HttpRequest.loadingOrUnloadEquip(params: params).then((res) {
      if (res["status"] == 200) {
        successCount = successCount + 1;

        getdelete(model.cid,
            equipmentDetailId: model.equipmentDetailId,
            time: model.createDate,
            type: model.type);
        return true;
      } else {
        shibaiList.add(model);
        return false;
      }
    }).catchError((err) {
      return false;
    });
    //equips.add(params);
  }

  Future<bool> carMaintain(List<CheckRecord> list) async {
    List cars = [];
    for (CheckRecord model in list) {
      cars.add({"carId": model.carId});
    }

    return await HttpRequest.carMaintain(params: cars).then((res) {
      if (res["status"] == 200) {
        successCount = successCount + cars.length;
        for (CheckRecord model in list) {
          getdelete(model.cid, carId: model.carId, time: model.createDate);
        }
        return true;
      } else {
        shibaiList.addAll(list);
        return false;
      }
    }).catchError((err) {
      return false;
    });
  }

  Future<bool> carRepair(List<CheckRecord> list) async {
    List cars = [];
    for (CheckRecord model in list) {
      cars.add({"carId": model.carId});
    }

    return await HttpRequest.carRepair(params: cars).then((res) {
      if (res["status"] == 200) {
        successCount = successCount + cars.length;
        for (CheckRecord model in list) {
          getdelete(model.cid, carId: model.carId, time: model.createDate);
        }
        return true;
      } else {
        shibaiList.addAll(list);
        return false;
      }
    }).catchError((err) {
      return false;
    });
  }

  Future<bool> carRepairComplete(List<CheckRecord> list) async {
    List cars = [];
    for (CheckRecord model in list) {
      cars.add({"carId": model.carId});
    }

    return await HttpRequest.carRepairComplete(params: cars).then((res) {
      if (res["status"] == 200) {
        successCount = successCount + cars.length;
        for (CheckRecord model in list) {
          getdelete(model.cid, carId: model.carId, time: model.createDate);
        }
        return true;
      } else {
        shibaiList.addAll(list);
        return false;
      }
    }).catchError((err) {
      return false;
    });
  }

  Future<String> carCreateScrap(CheckRecord cmodel) async {
    List cars = [];
    for (CheckRecord model in cmodel.equipList) {
      cars.add({"carId": model.carModel.carId, "reason": cmodel.reason});
    }

    return await HttpRequest.carCreateScrap(params: cars).then((res) {
      if (res["status"] == 200) {
        final result = res["result"];
        String spId = result["id"];

        successCount = successCount + cars.length;
        for (CheckRecord model in cmodel.equipList) {
          getdelete(model.cid, carId: model.carModel.carId, type: '26');
        }
        return spId;
      } else {
        return res["status"].toString();
      }
    }).catchError((err) {
      return err;
    });
  }

  Future<bool> fireAgentInStock(List<CheckRecord> list) async {
    List params = [];
    for (CheckRecord model in list) {
      params.add({
        "amount": model.amount,
        "equipmentDetailId": model.equipmentDetailId,
        "warehouseId": model.warehouseId,
        "warehouseStructureId": model.warehouseStructureId,
        "description": model.description.isEmpty ? ' ' : model.description,
        "qrCode": model.equipModel.qrCode,
        'createDate': model.createDate
      });
    }

    return await HttpRequest.fireAgentInStock(params: params).then((res) {
      if (res["status"] == 200) {
        successCount = successCount + 1;
        List lists = res['result']['stockData'];
        for (var asd in lists) {
          for (CheckRecord care in listData) {
            if (care.equipModel.equipmentDetailId.toString() ==
                asd['equipmentDetailId'].toString()) {
              care.stockDetailId = asd['stockDetailId'].toString();

              care.equipModel.stockDetailId = asd['stockDetailId'].toString();
            }
          }
          for (CheckRecord care in listbaofei) {
            if (care.type == '15') {
              for (CheckRecord assd in care.equipList) {
                if (assd.equipModel.equipmentDetailId.toString() ==
                    asd['equipmentDetailId'].toString()) {
                  care.stockDetailId = asd['stockDetailId'].toString();

                  assd.equipModel.stockDetailId =
                      asd['stockDetailId'].toString();
                }
              }
            }
          }
          //equipmentOnCar
          dbAccess().excuteSql(
              "update Equipment set  stockDetailId = ${asd['stockDetailId'].toString()}   where equipmentSpecificQrCode = ${asd['qrCode']}  ");
          for (CheckRecord model in list) {
            getdelete(model.cid,
                equipmentDetailId: model.equipmentDetailId,
                time: model.createDate);
          }
        }
        return true;
      } else {
        shibaiList.addAll(list);
        return false;
      }
    }).catchError((err) {
      return false;
    });
  }

  Future<bool> lossExtinguishantsSubmit(CheckRecord model) async {
    // for (CheckRecord model in list) {
    List equiplist = [];
    // model.equipList.forEach((element) {
    equiplist.add({
      "amount": double.parse(model.amount),
      "equipmentDetailId": model.equipmentDetailId,
      "total": model.total,
      'createDate': model.createDate
    });
    // });

    return await HttpRequest.lossExtinguishantsSubmit(model.carId,
            params: equiplist)
        .then((res) {
      if (res["status"] == 200) {
        successCount = successCount + 1;
        getdelete(model.cid,
            equipmentDetailId: model.equipmentDetailId,
            time: model.createDate,
            type: model.type);
        return true;
      } else {
        shibaiList.add(model);
        return false;
      }
    }).catchError((err) {
      return false;
    });
    //equips.add(params);
  }

  Future<bool> loadingExtinguishantSubmit(CheckRecord model) async {
    //for (CheckRecord model in list) {
    List equiplist = [];
    //model.equipList.forEach((element) {
    equiplist.add({
      "amount": double.parse(model.amount),
      "stockDetailId": model.stockDetailId,
      'createDate': model.createDate
    });
    //});

    return await HttpRequest.loadingExtinguishantSubmit(model.carId,
            params: equiplist)
        .then((res) {
      if (res["status"] == 200) {
        successCount = successCount + 1;

        getdelete(model.cid,
            stockDetailId: model.stockDetailId,
            time: model.createDate,
            type: model.type);
        return true;
      } else {
        shibaiList.add(model);
        return false;
      }
    }).catchError((err) {
      return false;
    });
    //equips.add(params);
  }

  Future<String> createScrapSubmit(CheckRecord cmodel) async {
    List params = [];
    for (CheckRecord model in cmodel.equipList) {
      params.add({
        "amount": model.agent['amount'],
        "stockDetailId": model.agent['stockDetailId'],
        "reason": model.agent['reason'],
      });
    }

    return await HttpRequest.createScrapSubmit(params: params).then((res) {
      if (res["status"] == 200) {
        final result = res["result"];
        String spId = result["id"];
        successCount = successCount + params.length;
        for (CheckRecord modela in cmodel.equipList) {
          getdelete(modela.cid,
              stockDetailId: modela.agent['stockDetailId'].toString(),
              type: '34');
        }
        return spId;
      } else {
        return res["status"].toString();
      }
    }).catchError((err) {
      return err;
    });
    //equips.add(params);
  }

  Future<bool> saveCheckRecordData(cid, pointId, recordData) async {
    var checkRecordDto = CheckRecordDto(recordData);
    checkRecordDto.checkItems.forEach((element) {
      if (element.checkInputImg != 'null') {
        String s1 = element.checkInputImg.replaceFirst('[', '');
        String s2 = s1.replaceFirst(']', '');
        element.checkInputImg = "[\"$s2\"]";
      } else {
        element.checkInputImg = '[]';
      }
    });
    String s1 = checkRecordDto.checkRecordImg.replaceFirst('[', '');
    String s2 = s1.replaceFirst(']', '');
    List imhg = s2.split(',');
    checkRecordDto.checkRecordImg = json.encode(imhg);
    LogUtil.d(checkRecordDto);
    return await saveCheckRecord(checkRecordDto).then((result) {
      if (result.isOk() || result.message == "无需重新巡检") {
        if (result.dataList == "无需重新巡检") {
          var param = List();
          param.add(cid);
          dbAccess().excuteSql("delete from CheckReord where cid = ?", param);
        } else {
//          int checkRecordId = result.dataList as int;
          //int checkRecordId = int.tryParse(
          // result.dataList["checkId"].toString());
          // 上传图片

          var param = List();
          param.add(cid);
          dbAccess().excuteSql("delete from CheckReord where cid = ?", param);
        }
        // else{ // TODO:无需重新巡检，后台如果success 返回true，则去掉此逻辑
        //   var param = List();
        //   param.add(cid);
        //   dbAccess().excuteSql("delete from CheckReord where cid = ?",param);
        // }
        return true;
      } else {
        return false;
      }
    });
  }

  Future<List> baofeiuploadImage(imagelist) async {
    // showDialog(
    //     context: context,
    //     builder: (ctx) {
    //       return LoadingDialog(
    //         barrierDismissible: true,
    //       );
    //     });
    var images = json.decode(imagelist);
    bool uoloadSucess = true;
    List imageUrls = [];
    try {
      for (int i = 0; i < images.length; i++) {
        // 获取 ByteData
        // ByteData byteData = await images[i].getByteData(quality: 30);
        List img = images[i];
        List<int> imageData = [];
        for (var e in img) {
          int r = int.parse(e.toString());
          imageData.add(r);
        }
        // List<int> imageData = images[i];

        MultipartFile multipartFile = MultipartFile.fromBytes(
          imageData,
          // 文件名
          filename: DateTime.now().toString() + '.jpg',
          // 文件类型
          contentType: MediaType("image", "jpg"),
        );
        FormData formData = FormData.fromMap({"files": multipartFile});
        // 使用 dio 上传图片
        var response = await HttpRequest.uploadImage(data: formData);

        if (response["status"] == 200) {
          String url = response["result"]["url"];
          //url.replaceAll(',', '');
          imageUrls.add(url);
          // return response["result"]["url"];
        } else {
          // return null;
          uoloadSucess = false;
          break;
        }
      }
    } on DioError catch (err) {
      return null;
    }

    return imageUrls;
  }

  Future<File> imageCompressAndGetFile(File file) async {
    if (file.lengthSync() < 200 * 1024) {
      return file;
    }
    var quality = 100;
    if (file.lengthSync() > 4 * 1024 * 1024) {
      quality = 50;
    } else if (file.lengthSync() > 2 * 1024 * 1024) {
      quality = 60;
    } else if (file.lengthSync() > 1 * 1024 * 1024) {
      quality = 70;
    } else if (file.lengthSync() > 0.5 * 1024 * 1024) {
      quality = 80;
    } else if (file.lengthSync() > 0.25 * 1024 * 1024) {
      quality = 90;
    }
    var dir = await path_provider.getTemporaryDirectory();
    var targetPath = dir.absolute.path +
        "/" +
        DateTime.now().millisecondsSinceEpoch.toString() +
        ".jpg";

    var result = await FlutterImageCompress.compressAndGetFile(
      file.absolute.path,
      targetPath,
      minWidth: 600,
      quality: quality,
      rotate: 0,
    );

    print("压缩后：${file.lengthSync() / 1024}");

    print("压缩后：${result.lengthSync() / 1024}");

    return result;
  }

  Future<List> uploadImage(images) async {
    // showDialog(
    //     context: context,
    //     builder: (ctx) {
    //       return LoadingDialog(
    //         barrierDismissible: true,
    //       );
    //     });

    bool uoloadSucess = true;
    List imageUrls = [];
    try {
      for (int i = 0; i < images.length; i++) {
        String file = images[i];

        File path = await imageCompressAndGetFile(File(file));

        var name = file.substring(file.lastIndexOf("/") + 1, file.length);
        String imageType =
            name.substring(name.lastIndexOf(".") + 1, name.length);
        var image = await MultipartFile.fromFile(
          path.path,
          filename: name,
        );
        FormData formData = FormData.fromMap({"files": image});
        // 使用 dio 上传图片
        var response = await HttpRequest.uploadImage(data: formData);

        if (response["status"] == 200) {
          String url = response["result"]["url"].toString().replaceAll(',', '');
          //url.replaceAll(',', '');
          imageUrls.add(url);
          // return response["result"]["url"];
        } else {
          // return null;
          uoloadSucess = false;
          break;
        }
      }
    } on DioError catch (err) {
      return null;
    }

    return imageUrls;
  }
//保存圖片
//   Future<List> uploadImage(images) async {
//     // showDialog(context: context,builder: (ctx){
//     //   return LoadingDialog(
//     //     barrierDismissible: true,
//     //   );
//     // });
//     bool uoloadSucess = true;
//     List imageUrls = [];
//     for (int i = 0; i < images.length; i++) {
//       File file = images[i];
//       String path = file.path;
//       var name = path.substring(path.lastIndexOf("/") + 1, path.length);
//       String imageType = name.substring(name.lastIndexOf(".") + 1, name.length);
//       var image = await MultipartFile.fromFile(
//         path,
//         filename: name,
//       );
//       FormData formData = FormData.fromMap({
//         "files": image
//       });
//       // 使用 dio 上传图片
//       var response = await HttpRequest.uploadImage(data: formData);
//
//       if (response["status"] == 200) {
//         imageUrls.add(response["result"]["url"].toString());
//         // return response["result"]["url"];
//       } else {
//         // return null;
//         uoloadSucess = false;
//         break;
//       }
//     }
//
//     return imageUrls;
//   }
}

class getListViewCard extends StatelessWidget {
  getListViewCard(this.record, {Key key}) : super(key: key);

  CheckRecord record;

  @override
  Widget build(BuildContext context) {
    return Card(
      elevation: 0.2,
      margin: EdgeInsets.only(top: 5, left: 10, right: 10),
      child: new Container(
          height: 80.0,
//                                          margin: EdgeInsets.only(top: 5,left: 20,right: 20),
          child: Row(
            children: <Widget>[
              Container(
                width: 8.0,
                //height: 80.0,
                padding: EdgeInsets.only(top: 5, bottom: 5),
                color: Colors.green,
              ),
              Container(
                padding:
                    EdgeInsets.only(left: 10, top: 5, bottom: 5, right: 10),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: <Widget>[
                    Container(
                        width: MediaQuery.of(context).size.width - 48,
                        child: new Text(
                          (record.planName ?? "") == ""
                              ? "无计划巡检"
                              : record.planName,
                          style: new TextStyle(
                              fontSize: 16.0, fontWeight: FontWeight.w500),
                          // maxLines: 10,
                          overflow: TextOverflow.ellipsis,
                        )),
                    Padding(
                      padding: EdgeInsets.only(top: 5),
                    ),
                    Row(
                      children: <Widget>[
                        Text(
                          "执行人: ${record.userName}",
                          style: new TextStyle(color: Colors.grey),
                        ),
                        Padding(
                          padding: EdgeInsets.only(left: 36),
                        ),
                        Text(
                          record.finishStatus ?? "",
                          style: TextStyle(color: Colors.green),
                        ),
                      ],
                    ),
                    Row(
                      children: <Widget>[
                        Text(
                          "时间:${record.checkTime}",
                          style: new TextStyle(color: Colors.grey),
                        ),
                      ],
                    ),
                  ],
                ),
              )
            ],
          )),
    );
  }
}

class AddDetailCard extends StatelessWidget {
  CheckRecord model;

  AddDetailCard(this.model, {Key key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    String type = '';
    if (model.type == '11') {
      type = '装备入账';
    } else if (model.type == '12') {
      type = '装备保养';
    } else if (model.type == '13') {
      type = '装备维修';
    } else if (model.type == '14') {
      type = '装备维修完成';
    } else if (model.type == '15') {
      type = '装备报废';
    } else if (model.type == '21') {
      type = '车辆装载';
    } else if (model.type == '22') {
      type = '车辆卸载';
    } else if (model.type == '23') {
      type = '车辆保养';
    } else if (model.type == '24') {
      type = '车辆维修';
    } else if (model.type == '25') {
      type = '车辆维修完成';
    } else if (model.type == '26') {
      type = '车辆报废';
    } else if (model.type == '31') {
      type = '灭火药剂入账';
    } else if (model.type == '32') {
      type = '灭火药剂装载';
    } else if (model.type == '33') {
      type = '灭火药剂损耗';
    } else if (model.type == '34') {
      type = '灭火药剂报废';
    }
    return Card(
      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(5.px)),
      shadowColor: Color(0xFF455b63).withOpacity(0.08),
      child: Column(
        children: <Widget>[
          Row(
            children: [
              model.glcarId.isEmpty
                  ? Container()
                  : Text('车辆：' + model?.carModel?.equipName,
                      style: Theme.of(context)
                          .textTheme
                          .headline4
                          .copyWith(fontSize: 15.px)),
              SizedBox(
                width: 12.px,
              ),
              Text(type,
                  style: Theme.of(context)
                      .textTheme
                      .headline4
                      .copyWith(fontSize: 15.px)),
            ],
          ),
          SizedBox(
            height: 12.px,
          ),
          Row(
            children: <Widget>[
              Padding(
                padding: EdgeInsets.fromLTRB(15.px, 15.px, 10.px, 15.px),
                child: Image.asset(
                  "assets/images/defule.png",
                  width: 70.px,
                ),
              ),
              // Padding(
              //   padding: EdgeInsets.fromLTRB(15.px, 15.px, 10.px, 15.px),
              //   child: Image.asset(
              //     "",
              //     width: 70.px,
              //     height: 80,
              //   ),
              // ),
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: <Widget>[
                    SizedBox(
                      height: 12.px,
                    ),
                    Text(
                        "${model.equipModel?.equipName ?? model.carModel.equipName}",
                        style: Theme.of(context)
                            .textTheme
                            .headline4
                            .copyWith(fontSize: 17.px)),
                    SizedBox(
                      height: 8.px,
                    ),
                    Text(
                        "数量：${model.amount.length > 0 ? model.amount : 1}" +
                            ((model.type == '23' ||
                                    model.type == '24' ||
                                    model.type == '25' ||
                                    model.type == '26')
                                ? (model.carModel.unit)
                                : (model.equipModel.unit)),
                        style: Theme.of(context)
                            .textTheme
                            .subtitle2
                            .copyWith(fontSize: 13.px)),
                    SizedBox(
                      height: 8.px,
                    ),
                    Text(
                        "标识码：${model.equipModel?.qrCode ?? model.carModel.qrCode}",
                        style: Theme.of(context)
                            .textTheme
                            .subtitle2
                            .copyWith(fontSize: 13.px)),
                    SizedBox(
                      height: 8.px,
                    ),
                    Text("时间：${model.createDate}",
                        style: Theme.of(context)
                            .textTheme
                            .subtitle2
                            .copyWith(fontSize: 13.px)),
                    SizedBox(
                      height: 8.px,
                    ),

                    // getShowContent(context)
                  ],
                ),
              ),
            ],
          ),
          // Positioned(
          //   right: 0.px,
          //   child: SvgButton(
          //     size: 40.px,
          //     src: "assets/images/icon_clear.svg",
          //     onTap: (){
          //       //callBack(index);
          //     },
          //   ),
          // )
        ],
      ),
    );
  }

// 获取展示内容
// Widget getShowContent(BuildContext context) {
//
//   if(category==RouteCategoryFrontComponentConst.fireFightingVehicle&&
//       (item == RouteItemFrontComponentConst.scraped||item == RouteItemFrontComponentConst.maintain||item == RouteItemFrontComponentConst.repair||item == RouteItemFrontComponentConst.repaired)) {
//     return Column(
//       children: <Widget>[
//         Wrap(
//           spacing: 2,
//           runSpacing: 2,
//           children: model.equProperties.map((e) {
//             return  e.textLine!=null? QuoteChip(quote: e.textLine,theme: this.theme):Container();
//           }).toList(),
//         ),
//         // Text("库存:   ${model?.amount??equipModel.total}${model?.unit??equipModel.unit}",style: Theme.of(context).textTheme.subtitle2.copyWith(fontSize: 13.px),),
//         model.carNum!=null?
//         Container(
//           alignment: Alignment.centerLeft,
//           padding: EdgeInsets.only(top: 5.rpx),
//           child: Text("车辆编码："+ model.carNum, style: Theme.of(context).textTheme.subtitle2.copyWith(fontSize: 13.px),textAlign: TextAlign.left,),
//         ):Container(),
//
//       ],
//     );
//   }else{
//     return Column(
//       crossAxisAlignment: CrossAxisAlignment.start,
//       children: <Widget>[
//         // RichText(
//         //     text: TextSpan(
//         //         text: "数量",
//         //         style: Theme.of(context).textTheme.subtitle2.copyWith(fontSize: 13.px),
//         //         children: [
//         //           WidgetSpan(child: SizedBox(width: 15.px,)),
//         //           TextSpan(text: "1", style: Theme.of(context).textTheme.headline4.copyWith(fontSize: 13.px)),
//         //           WidgetSpan(child: SizedBox(width: 15.px,)),
//         //           TextSpan(text: "${equipModel.unit}", style: Theme.of(context).textTheme.subtitle2.copyWith(fontSize: 13.px)),
//         //         ]
//         //     ),
//         //   ),
//         //SizedBox(height: 10.px,),
//         equipModel.carNum!=null?
//         Padding(
//           padding: EdgeInsets.only(top: 5.rpx),
//           child: Text("车辆编码："+ equipModel.carNum, style: Theme.of(context).textTheme.subtitle2.copyWith(fontSize: 13.px),),
//         ):Container(),
//         //性能指标查询报错
//         Wrap(
//           spacing: 2,
//           runSpacing: 2,
//           children: equipModel.equProperties.map((e) {
//             return  e.textLine!=null? QuoteChip(quote: e.textLine,theme: this.theme):Container();
//           }).toList(),
//         ),
//         // SizedBox(height: 8.px,),
//
//         Container(
//           alignment: Alignment.centerLeft,
//           padding: EdgeInsets.only(top: 5.rpx,bottom: 24.rpx,right: 10),
//           child: Text(
//               (equipModel.carNum!=null?"原位置：":"位置：")+ (equipModel.description!=null?equipModel.description:position),
//               style: Theme.of(context).textTheme.subtitle2.copyWith(fontSize: 13.px),
//               softWrap:true,
//               overflow:TextOverflow.ellipsis,
//               maxLines:2
//           ),
//         )
//       ],
//     );
//   }
//
// }

}

Future<List<CheckRecord>> getequipList(String glcarId) async {
  List liste = List();
  List<CheckRecord> 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());
  liste = lstRd;
  for (var map in liste) {
    EquipmentScanModel model = await getOfflineEquipment(map['type'],
        qrCode: map["qrCode"].toString());
    equiplist.add(CheckRecord.fromParams(
        qrCode: map["qrCode"],
        amount: map["amount"],
        carId: map["carId"],
        glcarId: map["glcarId"],
        equipmentDetailId: map["equipmentDetailId"],
        warehouseId: map["warehouseId"],
        reason: map["reason"],
        warehouseStructureId: map["warehouseStructureId"],
        description: map["description"],
        stockDetailId: map["stockDetailId"],
        type: map["type"],
        createDate: map["createDate"],
        total: map["total"],
        equipModel: model,
        cid: map['cid']));
  }
  return equiplist;
}

Future<bool> getdelete(
  dynamic cid, {
  String equipmentDetailId,
  String stockDetailId,
  String carId,
  String time,
  String type,
}) async {
  try {
    var sql = new StringBuffer();

    if (type == '21' || type == '22' || type == '32' || type == '33') {
      sql.write(
          "delete from SunminCar where carId =$carId and createDate = '$time'  ; ");
      await dbAccess().excuteSql(sql.toString());
    }

    sql = new StringBuffer();
    sql.write("delete from SunminEquipments where ");

    if (type == '15') {
      sql.write("stockDetailId =$stockDetailId;");
    } else if (type == '26') {
      sql.write("carId =$carId ;");
    } else if (type == '34') {
      sql.write("stockDetailId =$stockDetailId; ");
    } else {
      sql.write("cid=$cid; ");
    }

    return await dbAccess().excuteSql(sql.toString());
  } catch (e) {
    print(e);
    return false;
  }
}
