package com.mq.mylibrary.db.user;

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 com.mq.mylibrary.tool.MD5Tool;

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

/**
 * 创建人 mQ
 * 创建时间 2019/8/7 0007 16:21
 * 文件名称 UserDao
 * 说明:  用户信息操作类
 **/
public class UserDao extends BaseDao<UserEntity> {

    private UserDao() {
    }

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

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

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


    public boolean insertByJSONArray(SQLiteDatabase db, JSONArray array) {
        if (array == null || array.length() == 0) {
            LogTool.i("初始化: 没有用户信息");
            return true;
        }
        //根据json批量添加用户信息
        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) {
        UserEntity entity = new UserEntity();
        //根据json添加一条用户信息
        entity.setUser_code(object.optString("usercode"));
        entity.setReal_name(object.optString("username"));
        entity.setPassword(object.optString("password"));
        return insert(db, entity);
    }

    /**
     * 登录验证
     */
    public UserEntity checkUser(SQLiteDatabase db, String userCode, String password) {
        //单MD5加密密码
        String p1 = MD5Tool.MD5(password);
        LogTool.i("单MD5加密密码: "+p1);
        Cursor c1 = db.rawQuery("SELECT * FROM " + getTableName() +
                " WHERE user_code = '" + userCode + "'" +
                " AND password = '" + p1 + "'", null);
        if (c1.getCount() > 0) {
            return (UserEntity) HappySQL.cursor2VO(c1, UserEntity.class);
        }

        //双MD5加密密码
        String p2 = MD5Tool.MD5(MD5Tool.MD5(password));
        LogTool.i("双MD5加密密码: "+p1);
        Cursor c2 = db.rawQuery("SELECT * FROM " + getTableName() +
                " WHERE user_code = '" + userCode + "'" +
                " AND password = '" + p2 + "'", null);
        if (c2.getCount() > 0) {
            return (UserEntity) HappySQL.cursor2VO(c2, UserEntity.class);
        }
        return null;
    }
}
