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

import 'package:equipment_manage/model/equipment_scan_model.dart';
import 'package:base/widgets/JunCommon.dart';
import 'package:base/services/api_address.dart';
import 'package:base/utils/HttpUtil.dart';
import 'package:path/path.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:sqflite/sqflite.dart';

class dbAccess {
  String dbPath;

  Future<Database> createNewDb() async {
    int userid = await SharedPreferences.getInstance().then((sp) {
      String userId = sp.get("user_id");
      return int.tryParse(userId);
    });
    var databasesPath = await getDatabasesPath();
    String path = join(databasesPath, '$userid', 'my.db');
    SharedPreferences.getInstance().then((sp) {
      sp.setString("DBPath", path);
    });
    print("db path:$path");
    Database db = await openDatabase(path);

    return db;
  }

  Future<Database> openDb() async {
    int userid = await SharedPreferences.getInstance().then((sp) {
      String str = sp.get('user_id');
      return int.parse(str);
    });
    var databasesPath = await getDatabasesPath();
    String path = join(databasesPath, '$userid', 'my.db');
    SharedPreferences.getInstance().then((sp) {
      sp.setString("DBPath", path);
    });
    print("open db path:$path");
    Database db = await openDatabase(path);
    return db;
  }

  Future<bool> scrapPostBillTable(Database db) async {
    bool exists = await checkTableExists(db, "scrapPostBill");
    if (exists) {
      await db.execute("DROP TABLE scrapPostBill;");
      print("DROP TABLE scrapPostBill OK!");
    }
    try {
      StringBuffer sql = new StringBuffer();
      sql.write(" CREATE TABLE scrapPostBill(cid INTEGER PRIMARY KEY,"); //
      sql.write(" scrapId varchar(255),"); //id
      sql.write(" createDate varchar(255),"); //
      sql.write(" jsonString varchar(255),"); //
      sql.write(" type varchar(255),");
      sql.write(" reason varchar(255),");
      sql.write(" imageUrl text"); //
      sql.write(" );");
      await db.execute(sql.toString());
      print("CREATE TABLE scrapPostBill OK!");
      return true;
    } catch (e) {
      print("CREATE TABLE scrapPostBill Error:$e");
      return false;
    }
  }

  Future<bool> equipmentOnCarTable(Database db) async {
    bool exists = await checkTableExists(db, "EquipmentOnCar");
    if (exists) {
      await db.execute("DROP TABLE EquipmentOnCar;");
      print("DROP TABLE EquipmentOnCar OK!");
    }
    try {
      StringBuffer sql = new StringBuffer();
      sql.write(" CREATE TABLE EquipmentOnCar(cid INTEGER PRIMARY KEY,"); //
      sql.write(" id varchar(255),"); //id
      sql.write(" createDate varchar(255),"); //
      sql.write(" carId varchar(255),"); //
      sql.write(" equipmentDetailId varchar(255),"); //
      sql.write(" stockDetailId varchar(255),"); //
      sql.write(" amount varchar(255),"); //
      sql.write(" type varchar(255),");
      sql.write(" equipmentSpecificId varchar(255)"); //
      sql.write(" );");
      await db.execute(sql.toString());
      print("CREATE TABLE EquipmentOnCar OK!");
      return true;
    } catch (e) {
      print("CREATE TABLE EquipmentOnCar Error:$e");
      return false;
    }
  }

  Future<bool> sunminCarTable(Database db) async {
    bool exists = await checkTableExists(db, "SunminCar");
    if (exists) {
      await db.execute("DROP TABLE SunminCar;");
      print("DROP TABLE SunminCar OK!");
    }
    try {
      StringBuffer sql = new StringBuffer();
      sql.write(" CREATE TABLE SunminCar(cid INTEGER PRIMARY KEY,"); //装备表
      sql.write(" carId varchar(255),"); //车辆id
      sql.write(" shelfCellCode varchar(255),"); //设备二维码
      //sql.write(" equipmentsId varchar(255),");//关联id
      sql.write(" type varchar(255),"); //装载/卸载
      sql.write(" createDate varchar(255),"); //時間
      sql.write(" area varchar(255),"); //時間
      sql.write(" warehouseId varchar(255)"); //仓库id 默认0
      sql.write(" );");
      await db.execute(sql.toString());
      print("CREATE TABLE SunminCar OK!");
      return true;
    } catch (e) {
      print("CREATE TABLE SunminCar Error:$e");
      return false;
    }
  }

  Future<bool> sunminEquipmentsTable(Database db) async {
    bool exists = await checkTableExists(db, "SunminEquipments");
    if (exists) {
      await db.execute("DROP TABLE SunminEquipments;");
      print("DROP TABLE SunminEquipments OK!");
    }
    try {
      StringBuffer sql = new StringBuffer();
      sql.write(
          " CREATE TABLE SunminEquipments(cid INTEGER PRIMARY KEY,"); //装备表
      sql.write(" qrCode varchar(255),"); //车辆id
      sql.write(" amount varchar(255),"); //设备二维码
      sql.write(" carId varchar(255),"); //id
      sql.write(" glcarId varchar(255),"); //id
      // sql.write(" scrapId varchar(255),");//id
      // sql.write(" imageUrls varchar(255),");//图片地址
      sql.write(" equipmentDetailId varchar(255),"); //装载/卸载
      sql.write(" warehouseId varchar(255),"); //仓库id 默认0
      sql.write(" reason varchar(255),");
      sql.write(" warehouseStructureId varchar(255),");
      sql.write(" description varchar(255),");
      sql.write(" stockDetailId varchar(255),");
      sql.write(" type varchar(255),");
      sql.write(" createDate varchar(255),");
      sql.write(" shelfCellCode varchar(255),");
      sql.write(" area varchar(255),");
      sql.write(" total varchar(255)");
      sql.write(" );");
      await db.execute(sql.toString());
      print("CREATE TABLE SunminEquipments OK!");
      return true;
    } catch (e) {
      print("CREATE TABLE SunminEquipments Error:$e");
      return false;
    }
  }

  Future<bool> reasonDataTable(Database db) async {
    bool exists = await checkTableExists(db, "Reason");
    if (exists) {
      await db.execute("DROP TABLE Reason;");
      print("DROP TABLE Reason OK!");
    }
    try {
      StringBuffer sql = new StringBuffer();
      sql.write("CREATE TABLE Reason(cid INTEGER PRIMARY KEY,"); //装备表
      sql.write("id varchar(255),"); //单个设备id
      sql.write("createDate varchar(255),"); //值
      sql.write("code varchar(255),"); //值
      sql.write("name varchar(255),"); //值
      sql.write("type varchar(255),"); //值
      sql.write("remark varchar(255)"); //性能指标对应id
      sql.write(");");
      await db.execute(sql.toString());
      print("CREATE TABLE Reason OK!");
      return true;
    } catch (e) {
      print("CREATE TABLE Reason Error:$e");
      return false;
    }
  }

  Future<bool> equipmentDataTable(Database db) async {
    bool exists = await checkTableExists(db, "Equipment");
    if (exists) {
      await db.execute("DROP TABLE Equipment;");
      print("DROP TABLE Equipment OK!");
    }
    try {
      StringBuffer sql = new StringBuffer();
      sql.write(" CREATE TABLE Equipment(cid INTEGER PRIMARY KEY,"); //装备表
      sql.write(" equipmentSpecificId varchar(255),"); //单个设备id
      sql.write(" equipmentSpecificEquipmentDetailId varchar(255),"); //设备模板id
      sql.write(" equipmentSpecificQrCode varchar(255),"); //设备二维码
      sql.write(" equipmentSpecificSingle varchar(255),"); //管理方式(默认单件)
      sql.write(" equipmentSpecificCode varchar(255),"); //设备编码
      sql.write(" equipmentDetailName varchar(255),"); //设备模板名
      sql.write(" equipmentDetailPerfQuotaStr TEXT,"); //装备模板非核心性能指标
      sql.write(" warehouseStructureName varchar(255),"); //位置名称
      sql.write(" description varchar(255),"); //位置描述
      sql.write("equipmentId varchar(255),"); //类型Id
      sql.write(" equipmentPrefQuota varchar(255),"); //装备定义非核心性能指标
      sql.write(" stockDetailAmount varchar(255),"); //库存数量
      sql.write(" stockDetailWarehouseStructureId varchar(255),"); //货位id
      sql.write(" stockDetailWarehouseId varchar(255),"); //仓库id
      sql.write(" stockDetailStatus varchar(255),"); //库存状态
      sql.write(" unitId varchar(255),"); //数量单位id
      sql.write(" categoryCode varchar(255),"); //裝備類型id
      sql.write(" stockDetailId varchar(255),");
      sql.write(" unitName varchar(255)"); //数量单位名称
      sql.write(" );");
      await db.execute(sql.toString());
      print("CREATE TABLE Equipment OK!");
      return true;
    } catch (e) {
      print("CREATE TABLE Equipment Error:$e");
      return false;
    }
  }

