package cn.net.caoyao.cpzshandset.db.dal.yunCar;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import cn.net.caoyao.cpzshandset.db.YunCarDBHelper;

public class YunCarLingLiaoDal {
	private YunCarDBHelper helper;

	public YunCarLingLiaoDal(Context context) {
		helper = new YunCarDBHelper(context);
	}
	/**
	 * 
	 * @param car_no
	 * @param lingliaoDate
	 * @param picture_url
	 */
	public void insertLingLiaoInfo(String car_no, String lingliaoDate, String picture_url
			) {
		SQLiteDatabase db = helper.getWritableDatabase();
		String sql = "insert into "
				+ YunCarDBHelper.tb_LingLiao_info
				+ " (car_no,lingliaodate,picture_url,submit_status) values (?,?,?,?)";

		db.execSQL(sql, new Object[] { car_no, lingliaoDate, picture_url, 0});
		db.close();
	}
	/**
	 * 查询领料表中的有多少个最多一条
	 * @return 
	 */
	public boolean queryLingLiaoInfoCount() {
		SQLiteDatabase db = helper.getWritableDatabase();
		int count = 0;
		String sql = "select * from " + YunCarDBHelper.tb_LingLiao_info;
		Cursor c = db.rawQuery(sql, null);
		while (c.moveToNext()) {
			count = c.getColumnCount();
		}
		c.close();
		db.close();
		return count > 0 ? false : true;
	}
	
	/**
	 * 查询领料表中所有数据
	 * @return
	 */
	public List<Map<String, String>> queryLingLiaoInfo() {
		SQLiteDatabase db = helper.getWritableDatabase();
		List<Map<String, String>> list = new ArrayList<Map<String, String>>();

		String sql = "select * from " + YunCarDBHelper.tb_LingLiao_info;
		Cursor c = db.rawQuery(sql, null);
		Map<String, String> map = null;
		while (c.moveToNext()) {
			map = new HashMap<String, String>();

			String car_no = c.getString(c.getColumnIndex("car_no"));

			String lingLiaodate = c.getString(c
					.getColumnIndex("lingliaodate"));

			String picture_url = c.getString(c.getColumnIndex("picture_url"));
		
			String error_code = c.getString(c.getColumnIndex("error_code"));
			
			String submit_status = c.getString(c.getColumnIndex("submit_status"));
			
			map.put("car_no", car_no);
			map.put("lingLiaodate", lingLiaodate);
			map.put("picture_url", picture_url);
		
			map.put("error_code", error_code);
		
			map.put("submit_status", submit_status);
			
			list.add(map);
		}
		c.close();
		db.close();
		return list;
	}
	
	/**
	 * 删除
	 */
	
	public void deleteAllLingLiaoInfo() {
		SQLiteDatabase db = helper.getWritableDatabase();
		String sql = "delete from " + YunCarDBHelper.tb_LingLiao_info;
		db.execSQL(sql);
		db.close();
	}
	
	/**
	 * 根据id更新失败的errCode
	 * 
	 * @return
	 */
	public void upErrCode(int status,String errCode, String car_no) {

		SQLiteDatabase db = helper.getReadableDatabase();
		String sql = "update lingliaoInfo set submit_status="+status+",error_code  ='" + errCode
				+ "'where car_no ='" + car_no + "'";

		// errLog(sql);
		if (db.isOpen()) {
			db.execSQL(sql);
			db.close();
		}

	}

}
