package com.gingersoft.gsa.cloud.database.utils;

import android.content.Context;
import android.database.Cursor;
import android.text.TextUtils;
import android.util.Log;

import com.gingersoft.gsa.cloud.database.DaoManager;
import com.gingersoft.gsa.cloud.database.bean.ComboItem;
import com.gingersoft.gsa.cloud.database.greendao.ComboItemDao;

import org.greenrobot.greendao.query.QueryBuilder;

import java.util.ArrayList;
import java.util.List;

/**
 * 作者：ELEGANT_BIN
 * 版本：1.6.0
 * 创建日期：2020-01-02
 * 修订历史：2020-01-02
 * 描述：
 */
public class ComboItemDaoUtils {

    private static final String TAG = ComboItemDaoUtils.class.getSimpleName();
    private DaoManager mManager;
    private Context mContext;

    public ComboItemDaoUtils(Context context) {
        mManager = DaoManager.getInstance();
        mManager.init(context);
        this.mContext = context;
    }

    /**
     * 清除緩存
     */
    public void detachAll() {
        ComboItemDao comboItemDao = DaoManager.getInstance().getDaoSession().getComboItemDao();
        comboItemDao.detachAll();
    }


    /**
     * 完成Food记录的插入，如果表未创建，先创建Food表
     *
     * @param comboItem
     * @return
     */
    public boolean insertCombo(ComboItem comboItem) {
        boolean flag = false;
        flag = mManager.getDaoSession().getComboItemDao().insert(comboItem) == -1 ? false : true;
        Log.i(TAG, "insert ComboItem :" + flag + "-->" + comboItem.toString());
        return flag;
    }