  Future<bool> carDataTable(Database db) async {
    bool exists = await checkTableExists(db, "Car");
    if (exists) {
      await db.execute("DROP TABLE Car;");
      print("DROP TABLE Car OK!");
    }
    try {
      StringBuffer sql = new StringBuffer();
      sql.write("CREATE TABLE Car(cid INTEGER PRIMARY KEY,"); //装备表
      sql.write("id varchar(255),"); //id
      sql.write("name varchar(255),"); //名称
      sql.write("carNum varchar(255),"); //车牌号
      sql.write("carState varchar(255),"); //车辆状态
      sql.write("qrCode varchar(255)"); //二维码

      sql.write(");");
      await db.execute(sql.toString());
      print("CREATE TABLE Car OK!");
      return true;
    } catch (e) {
      print("CREATE TABLE Car Error:$e");
      return false;
    }
  }

  Future<bool> equipmentSpecificDataTable(Database db) async {
    bool exists = await checkTableExists(db, "EquipmentSpecific");
    if (exists) {
      await db.execute("DROP TABLE EquipmentSpecific;");
      print("DROP TABLE EquipmentSpecific OK!");
    }
    try {
      StringBuffer sql = new StringBuffer();
      sql.write(
          "CREATE TABLE EquipmentSpecific(cid INTEGER PRIMARY KEY,"); //装备表
      sql.write("equipmentSpecificId varchar(255),"); //单个设备id
      sql.write("value varchar(255),"); //值
      sql.write("equipmentIndexId varchar(255)"); //性能指标对应id

      sql.write(");");
      await db.execute(sql.toString());
      print("CREATE TABLE EquipmentSpecific OK!");
      return true;
    } catch (e) {
      print("CREATE TABLE EquipmentSpecific Error:$e");
      return false;
    }
  }

  Future<bool> equipmentIndexTable(Database db) async {
    bool exists = await checkTableExists(db, "EquipmentIndex");
    if (exists) {
      await db.execute("DROP TABLE EquipmentIndex;");
      print("DROP TABLE EquipmentIndex OK!");
    }
    try {
      StringBuffer sql = new StringBuffer();
      sql.write("CREATE TABLE EquipmentIndex(cid INTEGER PRIMARY KEY,"); //装备表
      sql.write("id varchar(255),"); //关联id
      sql.write("equipmentId varchar(255),"); //装备关联id
      sql.write("perfQuotaName varchar(255),"); //指标名称
      sql.write("perfQuotaDefinitionId varchar(255),"); //指标key
      sql.write("unitName varchar(255),"); //指标单位
      sql.write("isIot varchar(255),"); //是否物联
      sql.write("typeName varchar(255),"); //物联类型
      sql.write("typeCode varchar(255),"); //物联类型id
      sql.write("groupName varchar(255),"); //分组
      sql.write("indexId varchar(255),"); //指标id
      sql.write("sortNum varchar(255)"); //排序
      sql.write(");");
      await db.execute(sql.toString());
      print("CREATE TABLE EquipmentIndex OK!");
      return true;
    } catch (e) {
      print("CREATE TABLE EquipmentIndex Error:$e");
      return false;
    }
  }

  Future<bool> warehouseTable(Database db) async {
    bool exists = await checkTableExists(db, "Warehouse");
    if (exists) {
      await db.execute("DROP TABLE Warehouse;");
      print("DROP TABLE Warehouse OK!");
    }
    try {
      StringBuffer sql = new StringBuffer();
      sql.write("CREATE TABLE Warehouse(cid INTEGER PRIMARY KEY,"); //装备表
      sql.write("id varchar(255),"); //位置Id
      sql.write("code varchar(255),"); //位置编码
      sql.write("name varchar(255),"); //名称
      sql.write("fullName varchar(255),"); //全称
      sql.write("parentId varchar(255),"); //父ID
      sql.write("cellType varchar(255),"); //位置类型
      sql.write("cellCode varchar(255),"); //货位code
      sql.write("warehouseId varchar(255)"); //仓库ID
      sql.write(");");
      await db.execute(sql.toString());
      print("CREATE TABLE Warehouse OK!");
      return true;
    } catch (e) {
      print("CREATE TABLE Warehouse Error:$e");
      return false;
    }
  }

  Future<bool> createPlanInspectionTable(Database db) async {
    // 计划表
    bool exists = await checkTableExists(db, "PlanInspection");
    if (exists) {
      await db.execute("DROP TABLE PlanInspection;");
      print("DROP TABLE PlanInspection OK!");
    }

    // 计划关联检查点表
    exists = await checkTableExists(db, "PlanInspectionPoint");
    if (exists) {
      await db.execute("DROP TABLE PlanInspectionPoint;");
      print("DROP TABLE PlanInspectionPoint OK!");
    }

    try {
      StringBuffer sql = new StringBuffer();
      sql.write(" CREATE TABLE PlanInspection(cid INTEGER PRIMARY KEY,");
      sql.write(" planTaskId varchar(10),");
      sql.write("	taskName varchar(100),");
      sql.write("	beginTime varchar(50),");
      sql.write("	endTime varchar(50),");
      sql.write("	batchNo varchar(10),");
      sql.write("	finishStatus varchar(10),");
      sql.write(" userId varchar(10),");
      sql.write(" finshNum varchar(10),");
      sql.write(" taskPlanNum varchar(10),");
      sql.write(" inOrder varchar(10),");
      sql.write("	orgCode varchar(50)");
      sql.write("	)");

      // 执行create语句
      await db.execute(sql.toString());
      print("CREATE TABLE PlanInspection OK!");

      sql = new StringBuffer();
      sql.write("CREATE TABLE PlanInspectionPoint(cid INTEGER PRIMARY KEY,");
      sql.write("  pointId vahrcahr(10),");
      sql.write("  planTaskId vahrcahr(10),");
      sql.write("  taskName varchar(50),");
      sql.write("  routeId vahrcahr(10),");
      sql.write("  name varchar(50),");
      sql.write("  pointNO varchar(50),");
      sql.write("  offline vahrcahr(10),");
      sql.write("  status vahrcahr(10),");
      sql.write("  isFixed varchar(10),");
      sql.write("  orderNo varchar(10),");
      sql.write("  classify TEXT,");
      sql.write("  inputItems TEXT");
      sql.write("  );");
      // 执行create语句
      await db.execute(sql.toString());
      print("CREATE TABLE PlanInspectionPoint OK!");
      return true;
    } catch (e) {
      print("CREATE TABLE PlanInspectionPoint Error:$e");
      return false;
    }
  }

  Future<bool> createPointTable(Database db) async {
    bool exists = await checkTableExists(db, "Point");
    if (exists) {
      await db.execute("DROP TABLE Point;");
      print("DROP TABLE Point OK!");
    }
    try {
      StringBuffer sql = new StringBuffer();
      sql.write("CREATE TABLE Point(cid INTEGER PRIMARY KEY,");
      sql.write("  pointId vahrcahr(10),");
      sql.write("  pointName varchar(50),");
      sql.write("  pointNo varchar(50),");
      sql.write("  level varchar(50),");
      sql.write("  isFiexed varchar(10),");
      sql.write("  shotMinNumber varchar(10),");
      sql.write("  shotMaxNumber varchar(10),");
      sql.write("  fixedShot varchar(10),");
      sql.write("  usuallyShot varchar(10),");
      sql.write("  routeName varchar(50),");
      sql.write("  classifyNames varchar(50),");
      sql.write("  chargePerson varchar(50),");
      sql.write("  departmentName varchar(50),");
      sql.write("  classify TEXT,");
      sql.write("  remark varchar(50),");
      sql.write("  inputItems TEXT");
      sql.write("  );");
      await db.execute(sql.toString());
      print("CREATE TABLE Point OK!");
      return true;
    } catch (e) {
      print("CREATE TABLE Point Error:$e");
      return false;
    }
  }

  Future<bool> createClassifyTable(Database db) async {
    bool exists = await checkTableExists(db, "Classify");
    if (exists) {
      await db.execute("DROP TABLE Classify;");
      print("DROP TABLE Classify OK!");
    }
    try {
      StringBuffer sql = new StringBuffer();
      sql.write("CREATE TABLE Classify(cid INTEGER PRIMARY KEY,");
      sql.write("classifyId varchar(10),");
      sql.write("pointId varchar(10),");
      sql.write("classifyName varchar(50)");
      sql.write(");");
      await db.execute(sql.toString());
      print("CREATE TABLE Classify OK!");
      return true;
    } catch (e) {
      print("CREATE TABLE Classify Error:$e");
      return false;
    }
  }

