package com.mq.mylibrary.db.sotre;

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/8 0008 11:28
 * 文件名称 StoreDao
 * 说明:  仓房货位操作类
 **/
public class StoreDao extends BaseDao<StoreEntity> {

    private StoreDao() {
    }

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

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

    @Override
    public String getTableName() {
        return "store_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++) {

                JSONObject jsonObject = array.getJSONObject(i);
                long flg = insertByJSONObject(db, jsonObject);
                if (flg == -1)
                    return false;
            }
            return true;
        } catch (JSONException e) {
            e.printStackTrace();
            return false;
        }
    }

    public long insertByJSONObject(SQLiteDatabase db, JSONObject object) {
        StoreEntity entity = new StoreEntity();
        entity.setStore_name(object.optString("cf_name"));
        entity.setStore_id(object.optString("cf_id"));
        entity.setStore_code(object.optString("cf_code"));
        entity.setPosition_name(object.optString("hw_name"));
        entity.setPosition_id(object.optString("hw_id"));
        entity.setPosition_code(object.optString("hw_code"));
        return insert(db, entity);
    }

    /**
     * 获取仓房选项
     */
    public List<StoreEntity> getStoreList(SQLiteDatabase db) {
        String sql = "SELECT  * FROM " + getTableName() + " group by store_name order by store_id";
        LogTool.i("获取仓房列表：" + sql);
        Cursor cursor = db.rawQuery(sql, null);
        return HappySQL.cursor2VOList(cursor, StoreEntity.class);
    }

    /**
     * 获取货位
     */
    public List<StoreEntity> getPositionList(SQLiteDatabase db, String houseName) {
        String sql = "SELECT * FROM " + getTableName() +
                " WHERE store_name = '" + houseName + "'" +
                " group by position_name order by position_id";
        LogTool.i("获取货位列表：" + sql);
        Cursor cursor = db.rawQuery(sql, null);
        return HappySQL.cursor2VOList(cursor, StoreEntity.class);
    }

}