    /**
     * 插入多条数据，在子线程操作
     *
     * @param foodList
     * @return
     */
    public boolean insertMultCombo(final List<ComboItem> foodList) {
        boolean flag = false;
        try {
            mManager.getDaoSession().runInTx(new Runnable() {
                @Override
                public void run() {
                    for (ComboItem Food : foodList) {
                        mManager.getDaoSession().insertOrReplace(Food);
                    }
                }
            });
            flag = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return flag;
    }

    /**
     * 修改一条数据
     *
     * @param ComboItem
     * @return
     */
    public boolean updateCombo(ComboItem ComboItem) {
        boolean flag = false;
        try {
            mManager.getDaoSession().update(ComboItem);
            flag = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return flag;
    }

    /**
     * 删除单条记录
     *
     * @param food
     * @return
     */
    public boolean deleteCombo(ComboItem food) {
        boolean flag = false;
        try {
            //按照id删除
            mManager.getDaoSession().delete(food);
            flag = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return flag;
    }

    /**
     * 删除所有记录
     *
     * @return
     */
    public boolean deleteAll() {
        boolean flag = false;
        try {
            //按照id删除
            mManager.getDaoSession().deleteAll(ComboItem.class);
            flag = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return flag;
    }

    /**
     * 查询所有记录
     *
     * @return
     */
    public List<ComboItem> queryAllCombo() {
        return mManager.getDaoSession().loadAll(ComboItem.class);
    }

    /**
     * 根据主键id查询记录
     *
     * @param key
     * @return
     */
    public ComboItem queryComboById(long key) {
        return mManager.getDaoSession().load(ComboItem.class, key);
    }

    /**
     * 使用native sql进行查询操作
     */
    public List<ComboItem> queryComboByNativeSql(String sql, String[] conditions) {
        return mManager.getDaoSession().queryRaw(ComboItem.class, sql, conditions);
    }

    public ArrayList<ComboItem> queryComboItemsByFidQueryBuilder(long fid) {

        ArrayList<ComboItem> comboItems = new ArrayList<>();

//        String sql = "SELECT c.*,f.FOOD_NAME,f.FOOD_NAME1,f.FOOD_NAME2,f.PRICE,f.AUTO_MOD FROM COMBO_ITEM c join FOOD f on c.FID=f.FID and f.INVISIBLE=0 join FOOD_COMBO r on r.COM_ID=c.COM_ID ";
        String sql = "SELECT c.*,f.FOOD_NAME,f.FOOD_NAME1,f.FOOD_NAME2,f.PRICE,f.AUTO_MOD,f.PRINT_SETING,f.ABLE_DISCOUNT,SELECT_QTY,DEF_MODIFIER,INVISIBLE,POINTS_ADD,POINTS_RATIO,POINTS_REDEEM,SERVICE_CHARGE,c.DIFF_AMT FROM COMBO_ITEM c join FOOD f on c.FID=f.FID and f.INVISIBLE!=1 join FOOD_COMBO r on r.COM_ID=c.COM_ID and r.DELETES!=1";

        if (fid > 0) {
            sql = sql + "  where r.FID='" + fid + "'";
        }
        Cursor c = mManager.getDaoSession().getFoodDao().getDatabase().rawQuery(sql, null);
        while (c.moveToNext()) {
            ComboItem order = new ComboItem();
            order.setFid(c.getLong(c.getColumnIndex("FID")));
            order.setComId(c.getLong(c.getColumnIndex("COM_ID")));
//            order.setPrice(c.getDouble(c.getColumnIndex("PRICE")));
            order.setPrice(c.getDouble(c.getColumnIndex("DIFF_AMT")));
            order.setSeqNo(c.getLong(c.getColumnIndex("SEQ_NO")));
            order.setQty(c.getLong(c.getColumnIndex("QTY")));
            order.setName(c.getString(c.getColumnIndex("FOOD_NAME")));
            order.setName1(c.getString(c.getColumnIndex("FOOD_NAME1")));
            order.setName2(c.getString(c.getColumnIndex("FOOD_NAME2")));
            order.setVisible(c.getLong(c.getColumnIndex("VISIBLE")));
            order.setAutoMode(c.getInt(c.getColumnIndex("AUTO_MOD")));
            order.setSelectQty(c.getInt(c.getColumnIndex("SELECT_QTY")));
            order.setInvisible(c.getLong(c.getColumnIndex("INVISIBLE")));
            order.setPrintSeting(c.getString(c.getColumnIndex("PRINT_SETING")));
            order.setAblediscount(c.getLong(c.getColumnIndex("ABLE_DISCOUNT")));
            order.setPointsAdd(c.getDouble(c.getColumnIndex("POINTS_ADD")));
            order.setPointsRatio(c.getLong(c.getColumnIndex("POINTS_RATIO")));
            order.setPointsRedeem(c.getDouble(c.getColumnIndex("POINTS_REDEEM")));
            order.setServiceCharge(c.getInt(c.getColumnIndex("SERVICE_CHARGE")));
            String defmodifier = c.getString(c.getColumnIndex("DEF_MODIFIER"));
            if (!TextUtils.isEmpty(defmodifier) && !", ".equals(defmodifier)) {
                order.setDefmodifier(defmodifier);
            }
//            if (order.isVisible()) {
            comboItems.add(order);
//            }
        }
        c.close();
        return comboItems;
    }

    /**
     * 使用queryBuilder进行查询食品
     *
     * @return
     */
    public List<ComboItem> queryComboFoodsByQueryBuilder(long fid) {
//        ComboItem comboItem = queryComboByQueryBuilder(fid);
//        List<ComboItem> foodCombos = null;
//        if (comboItem != null) {
//            foodCombos = queryCombosByComIdQueryBuilder(comboItem.getComId());
//        }
        List<ComboItem> list = new ArrayList<>();
//        FoodDaoUtils foodDao = new FoodDaoUtils(mContext);
//        if (foodCombos != null) {
//            for (int i = 0; i < foodCombos.size(); i++) {
//                Food food = foodDao.queryFoodByFidQueryBuilder(foodCombos.get(i).getFid());
//                if (food != null) {
//                    list.add(comboItem.addFoodInfo(food, foodCombos.get(i)));
//                }
//            }
//        }
        return list;
    }

    public List<ComboItem> queryCombosFoodsByQueryBuilder(long fid) {
        QueryBuilder<ComboItem> queryBuilder = mManager.getDaoSession().queryBuilder(ComboItem.class);

//         queryBuilder.where(queryBuilder.join()).orderAsc(FoodDao.Properties.SeqNo).list();

//        List<ComboItem> ComboItem = queryCombosByQueryBuilder(fid);
//        List<ComboItem> foodCombos = null;
//        if (ComboItem != null && ComboItem.size() != 0) {
//            foodCombos = queryCombosByComIdQueryBuilder(ComboItem.get(0).getComId());
//        }
        List<ComboItem> list = new ArrayList<>();
//        FoodDaoUtils foodDao = new FoodDaoUtils(mContext);
//        if (foodCombos != null) {
//            for (int i = 0; i < foodCombos.size(); i++) {
//                Food food = foodDao.queryFoodByFidQueryBuilder(foodCombos.get(i).getFid());
//                if(food != null) {
//                    list.add(ComboItem.addFoodInfo(food, foodCombos.get(i)));
//                }
//            }
//        }
        return list;
    }

    /**
     * 使用queryBuilder进行查询食品
     *
     * @return
     */
    public ComboItem queryComboByQueryBuilder(long fid) {
        QueryBuilder<ComboItem> queryBuilder = mManager.getDaoSession().queryBuilder(ComboItem.class);
        return queryBuilder.where(ComboItemDao.Properties.Fid.eq(fid)).build().unique();
    }

    /**
     * 使用queryBuilder进行查询食品
     *
     * @return
     */
    public List<ComboItem> queryCombosByQueryBuilder(long fid) {
        QueryBuilder<ComboItem> queryBuilder = mManager.getDaoSession().queryBuilder(ComboItem.class);
        return queryBuilder.where(ComboItemDao.Properties.Fid.eq(fid)).build().list();
    }

    /**
     * 使用queryBuilder进行查询食品
     *
     * @return
     */
    public List<ComboItem> queryCombosByComIdQueryBuilder(int comId) {
        QueryBuilder<ComboItem> queryBuilder = mManager.getDaoSession().queryBuilder(ComboItem.class);
        return queryBuilder.where(ComboItemDao.Properties.ComId.eq(comId)).list();
    }
}