  Future<bool> createInputItemTable(Database db) async {
    bool exists = await checkTableExists(db, "InputItem");
    if (exists) {
      await db.execute("DROP TABLE InputItem;");
      print("DROP TABLE InputItem OK!");
    }
    try {
      StringBuffer sql = new StringBuffer();
      sql.write(" CREATE TABLE InputItem(cid INTEGER PRIMARY KEY,");
      sql.write(" id varchar(10),");
      sql.write(" pointId varchar(10),  ");
      sql.write("	createDate varchar(50),");
      sql.write("	catalogId varchar(50),");
      sql.write("	createBy varchar(50),");
      sql.write("	dataJson varchar(1000),");
      sql.write("	defaultValue varchar(50),");
      sql.write("	inputJson varchar(1000),");
      sql.write("	isMultiline varchar(10),");
      sql.write("	isMust varchar(10),");
      sql.write("	isScore varchar(10),");
      sql.write("	itemType varchar(10),");
      sql.write("	name varchar(100),");
      sql.write("	orderNo varchar(10),");
      sql.write("	orgCode varchar(50),");
      sql.write("	pictureJson varchar(4000),");
      sql.write("	remark varchar(500),");
      sql.write("	isDelete varchar(10),");
      sql.write("	pOrderNo varchar(10),");
      sql.write("	pointItemId varchar(10),");
      sql.write("	classifyNames varchar(20),");
      sql.write("	classifyIds varchar(20),");
      sql.write("	riskDesc varchar(1000)");
      sql.write("	)");

      await db.execute(sql.toString());
      print("CREATE TABLE InputItem OK!");
      return true;
    } catch (e) {
      print("CREATE TABLE InputItem Error:$e");
      return false;
    }
  }

  Future<bool> createCheckReordTable(Database db) async {
    bool exists = await checkTableExists(db, "CheckReord");
    if (exists) {
      db.execute("DROP TABLE CheckReord;");
      print("DROP TABLE CheckReord!");
    }
    try {
      StringBuffer sql = new StringBuffer();
      sql.write("CREATE TABLE CheckReord(cid INTEGER PRIMARY KEY,");
      sql.write("  recordJson text");
      sql.write("  );");
      await db.execute(sql.toString());
      print("CREATE TABLE CheckReord OK!");
      return true;
    } catch (e) {
      print("CREATE TABLE CheckReord Error:$e");
      return false;
    }
  }

  Future<bool> createTasksTable(Database db) async {
    bool exists = await checkTableExists(db, "Tasks");
    if (exists) {
      db.execute("DROP TABLE Tasks;");
      print("DROP TABLE Tasks!");
    }
    try {
      StringBuffer sql = new StringBuffer();
      sql.write("CREATE TABLE Tasks(cid INTEGER PRIMARY KEY,");
      sql.write("  id varchar(10),");
      sql.write("  title varchar(50),");
      sql.write("  publishTime varchar(20),");
      sql.write("  executor varchar(10),");
      sql.write("  status varchar(10),");
      sql.write("  jsonTask text,");
      sql.write("  jsonTaskDetail text");
      sql.write("  );");
      await db.execute(sql.toString());
      print("CREATE TABLE Tasks OK!");
      return true;
    } catch (e) {
      print("CREATE TABLE Tasks Error:$e");
      return false;
    }
  }

  Future<bool> createFeedbackTaskTable(Database db) async {
    bool exists = await checkTableExists(db, "FeedbackTask");
    if (exists) {
      db.execute("DROP TABLE FeedbackTask;");
      print("DROP TABLE FeedbackTask!");
    }
    try {
      StringBuffer sql = new StringBuffer();
      sql.write("CREATE TABLE FeedbackTask(cid INTEGER PRIMARY KEY,");
      sql.write("  id varchar(10),");
      sql.write("  title varchar(50),");
      sql.write("  publishTime varchar(20),");
      sql.write("  executor varchar(10),");
      sql.write("  status varchar(10),");
      sql.write("  jsonData text,");
      sql.write("  jsonPictures text");
      sql.write("  );");
      await db.execute(sql.toString());
      print("CREATE TABLE FeedbackTask OK!");
      return true;
    } catch (e) {
      print("CREATE TABLE FeedbackTask Error:$e");
      return false;
    }
  }

  Future<bool> checkTableExists(Database db, String tableName) async {
    try {
      var sql =
          "select * from sqlite_master where type = 'table' and name = '$tableName'";
      List<Map<String, dynamic>> lst = await db.rawQuery(sql);
      if (null == lst) {
        lst = new List();
      }
      if (lst.length > 0) {
        return true;
      } else {
        return false;
      }
    } catch (e) {
      print(e);
      return false;
    }
  }

