package com.mq.mylibrary.db.load_info;

import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import com.mq.mylibrary.db.BaseDao;
import com.mq.mylibrary.tool.HappySQL;
import com.mq.mylibrary.tool.LogTool;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.List;


/**
 * 创建人 mQ
 * 创建时间 2019/8/16 0016 10:30
 * 文件名称 LoadInfoDao
 * 说明:  火车卸车信息操作类
 **/
public class LoadInfoDao extends BaseDao<LoadInfoEntity> {

    private LoadInfoDao() {
    }

    private static class SingleHelper {
        private static final LoadInfoDao INSTANCE = new LoadInfoDao();
    }

    public static LoadInfoDao get() {
        return SingleHelper.INSTANCE;
    }


    @Override
    public String getTableName() {
        return "load_info";
    }


    public boolean insertByJSONArray(SQLiteDatabase db, JSONArray array) {
        if (array == null || array.length() == 0) {
            LogTool.i("初始化: 没有装车信息");
            return true;
        }
        try {
            for (int i = 0; i < array.length(); i++) {
                long flg = insertByJSONObject(db, array.getJSONObject(i));
                if (flg == -1)
                    return false;
            }
            return true;
        } catch (JSONException e) {
            e.printStackTrace();
            return false;
        }
    }

    public long insertByJSONObject(SQLiteDatabase db, JSONObject object) {
        LoadInfoEntity entity = new LoadInfoEntity();
        entity.setInbound_code(object.optString("rzdh"));
        entity.setTrain_code(object.optString("hcph"));
        entity.setCustomer(object.optString("khmc"));
        entity.setGrain_id(object.optString("lypz"));
        entity.setPlatform_name(object.optString("zt"));
        entity.setPosition_name(object.optString("hw"));
        return insert(db, entity);
    }

    /**
     * 获取入站单号 列表
     */
    public List<LoadInfoEntity> getInboundCodeList(SQLiteDatabase db) {
        Cursor cursor = db.rawQuery("SELECT * FROM " + getTableName() +
                " group by inbound_code order by inbound_code", null);
        return HappySQL.cursor2VOList(cursor, LoadInfoEntity.class);
    }

    /**
     * 根据入站单号 获取火车皮号 列表
     */
    public List<LoadInfoEntity> getTrainCodeList(SQLiteDatabase db, String inboundCode) {
        Cursor cursor = db.rawQuery("SELECT * FROM " + getTableName() +
                " where inbound_code = '" + inboundCode + "'" +
                " order by train_code", null);
        return HappySQL.cursor2VOList(cursor, LoadInfoEntity.class);
    }

}
