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.bean.Modifier;
import com.gingersoft.gsa.cloud.database.greendao.FoodDao;
import com.gingersoft.gsa.cloud.database.greendao.ModifierDao;

import org.greenrobot.greendao.query.Join;
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 ModifierDaoUtils {

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

    public static final int modifierMode_All = 700;//本行及以下四行为明细制作 方式
    public static final int modifierMode_Add = 701;
    public static final int modifierMode_Msg = 702;
    public static final int modifierMode_Add_2 = 703; //二级下的mod_taste=1
    public static final int modifierMode_Msg_2 = 704; //二级下的mod_msg=1
    public static final int modifierMode_Child = 705; //isPatent=1內的子項


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

    /**
     * 清除緩存
     */
    public void detachAll() {
        ModifierDao modifierDao = DaoManager.getInstance().getDaoSession().getModifierDao();
        modifierDao.detachAll();
    }

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

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

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

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

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

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

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


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


    /**
     * 使用queryBuilder进行查询食品
     *
     * @return
     */
    public Modifier queryModifierByQueryBuilder(long mid) {
        QueryBuilder<Modifier> queryBuilder = mManager.getDaoSession().queryBuilder(Modifier.class);
        return queryBuilder.where(ModifierDao.Properties.Mid.eq(mid)).build().unique();
    }

    /**
     * 使用queryBuilder进行查询食品
     *
     * @param mid
     * @return
     */
    public List<Modifier> queryModifierByMidIdQueryBuilder(long mid) {
        QueryBuilder<Modifier> queryBuilder = mManager.getDaoSession().queryBuilder(Modifier.class);
        return queryBuilder.where(ModifierDao.Properties.Mid.eq(mid)).list();
    }

    /**
     * 使用queryBuilder进行查询食品
     *
     * @return
     */
    public List<Modifier> queryModifierByModMsgAndVisibleQueryBuilder() {

        ArrayList<Modifier> fms = new ArrayList<>();

//        QueryBuilder<Modifier> queryBuilder = mManager.getDaoSession().queryBuilder(Modifier.class);
//        String parentSql = "SELECT * FROM MODIFIER WHERE MOD_MSG=1 and VISIBLE=0 and IS_PARENT=1";
        String parentSql = "SELECT * FROM MODIFIER WHERE MOD_MSG=1  and IS_PARENT=1";
        List<Modifier> parentModifiers = query_modifier_Child_new(parentSql, 0);

//        String childSql = "SELECT * FROM MODIFIER WHERE MOD_MSG=1 and VISIBLE=0 and IS_PARENT=0";
        String childSql = "SELECT * FROM MODIFIER WHERE MOD_MSG=1  and IS_PARENT=0";
        List<Modifier> childModifiers = query_modifier_Child_new(childSql, 0);

        fms.addAll(parentModifiers);
        fms.addAll(childModifiers);

        return fms;
    }

    /**
     * 使用queryBuilder进行查询食品
     *
     * @return
     */
    public List<Modifier> queryModifierByModModTasteVisibleQueryBuilder() {

        ArrayList<Modifier> fms = new ArrayList<>();

//        QueryBuilder<Modifier> queryBuilder = mManager.getDaoSession().queryBuilder(Modifier.class);

//        List<Modifier> parentModifiers = queryBuilder.where(queryBuilder.and(
//                ModifierDao.Properties.ModTaste.eq(mod_taste),
//                ModifierDao.Properties.Visible.eq(visible),
//                ModifierDao.Properties.IsParent.eq(1))).orderAsc(ModifierDao.Properties.SeqNo).list();
//
//        List<Modifier> childModifiers = queryBuilder.where(queryBuilder.and(
//                ModifierDao.Properties.ModTaste.eq(mod_taste),
//                ModifierDao.Properties.Visible.eq(visible),
//                ModifierDao.Properties.IsParent.eq(0))).orderAsc(ModifierDao.Properties.SeqNo).list();

//        String parentSql = "SELECT * FROM MODIFIER WHERE MOD_TASTE=1 and VISIBLE=0 and IS_PARENT=1";
        String parentSql = "SELECT * FROM MODIFIER WHERE MOD_TASTE=1 and IS_PARENT=1";
        List<Modifier> parentModifiers = query_modifier_Child_new(parentSql, 0);

//        String childSql = "SELECT * FROM MODIFIER WHERE MOD_TASTE=1 and VISIBLE=0 and IS_PARENT=0";
        String childSql = "SELECT * FROM MODIFIER WHERE MOD_TASTE=1 and IS_PARENT=0";
        List<Modifier> childModifiers = query_modifier_Child_new(childSql, 0);

        fms.addAll(parentModifiers);
        fms.addAll(childModifiers);

        return fms;
    }

    /**
     * 使用queryBuilder进行查询食品
     *
     * @return
     */
    public List<Modifier> queryModifierByModModCommVisibleQueryBuilder() {

        ArrayList<Modifier> fms = new ArrayList<>();

//        QueryBuilder<Modifier> queryBuilder = mManager.getDaoSession().queryBuilder(Modifier.class);

//        List<Modifier> parentModifiers = queryBuilder.where(queryBuilder.and(
//                ModifierDao.Properties.ModTaste.eq(mod_taste),
//                ModifierDao.Properties.Visible.eq(visible),
//                ModifierDao.Properties.IsParent.eq(1))).orderAsc(ModifierDao.Properties.SeqNo).list();
//
//        List<Modifier> childModifiers = queryBuilder.where(queryBuilder.and(
//                ModifierDao.Properties.ModTaste.eq(mod_taste),
//                ModifierDao.Properties.Visible.eq(visible),
//                ModifierDao.Properties.IsParent.eq(0))).orderAsc(ModifierDao.Properties.SeqNo).list();

//        String parentSql = "SELECT * FROM MODIFIER WHERE MOD_COMM=1 and VISIBLE=0 and IS_PARENT=1";
        String parentSql = "SELECT * FROM MODIFIER WHERE MOD_COMM=1 and IS_PARENT=1";
        List<Modifier> parentModifiers = query_modifier_Child_new(parentSql, 0);

//        String childSql = "SELECT * FROM MODIFIER WHERE MOD_COMM=1 and VISIBLE=0 and IS_PARENT=0";
        String childSql = "SELECT * FROM MODIFIER WHERE MOD_COMM=1 and IS_PARENT=0";
        List<Modifier> childModifiers = query_modifier_Child_new(childSql, 0);

        fms.addAll(parentModifiers);
        fms.addAll(childModifiers);

        return fms;
    }

    /**
     * 使用queryBuilder进行查询食品
     *
     * @param topid
     * @return
     */
    public List<Modifier> queryModifierByTopidAndVisibleQueryBuilder(long topid) {

        ArrayList<Modifier> fms = new ArrayList<>();

//        QueryBuilder<Modifier> queryBuilder = mManager.getDaoSession().queryBuilder(Modifier.class);

//        List<Modifier> parentModifiers = queryBuilder.where(queryBuilder.and(
//                ModifierDao.Properties.TopId.eq(topid),
//                ModifierDao.Properties.Visible.eq(0),
//                ModifierDao.Properties.IsParent.eq(1))).orderAsc(ModifierDao.Properties.SeqNo).list();
//
//        List<Modifier> childModifiers = queryBuilder.where(queryBuilder.and(
//                ModifierDao.Properties.TopId.eq(topid),
//                ModifierDao.Properties.Visible.eq(0),
//                ModifierDao.Properties.IsParent.eq(0))).orderAsc(ModifierDao.Properties.SeqNo).list();

        String parentSql = "SELECT * FROM MODIFIER WHERE TOP_ID='" + topid + "'  and VISIBLE=0 and IS_PARENT=1";
        List<Modifier> parentModifiers = query_modifier_Child_new(parentSql, 0);

        String childSql = "SELECT * FROM MODIFIER WHERE TOP_ID='" + topid + "'  and VISIBLE=0 and IS_PARENT=0";
        List<Modifier> childModifiers = query_modifier_Child_new(childSql, 0);

        fms.addAll(parentModifiers);
        fms.addAll(childModifiers);

        return fms;
    }


    public List<Modifier> queryModifiersByFid(long fid, int mode) {

//      String sql =  " SELECT MODIFIER.mid,MODIFIER_NAME,MODIFIER_NAME1,MODIFIER_NAME2,TOP_ID,PRICE,MOD_COMM,MOD_TASTE,MOD_MSG,VISIBLE,MULTIPLE,IS_PARENT" +
//                " FROM MODIFIER join FOOD_MODIFIER on MODIFIER.MID=FOOD_MODIFIER.MID  where MODIFIER.VISIBLE=0 and  FOOD_MODIFIER.FID='" + fid + "' order by FOOD_MODIFIER.seq,MODIFIER.SEQ_NO";

        String sql = " SELECT MODIFIER.MID,MODIFIER_NAME,MODIFIER_NAME1,MODIFIER_NAME2,TOP_ID,PRICE,MOD_COMM,MOD_TASTE,MOD_MSG,INVISIBLE,VISIBLE,MULTIPLE,IS_PARENT,MAX_QTY,MIN_QTY,ABLE_DIS_COUNT,PRINT_SET" +
                " FROM MODIFIER join FOOD_MODIFIER fm on MODIFIER.MID=FOOD_MODIFIER.MID  where MODIFIER.INVISIBLE!=1 and  FOOD_MODIFIER.FID='" + fid + "' order by FOOD_MODIFIER.SEQ_NO,MODIFIER.SEQ_NO";

        List<Modifier> mfs_child = new ArrayList<>();

        List<Modifier> mfs_child1 = new ArrayList<>();

        String sqlstr = " TOP_ID IN (SELECT MID  FROM FOOD_MODIFIER where  FID='" + fid + "')";

//        List<Modifier> fms1 = query_modifier_Child_new(sql, fid);

        switch (mode) {
            case modifierMode_All:
                sqlstr = " SELECT m.MID,MODIFIER_NAME,MODIFIER_NAME1,MODIFIER_NAME2,TOP_ID,PRICE,MOD_COMM,MOD_TASTE,MOD_MSG,INVISIBLE,VISIBLE,MULTIPLE,IS_PARENT,DEFMODIFIER,MAX_QTY,MIN_QTY,ABLE_DIS_COUNT,PRINT_SET,KT_SETTING" +
                        " FROM MODIFIER m join FOOD_MODIFIER fm on m.TOP_ID=fm.MID  where m.INVISIBLE!=1 and  m.IS_PARENT=1  and fm.FID='" + fid + "' order by fm.SEQ_NO,m.SEQ_NO";

                mfs_child1 = query_modifier_Child_new(sqlstr, fid);

                List<Modifier> mfs_child2 = new ArrayList<>();

                sqlstr = " SELECT m.MID,MODIFIER_NAME,MODIFIER_NAME1,MODIFIER_NAME2,TOP_ID,PRICE,MOD_COMM,MOD_TASTE,MOD_MSG,INVISIBLE,VISIBLE,MULTIPLE,IS_PARENT,DEFMODIFIER,MAX_QTY,MIN_QTY,ABLE_DIS_COUNT,PRINT_SET,KT_SETTING" +
                        " FROM MODIFIER m join FOOD_MODIFIER fm on m.TOP_ID=fm.MID  where m.INVISIBLE!=1 and  m.IS_PARENT=0  and fm.FID='" + fid + "' order by fm.SEQ_NO,m.SEQ_NO";

                mfs_child2 = query_modifier_Child_new(sqlstr, fid);
                mfs_child1.addAll(mfs_child2);
                mfs_child2.clear();
                break;
//            case modifierMode_Add:
//                sqlstr = " mod_taste=1 and visible=0";
//                mfs_child1 = query_modifier_Child(sqlstr, fid);
//                break;
//            case modifierMode_Add_2:
//                sqlstr = "  topid='" + fid + "' and visible=0";
//                mfs_child1 = query_modifier_Child(sqlstr, fid);
//                break;
//            case modifierMode_Msg:
//                sqlstr = "  mod_msg=1 and visible=0";
//                mfs_child1 = query_modifier_Child(sqlstr, fid);
//                break;
//            case modifierMode_Msg_2:
//                sqlstr = "  topid='" + fid + "' and visible=0";
//                mfs_child1 = query_modifier_Child(sqlstr, fid);
//                break;
            case modifierMode_Child:
                sqlstr = "  topid='" + fid + "' and visible=0";
//                mfs_child1 = query_modifier_Child(sqlstr, fid);
                break;
        }

//        mfs_child.addAll(fms1);
        mfs_child.addAll(mfs_child1);
        return mfs_child;
    }

    private List<Modifier> query_modifier_Child_new(String sql, long fid) {
        ArrayList<Modifier> modifiers = new ArrayList<>();
        Cursor c = mManager.getDaoSession().getModifierDao().getDatabase().rawQuery(sql, null);
        while (c.moveToNext()) {
            Modifier modifier = new Modifier();
            modifier.setFid(fid);
            modifier.setMid(c.getLong(c.getColumnIndex("MID")));
            modifier.setPrice(c.getDouble(c.getColumnIndex("PRICE")));
            modifier.setIsParent(c.getLong(c.getColumnIndex("IS_PARENT")));
//            order.setSeqNo(c.getLong(c.getColumnIndex("SEQ_NO")));
            modifier.setModifierName(c.getString(c.getColumnIndex("MODIFIER_NAME")));
            modifier.setModifierName1(c.getString(c.getColumnIndex("MODIFIER_NAME1")));
            modifier.setModifierName2(c.getString(c.getColumnIndex("MODIFIER_NAME2")));
//            order.setVisible(c.getInt(c.getColumnIndex("VISIBLE")));
            modifier.setTopId(c.getLong(c.getColumnIndex("TOP_ID")));
            modifier.setModComm(c.getLong(c.getColumnIndex("MOD_COMM")));
            modifier.setModMsg(c.getLong(c.getColumnIndex("MOD_MSG")));
            modifier.setModTaste(c.getLong(c.getColumnIndex("MOD_TASTE")));
            modifier.setMultiple(c.getDouble(c.getColumnIndex("MULTIPLE")));
            modifier.setAbleDisCount(c.getLong(c.getColumnIndex("ABLE_DIS_COUNT")));
            modifier.setInvisible(c.getLong(c.getColumnIndex("INVISIBLE")));
            modifier.setPrintSet(c.getString(c.getColumnIndex("PRINT_SET")));
            modifier.setKtSetting(c.getString(c.getColumnIndex("KT_SETTING")));
            if (fid != 0) {
                //非公共細項
                modifier.setSelectQty(c.getInt(c.getColumnIndex("MAX_QTY")));
                String defmodifier = c.getString(c.getColumnIndex("DEFMODIFIER"));
                if (!TextUtils.isEmpty(defmodifier) && !", ".equals(defmodifier)) {
                    modifier.setDefmodifier(defmodifier);
                }
            }
//            if (order.isVisible()) {
            modifiers.add(modifier);
//            }
        }
        c.close();
        return modifiers;
    }
}