  //获取装备
  Future<bool> loadEquipmentData(Database db) async {
    dynamic dataPlan;
    //访问API获取数据
    try {
      dataPlan = await HttpUtil().get(ApiAddress.APPDOWNLOADDATAS);
      print('获取同步数据，巡检计划：$dataPlan');
    } catch (e) {
      print("访问${ApiAddress.APPDOWNLOADDATAS} 失败！");
      return false;
    }
    //清空表数据
    try {
      //
      await db.execute("delete from Equipment");
      await db.execute("delete from Car");
      await db.execute("delete from EquipmentSpecific");
      await db.execute("delete from EquipmentIndex");
      await db.execute("delete from Warehouse");
      await db.execute("delete from Reason");
      await db.execute("delete from EquipmentOnCar");
      print("delete from equipment OK!");
    } catch (e) {
      print("delete from equipment Error:$e");
      return false;
    }
    //导入数据
    try {
      var count = 0;
      StringBuffer sql;
      for (var plan in dataPlan['result']["downloadEquipmentDatas"]) {
        // 插入计划
        sql = new StringBuffer();
        sql.write("insert into Equipment(");
        sql.write("equipmentSpecificId,");
        sql.write("equipmentSpecificEquipmentDetailId,");
        sql.write("equipmentSpecificQrCode,");
        sql.write("equipmentSpecificSingle,");
        sql.write("equipmentSpecificCode,");
        sql.write("equipmentDetailName,");
        sql.write("equipmentDetailPerfQuotaStr,");
        sql.write("warehouseStructureName,");
        sql.write("description,");
        sql.write("equipmentId,");
        sql.write("equipmentPrefQuota,");
        sql.write("stockDetailAmount,");
        sql.write("stockDetailWarehouseStructureId,");
        sql.write("stockDetailWarehouseId,");
        sql.write("stockDetailStatus,");
        sql.write("unitId,");
        sql.write("categoryCode,");
        sql.write("stockDetailId,");
        sql.write("unitName");
        sql.write(")");
        sql.write("values");
        sql.write("(");
        sql.write("'" + plan['equipmentSpecificId'].toString() + "',");
        sql.write(
            "'" + plan['equipmentSpecificEquipmentDetailId'].toString() + "',");
        sql.write("'" + plan['equipmentSpecificQrCode'].toString() + "',");
        sql.write("'" + plan['equipmentSpecificSingle'].toString() + "',");
        sql.write("'" + plan['equipmentSpecificCode'].toString() + "',");
        sql.write("'" + plan['equipmentDetailName'].toString() + "',");
        sql.write("'" + plan['equipmentDetailPerfQuotaStr'].toString() + "',");
        sql.write("'" + plan['warehouseStructureName'].toString() + "',");
        sql.write("'" + plan['description'].toString() + "',");
        sql.write("'" + plan['equipmentId'].toString() + "',");
        sql.write("'" + plan['equipmentPrefQuota'].toString() + "',");
        sql.write("'" + plan['stockDetailAmount'].toString() + "',");
        sql.write(
            "'" + plan['stockDetailWarehouseStructureId'].toString() + "',");
        sql.write("'" + plan['stockDetailWarehouseId'].toString() + "',");
        sql.write("'" + plan['stockDetailStatus'].toString() + "',");
        sql.write("'" + plan['unitId'].toString() + "',");
        sql.write("'" + plan['categoryCode'].toString() + "',");
        sql.write("'" + plan['stockDetailId'].toString() + "',");
        sql.write("'" + plan['unitName'].toString() + "'");
        sql.write(")");
        await db.execute(sql.toString());
        print("insert into Equipment id:${plan['equipmentSpecificId']} OK!");
        count++;
      }
    } catch (e) {
      print("insert into Equipment Error:$e");
      return false;
    }

    try {
      var count = 0;
      StringBuffer sql;
      for (var plan in dataPlan['result']["reason"]) {
        // 插入计划
        sql = new StringBuffer();
        sql.write("insert into Reason(");
        sql.write("id,");
        sql.write("name,");
        sql.write("createDate,");
        sql.write("code,");
        sql.write("type,");
        sql.write("remark");
        sql.write(")");
        sql.write("values");
        sql.write("(");
        sql.write("'" + plan['id'].toString() + "',");
        sql.write("'" + plan['name'].toString() + "',");
        sql.write("'" + plan['createDate'].toString() + "',");
        sql.write("'" + plan['code'].toString() + "',");
        sql.write("'" + plan['type'].toString() + "',");
        sql.write("'" + plan['remark'].toString() + "'");
        sql.write(")");
        await db.execute(sql.toString());
        print("insert into Reason id:${plan['id']} OK!");
        count++;
      }
      print("insert into Reason OK! Count:" + count.toString());
    } catch (e) {
      print("insert into Reason Error:$e");
      return false;
    }

    try {
      var count = 0;
      StringBuffer sql;
      for (var plan in dataPlan['result']["downloadCarDatas"]) {
        // 插入计划
        sql = new StringBuffer();
        sql.write("insert into Car(");
        sql.write("id,");
        sql.write("name,");
        sql.write("carNum,");
        sql.write("carState,");
        sql.write("qrCode");
        sql.write(")");
        sql.write("values");
        sql.write("(");
        sql.write("'" + plan['id'].toString() + "',");
        sql.write("'" + plan['name'].toString() + "',");
        sql.write("'" + plan['carNum'].toString() + "',");
        sql.write("'" + plan['carState'].toString() + "',");
        sql.write("'" + plan['qrCode'].toString() + "'");
        sql.write(")");
        await db.execute(sql.toString());
        print("insert into Car id:${plan['qrCode']} OK!");
        count++;
      }
      print("insert into Car OK! Count:" + count.toString());
    } catch (e) {
      print("insert into Car Error:$e");
      return false;
    }

    try {
      var count = 0;
      StringBuffer sql;
      for (var plan in dataPlan['result']["equipmentSpecificIndexs"]) {
        // 插入计划
        sql = new StringBuffer();
        sql.write("insert into EquipmentSpecific(");
        sql.write("equipmentSpecificId,");
        sql.write("value,");
        sql.write("equipmentIndexId");
        sql.write(")");
        sql.write("values");
        sql.write("(");
        sql.write("'" + plan['equipmentSpecificId'].toString() + "',");
        sql.write("'" + plan['value'].toString() + "',");
        sql.write("'" + plan['equipmentIndexId'].toString() + "'");
        sql.write(")");
        await db.execute(sql.toString());
        print(
            "insert into EquipmentSpecific id:${plan['equipmentSpecificId']} OK!");
        count++;
      }
      print("insert into EquipmentSpecific OK! Count:" + count.toString());
    } catch (e) {
      print("insert into EquipmentSpecific Error:$e");
      return false;
    }

    try {
      var count = 0;
      StringBuffer sql;
      for (var plan in dataPlan['result']["equipmentIndex"]) {
        // 插入计划
        sql = new StringBuffer();
        sql.write("insert into EquipmentIndex(");
        sql.write("id,");
        sql.write("equipmentId,");
        sql.write("perfQuotaName,");
        sql.write("perfQuotaDefinitionId,");
        sql.write("unitName,");
        sql.write("isIot,");
        sql.write("typeName,");
        sql.write("typeCode,");
        sql.write("groupName,");
        sql.write("indexId,");
        sql.write("sortNum");
        sql.write(")");
        sql.write("values");
        sql.write("(");
        sql.write("'" + plan['id'].toString() + "',");
        sql.write("'" + plan['equipmentId'].toString() + "',");
        sql.write("'" + plan['perfQuotaName'].toString() + "',");
        sql.write("'" + plan['perfQuotaDefinitionId'].toString() + "',");
        sql.write("'" + plan['unitName'].toString() + "',");
        sql.write("'" + plan['isIot'].toString() + "',");
        sql.write("'" + plan['typeName'].toString() + "',");
        sql.write("'" + plan['typeCode'].toString() + "',");
        sql.write("'" + plan['groupName'].toString() + "',");
        sql.write("'" + plan['indexId'].toString() + "',");
        sql.write("'" + plan['sortNum'].toString() + "'");
        sql.write(")");
        await db.execute(sql.toString());
        print("insert into EquipmentIndex id:${plan['id']} OK!");
        count++;
      }
      print("insert into EquipmentIndex OK! Count:" + count.toString());
    } catch (e) {
      print("insert into EquipmentIndex Error:$e");
      return false;
    }

    try {
      var count = 0;
      StringBuffer sql;
      for (var plan in dataPlan['result']["warehouseStructure"]) {
        // 插入计划
        sql = new StringBuffer();
        sql.write("insert into Warehouse(");
        sql.write("id,");
        sql.write("code,");
        sql.write("name,");
        sql.write("fullName,");
        sql.write("parentId,");
        sql.write("cellType,");
        sql.write("cellCode,");
        sql.write("warehouseId");
        sql.write(")");
        sql.write("values");
        sql.write("(");
        sql.write("'" + plan['id'].toString() + "',");
        sql.write("'" + plan['code'].toString() + "',");
        sql.write("'" + plan['name'].toString() + "',");
        sql.write("'" + plan['fullName'].toString() + "',");
        sql.write("'" + plan['parentId'].toString() + "',");
        sql.write("'" + plan['cellType'].toString() + "',");
        sql.write("'" + plan['cellCode'].toString() + "',");
        sql.write("'" + plan['warehouseId'].toString() + "'");
        sql.write(")");
        await db.execute(sql.toString());
        print("insert into Warehouse id:${plan['id']} OK!");
        count++;
      }
      print("insert into Warehouse OK! Count:" + count.toString());
    } catch (e) {
      print("insert into Warehouse Error:$e");
      return false;
    }

    try {
      var count = 0;
      StringBuffer sql;
      for (var plan in dataPlan['result']["equipmentOnCar"]) {
        // 插入计划
        sql = new StringBuffer();
        sql.write("insert into EquipmentOnCar(");
        sql.write("id,");
        sql.write("createDate,");
        sql.write("carId,");
        sql.write("equipmentDetailId,");
        sql.write("stockDetailId,");
        sql.write("amount,");
        sql.write("equipmentSpecificId");
        sql.write(")");
        sql.write("values");
        sql.write("(");
        sql.write("'" + plan['id'].toString() + "',");
        sql.write("'" + plan['createDate'].toString() + "',");
        sql.write("'" + plan['carId'].toString() + "',");
        sql.write("'" + plan['equipmentDetailId'].toString() + "',");
        sql.write("'" + plan['stockDetailId'].toString() + "',");
        sql.write("'" + plan['amount'].toString() + "',");
        sql.write("'" + plan['equipmentSpecificId'].toString() + "'");
        sql.write(")");
        await db.execute(sql.toString());
        print("insert into EquipmentOnCar id:${plan['id']} OK!");
        count++;
      }
      print("insert into EquipmentOnCar OK! Count:" + count.toString());
    } catch (e) {
      print("insert into EquipmentOnCar Error:$e");

      return false;
    }

    try {
      var count = 0;
      StringBuffer sql;
      for (var plan in dataPlan['result']["extinguishantOnCar"]) {
        // 插入计划
        sql = new StringBuffer();
        sql.write("insert into EquipmentOnCar(");
        sql.write("id,");
        sql.write("createDate,");
        sql.write("carId,");
        sql.write("equipmentDetailId,");
        sql.write("stockDetailId,");
        sql.write("amount,");
        sql.write("equipmentSpecificId");
        sql.write(")");
        sql.write("values");
        sql.write("(");
        sql.write("'" + plan['id'].toString() + "',");
        sql.write("'" + plan['createDate'].toString() + "',");
        sql.write("'" + plan['carId'].toString() + "',");
        sql.write("'" + plan['equipmentDetailId'].toString() + "',");
        sql.write("'" + plan['stockDetailId'].toString() + "',");
        sql.write("'" + plan['amount'].toString() + "',");
        sql.write("'" + plan['equipmentSpecificId'].toString() + "'");
        sql.write(")");
        await db.execute(sql.toString());
        print("insert into EquipmentOnCar id:${plan['id']} OK!");
        count++;
      }
      print("insert into EquipmentOnCar OK! Count:" + count.toString());
    } catch (e) {
      print("insert into EquipmentOnCar Error:$e");

      return false;
    }
    return true;
  }

  Future<bool> loadPlanData(Database db) async {
    dynamic dataPlan;
    //访问API获取数据
    try {
      dataPlan = await HttpUtil().get(ApiAddress.OFFLINE_QUERYPLANTASK);
      print('获取同步数据，巡检计划：$dataPlan');
    } catch (e) {
      print("访问$ApiAddress.OFFLINE_QUERYPLANTASK 失败！");
      return false;
    }
    //清空表数据
    try {
      // 删除当前登陆用户的计划数据
      await db.execute("delete from PlanInspection");
      print("delete from PlanInspection OK!");
    } catch (e) {
      print("delete from PlanInspection Error:$e");
      return false;
    }
    //导入数据
    try {
      var count = 0;
      StringBuffer sql;
      for (var plan in dataPlan["dataList"]) {
        // 插入计划
        sql = new StringBuffer();
        sql.write("insert into PlanInspection(");
        sql.write("planTaskId,");
        sql.write("taskName,");
        sql.write("beginTime,");
        sql.write("endTime,");
        sql.write("batchNo,");
        sql.write("finishStatus,");
        sql.write("userId,");
        sql.write("finshNum,");
        sql.write("taskPlanNum,");
        sql.write("inOrder,");
        sql.write("orgCode");
        sql.write(")");
        sql.write("values");
        sql.write("(");
        sql.write("'" + plan['planTaskId'].toString() + "',");
        sql.write("'" + plan['taskName'].toString() + "',");
        sql.write("'" + plan['beginTime'].toString() + "',");
        sql.write("'" + plan['endTime'].toString() + "',");
        sql.write("'" + plan['batchNo'].toString() + "',");
        // 已超时，本地为 已执行
        if (plan['finishStatus'].toString() == '3') {
          sql.write("'2',"); // 已执行
        } else {
          sql.write("'" +
              plan['finishStatus'].toString() +
              "',"); // 计划所有点都巡检完成，此状态修改为 2：已执行
        }
        sql.write("'" + plan['userId'].toString() + "',");
        sql.write("'" + plan['finshNum'].toString() + "',");
        sql.write("'" + plan['taskPlanNum'].toString() + "',");
        sql.write("'" + plan['inOrder'].toString() + "',");
        sql.write("'" + plan['orgCode'].toString() + "'");
        sql.write(")");
        await db.execute(sql.toString());
        print("insert into PlanInspection id:${plan['planTaskId']} OK!");

        // 插入计划相关点
        var jsonPoints = plan["points"];
        for (var point in jsonPoints) {
          sql = new StringBuffer();
          sql.write("insert into PlanInspectionPoint(");
          sql.write("pointId,");
          sql.write("planTaskId,");
          sql.write("taskName,");
          sql.write("routeId,");
          sql.write("name,");
          sql.write("pointNO,");
          sql.write("offline,");
          sql.write("status,");
          sql.write("isFixed,");
          sql.write("orderNo,");
          sql.write("classify,");
          sql.write("inputItems");
          sql.write(")");
          sql.write("values");
          sql.write("(");
          sql.write("'" + point['pointId'].toString() + "',");
          sql.write("'" + point['planTaskId'].toString() + "',");
          sql.write("'" + point['taskName'].toString() + "',");
          sql.write("'" + point['routeId'].toString() + "',");
          sql.write("'" + point['name'].toString() + "',");
          sql.write("'" + point['pointNO'].toString() + "',");
          sql.write("'" + point['offline'].toString() + "',");
          // 0:未开始
          if ("0" == point['status'].toString()) {
            sql.write("'0',"); // 本地标识为 未巡检
          } else {
            sql.write("'1',"); // 本地标识为 已巡检
          }
          sql.write("'" + point['isFixed'].toString() + "',");

          sql.write("'" + point['orderNo'].toString() + "',");
          // 检查项分类
          var classify = json.encode(point['classify']);
          sql.write("'$classify',");
          // 所有检查项
          var inputItems = json.encode(point['inputItems']);
          sql.write("'$inputItems'");
          sql.write(")");
          await db.execute(sql.toString());
          print("insert into PlanInspectionPoint id:${point['pointId']} OK!");
        }
        count++;
      }
      print("insert into PlanInspection OK! Count:" + count.toString());
    } catch (e) {
      print("insert into PlanInspection Error:$e");
      return false;
    }
    return true;
  }

  Future<bool> loadTaskData(Database db) async {
    dynamic taskData;
    //获取API数据
    try {
      taskData = await HttpUtil().get(ApiAddress.QUERY_OFFLINE_TASKS);
      print('获取同步数据，任务：$taskData');
    } catch (e) {
      print("访问$ApiAddress.QUERY_OFFLINE_TASKS 失败！");
      return false;
    }
    //TODO 清空数据库数据
    try {
      await db.execute("delete from Tasks");
      print("delete from Tasks OK!");
    } catch (e) {
      print("delete from Tasks Error:$e");
      return false;
    }
    //TODO 导入数据
    try {
      var count = 0;
      StringBuffer sql;
      for (var task in taskData["dataList"]) {
        sql = new StringBuffer();
        sql.write("insert into Tasks(");
        sql.write("id,");
        sql.write("title,");
        sql.write("publishTime,");
        sql.write("executor,");
        sql.write("status,");
        sql.write("jsonTask,");
        sql.write("jsonTaskDetail");
        sql.write(")");
        sql.write("values");
        sql.write("(");
        sql.write("'" + task['id'].toString() + "',");
        sql.write("'" + task['title'].toString() + "',");
        sql.write("'" + task['publishTime'].toString() + "',");
        sql.write("'" + task['executor'].toString() + "',");
        sql.write("'" + task['status'].toString() + "',");

        var strTask = json.encode(task['task']);
        sql.write("'$strTask',");

        var strTaskDetail = json.encode(task['taskDetail']);
        sql.write("'$strTaskDetail'");

        sql.write(")");

        await db.execute(sql.toString());
        print("insert into Tasks id:${task['id']} OK!");
        count++;
      }
      print("insert into Tasks OK! Count:" + count.toString());
    } catch (e) {
      print("insert into Tasks Error:$e");
      return false;
    }
    return true;
  }

  Future<bool> loadPointData(Database db) async {
    dynamic pointData;
    try {
      pointData = await HttpUtil().get(ApiAddress.QUERY_OFFLINE_POINT);
      print('同步数据，巡检点：$pointData');
    } catch (e) {
      print("访问$ApiAddress.QUERY_OFFLINE_POINT 失败！");
      return false;
    }

    try {
      await db.execute("delete from Point");
      print("delete from Point OK!");
    } catch (e) {
      print("delete from Point Error:$e");
      return false;
    }

    try {
      var count = 0;
      StringBuffer sql;
      for (var point in pointData["dataList"]) {
        sql = new StringBuffer();
        sql.write("insert into Point(");
        sql.write("pointId,");
        sql.write("pointName,");
        sql.write("pointNo,");
        sql.write("level,");
        sql.write("isFiexed,");
        sql.write("shotMinNumber,");
        sql.write("shotMaxNumber,");
        sql.write("fixedShot,");
        sql.write("usuallyShot,");
        sql.write("routeName,");
        sql.write("classifyNames,");
        sql.write("chargePerson,");
        sql.write("departmentName,");
        sql.write("classify,");
        sql.write("remark,");
        sql.write("inputItems");
        sql.write(")");
        sql.write("values");
        sql.write("(");
        sql.write("'" + point['pointId'].toString() + "',");
        sql.write("'" + point['pointName'].toString() + "',");
        sql.write("'" + point['pointNo'].toString() + "',");
        sql.write("'" + point['level'].toString() + "',");
        sql.write("'" + point['isFiexed'].toString() + "',");
        sql.write("'" + point['shotMinNumber'].toString() + "',");
        sql.write("'" + point['shotMaxNumber'].toString() + "',");
        sql.write("'" + point['fixedShot'].toString() + "',");
        sql.write("'" + point['usuallyShot'].toString() + "',");
        sql.write("'" + point['routeName'].toString() + "',");
        sql.write("'" + point['classifyNames'].toString() + "',");
        sql.write("'" + point['chargePerson'].toString() + "',");
        sql.write("'" + point['departmentName'].toString() + "',");

        var classify = json.encode(point['classify']);
        sql.write("'$classify',");

//        var riskDesc = json.encode(point['riskDesc']);
//        sql.write("'$riskDesc',");
        sql.write("'" + point['remark'].toString() + "',");
        var inputItems = json.encode(point['inputItems']);
        sql.write("'$inputItems'");

        sql.write(")");

        await db.execute(sql.toString());
        print("insert into Point PointId:$point['pointId'] OK!");
        count++;
      }
      print("insert into Point OK! Count:" + count.toString());
    } catch (e) {
      print("insert into Point Error:$e");
      return false;
    }
    return true;
  }

  // 保存巡检记录
  Future<bool> insertCheckRecord(Database db, String jsonData) async {
    try {
      StringBuffer sql;
      sql = new StringBuffer();
      sql.write("insert into CheckReord(");
      sql.write("recordJson");
      // 有ItemID的是属于检查项的，没有的是检查点的
      sql.write(")");
      sql.write("values");
      sql.write("(");
      sql.write("'$jsonData'");
      sql.write(")");
      await db.execute(sql.toString());

      // 更新状态
      var recordData = json.decode(jsonData);
      if (null != recordData["pointId"] &&
          null != recordData["planTaskId"] &&
          recordData["planTaskId"] != 0) {
        // 更新本地，计划，以及其对应点的状态
        await db.execute(
            "update PlanInspectionPoint set status = ? where pointId = ? and planTaskId = ? ",
            ["1", recordData["pointId"], recordData["planTaskId"]]);
        // 查询未巡检点个数
        List<Map<String, dynamic>> noexecpoints = await db.rawQuery(
            "select count(1) as ct from PlanInspectionPoint where planTaskId = ? and status = '0'",
            [recordData["planTaskId"]]);
        print(noexecpoints);
        if (null != noexecpoints && noexecpoints.length > 0) {
          Map<String, dynamic> count = noexecpoints[0];
          if (null != count && null != count["ct"]) {
            int ct = JunMath.parseInt(count["ct"].toString());
            // 更新剩余数量
            await db.execute(
                "update PlanInspection set finshNum = taskPlanNum - ? where planTaskId = ? ",
                [ct, recordData["planTaskId"]]);
            if (ct == 0) {
              // 更新计划状态为已结束
              await db.execute(
                  "update PlanInspection set finishStatus = ? where planTaskId = ? ",
                  ["2", recordData["planTaskId"]]);
            }
          }
        }
      }
      print("insert into CheckReord OK!");
    } catch (e) {
      print("insert into Point Error:$e");
      return false;
    }
    return true;
  }

  Future<List<Map<String, dynamic>>> getCheckRecords(Database db) async {
    try {
      var sql = new StringBuffer();
      sql.write("select ");
      sql.write("* ");
      sql.write("from CheckReord;");
      List<Map<String, dynamic>> lst = await db.rawQuery(sql.toString());
      if (null == lst) {
        lst = new List();
      }
      return lst;
    } catch (e) {
      print(e);
      return new List();
    }
  }

  Future<List<Map<String, dynamic>>> getPoints(Database db) async {
    try {
      var sql = new StringBuffer();
      sql.write("select ");
      sql.write("* ");
      sql.write("from Point");
      List<Map<String, dynamic>> lst = await db.rawQuery(sql.toString());
      if (null == lst) {
        lst = new List();
      }
      return lst;
    } catch (e) {
      print(e);
      return new List();
    }
  }

  Future<List<Map<String, dynamic>>> getPlanInspections(Database db) async {
    try {
      var sql = new StringBuffer();
      sql.write("select ");
      sql.write("* ");
      sql.write("from PlanInspection");
      List<Map<String, dynamic>> lst = await db.rawQuery(sql.toString());
      if (null == lst) {
        lst = new List();
      }
      return lst;
    } catch (e) {
      print(e);
      return new List();
    }
  }

  Future<Map<String, dynamic>> getPlanInspectionById(
      Database db, int planId) async {
    try {
      // 查询参数
      List<dynamic> arguments = new List();
      if (null == planId) {
        planId = 0;
      }
      arguments.add(planId);
      var sql = new StringBuffer();
      sql.write("select ");
      sql.write("* ");
      sql.write("from PlanInspection where planTaskId = ?");
      List<Map<String, dynamic>> lst =
          await db.rawQuery(sql.toString(), arguments);
      if (null == lst) {
        return null;
      }
      return lst[0];
    } catch (e) {
      print(e);
      return null;
    }
  }

  Future<List<Map<String, dynamic>>> getPlanInspectionPoints(
      Database db, int planId) async {
    // 查询参数
    List<dynamic> arguments = new List();
    if (null == planId) {
      planId = 0;
    }
    arguments.add(planId);
    try {
      var sql = new StringBuffer();
      sql.write("select ");
      sql.write("* ");
      sql.write("from PlanInspectionPoint where planTaskId = ?");
      List<Map<String, dynamic>> lst =
          await db.rawQuery(sql.toString(), arguments);
      if (null == lst) {
        lst = new List();
      }
      return lst;
    } catch (e) {
      print(e);
      return new List();
    }
  }

  Future<List<Map<String, dynamic>>> queryData(String sql,
      [List<dynamic> arguments]) async {
    try {
      Database db = await openDb();
      List<Map<String, dynamic>> lst = await db.rawQuery(sql, arguments);
      await db.close();
      return lst;
    } catch (e) {
      print(e);
      return new List();
    }
  }

  Future<bool> excuteSql(String sql, [List<dynamic> arguments]) async {
    try {
      Database db = await openDb();
      await db.execute(sql, arguments);
      await db.close();
      return true;
    } catch (e) {
      print(e);
      return false;
    }
  }

  Future<bool> closeDb(Database db) async {
    try {
      await db.close();
      print("db.close OK");
      return true;
    } catch (e) {
      print("close db Error:$e");
      return false;
    }
  }

  //获取建筑树
  Future<List> getWarehouse(Database db) async {
    try {
      var sql = new StringBuffer();
      sql.write("select ");
      sql.write("* ");
      sql.write("from Warehouse;");
      List<Map<String, dynamic>> lst = await db.rawQuery(sql.toString());
      List<dynamic> list = [];
      for (var par in lst) {
        list.add({
          'cid': par['cid'].toString(),
          'id': par['id'].toString(),
          'code': par['code'].toString(),
          'name': par['name'].toString(),
          'fullName': par['fullName'].toString(),
          'parentId': par['parentId'].toString(),
          'cellType': par['cellType'].toString(),
          'cellCode': par['cellCode'].toString(),
          'warehouseId': par['warehouseId'].toString(),
          'children': []
        });
      }
      if (null == list) {
        list = new List();
      }
      return list;
    } catch (e) {
      print(e);
      return new List();
    }
  }

  //获取报废原因
  Future<List<Map<String, dynamic>>> getReason(Database db) async {
    try {
      var sql = new StringBuffer();
      sql.write("select ");
      sql.write("* ");
      sql.write("from Reason;");
      List<Map<String, dynamic>> lst = await db.rawQuery(sql.toString());
      if (null == lst) {
        lst = new List();
      }
      return lst;
    } catch (e) {
      print(e);
      return new List();
    }
  }

  //装备扫码
  Future<Map<String, dynamic>> getEquipment(Database db, String qrCode) async {
    try {
      var sql = new StringBuffer();
      sql.write("select ");
      sql.write("* ");
      String code;
      if (qrCode.indexOf('#') < 0) {
        code = qrCode;
      } else {
        code = qrCode.substring(3);
      }

      sql.write("from Equipment where equipmentSpecificQrCode =$code;");
      List<Map<String, dynamic>> lst = await db.rawQuery(sql.toString());
      if (null == lst) {
        return null;
      }
      return lst[0];
    } catch (e) {
      print(e);
      return null;
    }
  }

  //装备扫码
  Future<Map<String, dynamic>> getEquipmentsum(
      Database db, String stockDetailId) async {
    try {
      var sql = new StringBuffer();
      sql.write("select ");
      sql.write("* ");
      //String code=qrCode.substring(3);
      sql.write("from Equipment where stockDetailId =$stockDetailId;");
      List<Map<String, dynamic>> lst = await db.rawQuery(sql.toString());
      if (null == lst) {
        return null;
      }
      return lst[0];
    } catch (e) {
      print(e);
      return null;
    }
  }

  Future<Map<String, dynamic>> getEquipmentIDsum(
      Database db, String equipDetaId) async {
    try {
      var sql = new StringBuffer();
      sql.write("select ");
      sql.write("* ");
      sql.write(
          "from Equipment where equipmentSpecificEquipmentDetailId =$equipDetaId;");
      List<Map<String, dynamic>> lst = await db.rawQuery(sql.toString());
      if (null == lst) {
        return null;
      }
      return lst[0];
    } catch (e) {
      print(e);
      return null;
    }
  }

  //车辆扫码
  Future<List<Map<String, dynamic>>> getCar(Database db, String qrCode) async {
    try {
      var sql = new StringBuffer();
      sql.write("select ");
      sql.write("* ");
      if (qrCode.isEmpty) {
        sql.write("from Car;");
      } else {
        String code = qrCode.substring(3);
        sql.write("from Car where qrCode =$code;");
      }
      List<Map<String, dynamic>> lst = await db.rawQuery(sql.toString());
      if (null == lst) {
        lst = new List();
      }
      return lst;
    } catch (e) {
      print(e);
      return new List();
    }
  }

  Future<List<Map<String, dynamic>>> getCarsum(
      Database db, String qrCode) async {
    try {
      var sql = new StringBuffer();
      sql.write("select ");
      sql.write("* ");
      if (qrCode.isEmpty) {
        sql.write("from Car;");
      } else {
        // String code=qrCode.substring(3);
        sql.write("from Car where id =$qrCode;");
      }
      List<Map<String, dynamic>> lst = await db.rawQuery(sql.toString());
      if (null == lst) {
        lst = new List();
      }
      return lst;
    } catch (e) {
      print(e);
      return new List();
    }
  }

  // //车辆扫码
  // Future<List<Map<String, dynamic>>> getCarsum(Database db, String qrCode ) async {
  //   try {
  //
  //     var sql = new StringBuffer();
  //     sql.write("select ");
  //     sql.write("* ");
  //     if(qrCode.isEmpty){
  //       sql.write("from Car;");
  //     }else {
  //       String code=qrCode.substring(3);
  //       sql.write("from Car where carId =$code;");
  //     }
  //     List<Map<String, dynamic>> lst = await db.rawQuery(sql.toString());
  //     if(null == lst){
  //       lst = new List();
  //     }
  //     return lst;
  //   } catch (e) {
  //     print(e);
  //     return new List();
  //   }
  // }
//车辆扫码
  Future<List<Map<String, dynamic>>> getSpecific(Database db, String id) async {
    try {
      var sql = new StringBuffer();
      sql.write("select ");
      sql.write("eid.perfQuotaName ，esc.value ，eid.unitName  ");
      sql.write(
          "from EquipmentSpecific esc left join EquipmentIndex eid on esc.equipmentIndexId=eid.id where equipmentSpecificId  =$id;");
      List<Map<String, dynamic>> lst = await db.rawQuery(sql.toString());
      if (null == lst) {
        lst = new List();
      }
      return lst;
    } catch (e) {
      print(e);
      return new List();
    }
  }

  //灭火药剂列表
  Future<List<Map<String, dynamic>>> getAgent(Database db, String warId) async {
    try {
      var sql = new StringBuffer();
      sql.write("select ");
      sql.write("* ");
      sql.write(
          "from Equipment where stockDetailWarehouseStructureId in ($warId) and categoryCode like '4%'");
      print(sql.toString());
      List<Map<String, dynamic>> lst = await db.rawQuery(sql.toString());

      if (null == lst) {
        return null;
      }
      return lst;
    } catch (e) {
      print(e);
      return null;
    }
  }

  //灭火药剂列表
  Future<List<Map<String, dynamic>>> getAgentsh(Database db,
      {String Id, String stId}) async {
    try {
      String aid = Id.isNotEmpty ? Id : stId;
      String sid = Id.isNotEmpty
          ? 'equipmentSpecificEquipmentDetailId'
          : 'stockDetailId';
      var sql = new StringBuffer();
      sql.write("select ");
      sql.write("* ");
      sql.write("from Equipment where $sid = $aid ");
      print(sql.toString());
      List<Map<String, dynamic>> lst = await db.rawQuery(sql.toString());
      if (null == lst) {
        return null;
      }
      return lst;
    } catch (e) {
      print(e);
      return null;
    }
  }

  //灭火药剂列表
  Future<List<Map<String, dynamic>>> getsunhaoequipidList(
      Database db, String carId) async {
    try {
      var sql = new StringBuffer();
      sql.write("select ");
      sql.write("* ");
      sql.write("from EquipmentOnCar where carId = $carId ");
      print(sql.toString());
      List<Map<String, dynamic>> lst = await db.rawQuery(sql.toString());
      if (null == lst) {
        return null;
      }
      return lst;
    } catch (e) {
      print(e);
      return null;
    }
  }

  //灭火药剂损耗列表
  Future<List<Map<String, dynamic>>> getsunhaoAgent(
      Database db, String carId) async {
    try {
      var sql = new StringBuffer();
      sql.write("select ");
      sql.write("* ");
      sql.write(
          "from Equipment where carId = $carId , categoryCode like '4%';");
      List<Map<String, dynamic>> lst = await db.rawQuery(sql.toString());
      if (null == lst) {
        return null;
      }
      return lst;
    } catch (e) {
      print(e);
      return null;
    }
  }

  //报废数据插入
  Future<bool> getScrapPostBill(Database db, dynamic ponit, String type) async {
    try {
      StringBuffer sql = new StringBuffer();
      sql.write(" select * ");
      sql.write(" from scrapPostBill where type = $type;");
      var equipsum = await queryData(sql.toString());
      bool res = false;
      if (equipsum.length > 0) {
        for (var dit in equipsum) {
          if (dit['createDate'] == ponit['createDate']) {
            res = true;
          }
        }
      }
      if (res) {
        sql = new StringBuffer();
        sql.write(" update scrapPostBill ");
        sql.write(" set imageUrl = '${ponit['imageUrls']}'");
        sql.write(" where createDate = '${ponit['createDate'].toString()}';");
        LogUtil.d(sql.toString());
        excuteSql(sql.toString());
      } else {
        sql = new StringBuffer();
        sql.write("insert into scrapPostBill(");
        sql.write("scrapId,");
        sql.write("createDate,");
        sql.write("jsonString,");
        sql.write("type,");
        sql.write("reason,");
        sql.write("imageUrl");
        sql.write(")");
        sql.write("values");
        sql.write("(");
        sql.write("'" +
            (ponit.containsKey('scrapId') ? ponit['scrapId'].toString() : "") +
            "',");
        sql.write("'" +
            ((ponit.containsKey('createDate') &&
                    ponit['createDate'].toString() != 'null')
                ? ponit['createDate'].toString()
                : DateTime.now().toString().substring(0, 19)) +
            "',");
        sql.write("'" +
            (ponit.containsKey('parame') ? ponit['parame'].toString() : "") +
            "',");
        sql.write("'" + type + "',");
        sql.write("'" +
            (ponit.containsKey('reason') ? ponit['reason'].toString() : "") +
            "',");
        sql.write("'" +
            (ponit.containsKey('imageUrls')
                ? ponit['imageUrls'].toString()
                : "") +
            "'");
        sql.write(");");
        LogUtil.d(sql.toString());
        excuteSql(sql.toString());
      }
      return true;
    } catch (e) {
      print(e);
      return false;
    }
  }

  //入账
  Future<bool> getInStockEquipments(
      Database db, List<dynamic> equips, String type,
      {String shelfCellCode}) async {
    try {
      equips.forEach((ponitq) {
        Map point = ponitq;
        StringBuffer sql;
        sql = new StringBuffer();
        sql.write("insert into SunminEquipments(");
        sql.write("qrCode,");
        sql.write("amount,");
        sql.write("carId,");
        sql.write("glcarId,");
        // sql.write("scrapId,");
        sql.write("shelfCellCode,");
        sql.write("equipmentDetailId,");
        sql.write("warehouseId,");
        sql.write("reason,");
        sql.write("area,");
        sql.write("warehouseStructureId,");
        sql.write("description,");
        sql.write("stockDetailId,");
        sql.write("type,");
        sql.write("createDate,");
        sql.write("total");
        sql.write(")");
        sql.write("values");
        sql.write("(");
        sql.write("'" +
            (point.containsKey('qrCode') ? point['qrCode'].toString() : "") +
            "',");
        sql.write("'" +
            (point.containsKey('amount') ? point['amount'].toString() : "") +
            "',");
        sql.write("'" +
            (point.containsKey('carId') ? point['carId'].toString() : "") +
            "',");
        sql.write("'" +
            (point.containsKey('glcarId') ? point['glcarId'].toString() : "") +
            "',");
        // sql.write("'" +(point.containsKey('scrapId')?point['scrapId'].toString():"") + "',");
        sql.write("'${shelfCellCode == null ? '' : shelfCellCode}',");
        sql.write("'" +
            (point.containsKey('equipmentDetailId')
                ? point['equipmentDetailId'].toString()
                : "") +
            "',");
        sql.write("'0',");
        sql.write("'" +
            (point.containsKey('reason') ? point['reason'].toString() : "") +
            "',");
        sql.write("'" +
            (point.containsKey('area') ? point['area'].toString() : "") +
            "',");
        sql.write("'" +
            (point.containsKey('warehouseStructureId')
                ? point['warehouseStructureId'].toString()
                : "") +
            "',");
        sql.write("'" +
            (point.containsKey('description')
                ? point['description'].toString()
                : "") +
            "',");
        sql.write("'" +
            (point.containsKey('stockDetailId')
                ? point['stockDetailId'].toString()
                : "") +
            "',");
        sql.write("'$type',");
        sql.write("'" + DateTime.now().toString().substring(0, 19) + "',");
        sql.write("'" +
            (point.containsKey('total') ? point['total'].toString() : "") +
            "'");
        sql.write(");");
        print(sql.toString());
        db.execute(sql.toString());
        String stockID = point.containsKey('stockDetailId')
            ? point['stockDetailId'].toString()
            : "";
        String EquipID = point.containsKey('equipmentDetailId')
            ? point['equipmentDetailId'].toString()
            : "";
        String amount = point.containsKey('zamount')
            ? point['zamount'].toString()
            : point['amount'].toString();
        String wareId = point.containsKey('warehouseStructureId')
            ? point['warehouseStructureId'].toString()
            : "";
        String id = EquipID ?? stockID;
        String status = '';
        if (type == '11') {
          status = '1';
        } else if (type == '13') {
          status = '3';
        } else if (type == '15' || type == '35') {
          status = '7';
        } else if (type == '21') {
          status = '10';
        } else {
          status = '1';
        }

        if (type == '21' || type == '32') {
          getEquipmentOnCar(db, point);
        }
        if (type == '33') {
          db.execute(
              "update equipmentOnCar set amount =${point['amount'].toString()}  where stockDetailId = ${point['stockDetailId'].toString()} and carId= ${point['carId'].toString()}; ");
        } else if (type == '34') {
          //bfamout

          sql = new StringBuffer();
          sql.write(
              "update Equipment set stockDetailAmount = ${point['bfamout'].toString()}  where stockDetailId = ${point['stockDetailId'].toString()} and stockDetailWarehouseStructureId=${point['warehouseStructureId'].toString()} ;");
          print(sql.toString());
          var sqla = db.execute(sql.toString());
          LogUtil.d(sqla);
        } else if (type == '32') {
          //bfamout

          sql = new StringBuffer();
          sql.write(
              "update Equipment set stockDetailAmount = $amount  where stockDetailId = ${point['stockDetailId'].toString()} and stockDetailWarehouseStructureId=${point['warehouseStructureId'].toString()} ;");
          print(sql.toString());
          var sqla = db.execute(sql.toString());
          LogUtil.d(sqla);
        } else if (type == '31') {
          //    List lst=await getinstonkAgent(point);
          // if(lst==null){
          getmhyjinskon(db, point);
          // }else {
          //   db.execute(
          //       "update Equipment set  stockDetailAmount = amount   where equipmentSpecificEquipmentDetailId = ${point['equipmentDetailId']
          //           .toString()} and stockDetailWarehouseStructureId=${point['warehouseStructureId']
          //           .toString()} ");
          //}
        } else if (type == '24') {
          db.execute(
              "update Car set carState = '3'  where id = ${point['carId']}");
        } else if (type == '25') {
          db.execute(
              "update Car set carState = '1' where id = ${point['carId']} ");
        } else if (type == '26') {
          db.execute(
              "update Car set carState = '7' where id = ${point['carId']} ");
        } else {
          updateEquipments(db, status, id, wareId, amount, type);
        }
        if (type == '22') {
          db.execute(
              "delete from equipmentOnCar where equipmentDetailId =${point['equipmentDetailId'].toString()} ");
        }
      });

      return true;
    } catch (e) {
      print(e);
      return false;
    }
  }

  Future<List<Map<String, dynamic>>> getinstonkAgent(dynamic point) async {
    try {
      var sql = new StringBuffer();
      sql.write("select ");
      sql.write("* ");
      sql.write(
          "from Equipment where equipmentSpecificEquipmentDetailId = ${point['equipmentDetailId'].toString()} and stockDetailWarehouseStructureId=${point['warehouseStructureId'].toString()};");
      List<Map<String, dynamic>> lst =
          await dbAccess().queryData(sql.toString());
      if (null == lst) {
        return null;
      }
      if (lst.length == 0) {
        return null;
      }
      return lst;
    } catch (e) {
      print(e);
      return null;
    }
  }

  Future<bool> getmhyjinskon(Database db, dynamic plan) async {
    try {
      EquipmentScanModel model = plan["item"];
      StringBuffer sql = new StringBuffer();
      sql.write("insert into Equipment(");
      sql.write("equipmentSpecificId,");
      sql.write("equipmentSpecificEquipmentDetailId,");
      sql.write("equipmentSpecificQrCode,");
      sql.write("equipmentSpecificSingle,");
      sql.write("equipmentSpecificCode,");
      sql.write("equipmentDetailName,");
      sql.write("equipmentDetailPerfQuotaStr,");
      sql.write("warehouseStructureName,");
      sql.write("description,");
      sql.write("equipmentId,");
      sql.write("equipmentPrefQuota,");
      sql.write("stockDetailAmount,");
      sql.write("stockDetailWarehouseStructureId,");
      sql.write("stockDetailWarehouseId,");
      sql.write("stockDetailStatus,");
      sql.write("unitId,");
      sql.write("categoryCode,");
      sql.write("stockDetailId,");
      sql.write("unitName");
      sql.write(")");
      sql.write("values");
      sql.write("(");
      sql.write("' ',");
      sql.write("'" +
          (plan.containsKey('equipmentDetailId')
              ? plan['equipmentDetailId'].toString()
              : "") +
          "',");
      sql.write("'" +
          (plan.containsKey('qrCode') ? plan['qrCode'].toString() : "") +
          "',");
      sql.write("' ',");
      sql.write("' ',");
      sql.write("'" + model.equipName + "',");
      sql.write("' ',");
      sql.write("' ',");
      sql.write("'" +
          (plan.containsKey('description')
              ? plan['description'].toString()
              : "") +
          "',");
      sql.write("'" +
          (plan.containsKey('equipmentId')
              ? plan['equipmentId'].toString()
              : "") +
          "',");
      sql.write("' ',");
      sql.write("'" +
          (plan.containsKey('amount') ? plan['amount'].toString() : "") +
          "',");
      sql.write("'" +
          (plan.containsKey('warehouseStructureId')
              ? plan['warehouseStructureId'].toString()
              : "") +
          "',");
      sql.write("'" +
          (plan.containsKey('warehouseId')
              ? plan['warehouseId'].toString()
              : "") +
          "',");
      sql.write("'1 ',");
      sql.write("' ',");
      sql.write("'" + "4000000" + "',");
      sql.write("'" +
          (plan.containsKey('stockDetailId')
              ? plan['stockDetailId'].toString()
              : "") +
          "',");
      sql.write("'" + model.unit + "'");
      sql.write(")");
      print(sql.toString());
      await db.execute(sql.toString());
      return true;
    } catch (e) {
      print(e);
      return e;
    }
  }

//保存数据
  Future<bool> getEquipmentOnCar(Database db, dynamic point) async {
    try {
      StringBuffer sql;
      sql = new StringBuffer();
      sql.write("insert into equipmentOnCar(");
      // sql.write("cid,");
      sql.write("id,");
      sql.write("createDate,");
      sql.write("carId,");
      sql.write("equipmentDetailId,");
      sql.write("stockDetailId,");
      sql.write("amount,");
      sql.write("type,");
      sql.write("equipmentSpecificId");
      sql.write(")");
      sql.write("values");
      sql.write("(");
      //sql.write("'" +(point.containsKey('cid')?point['cid'].toString():"") + "',");
      sql.write(
          "'" + (point.containsKey('id') ? point['id'].toString() : "") + "',");
      sql.write("'" + DateTime.now().toString().substring(0, 19) + "',");
      sql.write("'" +
          (point.containsKey('carId') ? point['carId'].toString() : "") +
          "',");
      sql.write("'" +
          (point.containsKey('equipmentDetailId')
              ? point['equipmentDetailId'].toString()
              : "") +
          "',");
      sql.write("'" +
          (point.containsKey('stockDetailId')
              ? point['stockDetailId'].toString()
              : "") +
          "',");
      sql.write("'" +
          (point.containsKey('amount') ? point['amount'].toString() : "") +
          "',");
      sql.write("'" +
          (point.containsKey('type') ? point['type'].toString() : "") +
          "',");
      sql.write("'" +
          (point.containsKey('equipmentSpecificId')
              ? point['equipmentSpecificId'].toString()
              : "") +
          "'");
      sql.write(")");
      print(sql.toString());
      await db.execute(sql.toString());
      return true;
    } catch (e) {
      print(e);
      return false;
    }
  }

//保存数据
  Future<bool> getInStockCar(Database db, dynamic point, String type) async {
    try {
      StringBuffer sql;
      sql = new StringBuffer();
      sql.write("insert into SunminCar(");
      sql.write("shelfCellCode,");
      sql.write("carId,");
      sql.write("warehouseId,");
      sql.write("createDate,");
      sql.write("area,");
      sql.write("type");
      sql.write(")");
      sql.write("values");
      sql.write("(");
      sql.write("'" +
          (point.containsKey('shelfCellCode')
              ? point['shelfCellCode'].toString()
              : "") +
          "',");
      sql.write("'" +
          (point.containsKey('carId') ? point['carId'].toString() : "") +
          "',");
      sql.write("'0',");
      sql.write("'" + DateTime.now().toString().substring(0, 19) + "',");
      sql.write("'" +
          (point.containsKey('area') ? point['area'].toString() : "") +
          "',");
      sql.write("'" + type + "'");
      sql.write(")");
      print(sql.toString());
      await db.execute(sql.toString());
      return true;
    } catch (e) {
      print(e);
      return false;
    }
  }

//修改装备数据
  Future<bool> updateEquipments(Database db, String stater, String eqid,
      String warehouseStructureId, String amount, String type) async {
    try {
      if (type == '11') {
        await db.execute(
            "update Equipment set stockDetailStatus = $stater, stockDetailAmount = $amount , stockDetailWarehouseStructureId = $warehouseStructureId   where equipmentSpecificEquipmentDetailId = $eqid  ");
      }
      //   else
      //     if(type=='32'){
      //  var res =await db.execute(
      //       "update Equipment set  stockDetailAmount = $amount   where equipmentSpecificEquipmentDetailId = ${eqid.toString()} and stockDetailWarehouseStructureId=${warehouseStructureId.toString()}  ");
      //  LogUtil.d(res);
      // }
      else if (type == '21' ||
          type == '22' ||
          type == '12' ||
          type == '13' ||
          type == '14' ||
          type == '15') {
        await db.execute(
            "update Equipment set stockDetailStatus = $stater  where equipmentSpecificEquipmentDetailId = $eqid ");
      }
      //   else if(type=='12'||type=='13'||type=='14'||type=='15'){
      //   await db.execute(
      //       "update Equipment set stockDetailStatus = $stater  where equipmentSpecificEquipmentDetailId = $eqid ");
      // }
      // else if(type=='34'){
      //   await db.execute(
      //       "update Equipment set stockDetailStatus = $stater  where equipmentSpecificEquipmentDetailId = $id ");
      // }
      // return true;
    } catch (e) {
      print(e);
      return false;
    }
  }
}
