package com.joe.print.mvp.print;

import android.content.Context;
import android.graphics.Bitmap;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.gingersoft.gsa.cloud.common.core.table.TableBean;
import com.gingersoft.gsa.cloud.common.core.user.UserContext;
import com.gingersoft.gsa.cloud.common.utils.other.TextUtil;
import com.gingersoft.gsa.cloud.common.utils.time.TimeUtils;
import com.gingersoft.gsa.cloud.database.bean.PrinterDeviceBean;
import com.gingersoft.gsa.cloud.order.commodity.OrderDetail;
import com.gingersoft.gsa.cloud.order.order.DoshokuOrder;
import com.joe.print.R;
import com.joe.print.mvp.ui.adapter.KitChenPrintFoodAdapter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * 廚房單打印
 */
public class PrintKitchen extends PrinterRoot {

    @Override
    public Map<String, List<Bitmap>> getPrintBitmap(Context mContext, PrinterDeviceBean deviceBean) {
        Map<String, List<Bitmap>> bitmapMaps = new HashMap<>();
        List<OrderDetail> orderDetails = DoshokuOrder.getInstance().getNewFoodList();
        if (orderDetails != null) {
//            for (int i = 0; i < orderDetails.size(); i++) {
//                orderDetails.get(i).setPrintseting(printLocation[i % 2]);
//            }
            //廚房單，可能會有多個IP打印
            //獲得ip打印列表，
            //再將食品數據根據打印位置分組。
            //打印一組之後，關閉連接，切換第二台打印機ip，如此循環
            //打印完成之後，返回所有打印結果。
            Map<String, List<OrderDetail>> foodMaps = new HashMap<>();
            String emptyPrintLocation = "";//部分食品沒有打印位置時設置為此key，比如這是第一個食品，沒有打印位置時
            int lastEmptyPrintLocationIndex = 0;//上一次遍歷到第一個食品時都沒有打印位置時，開始的食品位置
            //將所有食品進行遍歷，分組
            for (int i = 0; i < orderDetails.size(); i++) {
                OrderDetail food = orderDetails.get(i);
                if (TextUtil.isEmptyOrNullOrUndefined(food.getPrintseting())) {
                    //如果沒有打印位置，向上尋找
                    if (i == 0) {
                        food.setPrintseting(emptyPrintLocation);
                        addToMap(foodMaps, food);
                    } else {
                        for (int j = i - 1; j >= lastEmptyPrintLocationIndex; j--) {
                            //一直遍歷，直到找到有打印位置的食品
                            // 如果所有食品都沒有打印位置的情況，為了避免多次遍歷
                            // 如果本次遍歷到第一個食品，都沒有打印位置，記錄下這一次開始遍歷的下標，下一次遍歷到這個位置就停止
                            if (!TextUtil.isEmptyOrNullOrUndefined(orderDetails.get(j).getPrintseting())) {
                                //一直遍歷，直到找到有打印位置的食品
                                //判斷是否帶*號
                                if (orderDetails.get(j).getPrintseting().contains("*")) {
                                    //帶*號，則需要取得通過下標加去掉*號的標識來取得map中的集合，將i食品裝進去，這樣就能打印在一張紙上
                                    //如果沒取得集合，則通過打印位置去map取得集合，將j食品從map中移除，將這個j食品的和i食品裝一起
                                    // 生成新的key。為當前下標+"標識符"+去掉*的打印位置，不帶*的key取得的食品集合才能打印在一張紙上。
                                    String newKey = j + DELIMITER + orderDetails.get(j).getPrintseting().replaceAll("\\*", "");
                                    //通過newKey取得map中的集合
                                    List<OrderDetail> newKeyfoods = foodMaps.get(newKey);
                                    if (newKeyfoods != null) {
                                        newKeyfoods.add(food);
                                    } else {
                                        List<OrderDetail> printsetingFoods = foodMaps.get(orderDetails.get(j).getPrintseting());
                                        if (printsetingFoods != null) {//理論上不會為空
                                            printsetingFoods.remove(printsetingFoods.lastIndexOf(orderDetails.get(j)));
                                            //移除掉之後，put到newkey中
                                            List<OrderDetail> newFoods = new ArrayList<>();
                                            newFoods.add(orderDetails.get(j));
                                            newFoods.add(food);
                                            foodMaps.put(newKey, newFoods);
                                        }
                                    }
                                    break;
                                } else {
                                    //沒有*號，不需要做多餘的操作
                                    food.setPrintseting(orderDetails.get(j).getPrintseting());
                                    addToMap(foodMaps, food);
                                }
                            } else if (j == lastEmptyPrintLocationIndex) {
                                //從i到0的打印位置都沒有，記錄下i，下次只遍歷到i就停下來
                                lastEmptyPrintLocationIndex = i;
                                //如果找到最初的那個食品，也沒有打印位置，設置打印位置為"null"
                                food.setPrintseting(emptyPrintLocation);
                                addToMap(foodMaps, food);
                            }
                        }
                    }
                } else {
                    //有打印位置，
                    //已經保存過這個位置的，
                    addToMap(foodMaps, food);
                }
            }
            //通過打印位置生成多張用於打印的bitmap
            for (Map.Entry<String, List<OrderDetail>> entry : foodMaps.entrySet()) {
                String key = entry.getKey();
                List<Bitmap> bitmaps = new ArrayList<>();
                if (key.contains("*")) {
                    //如果帶*號，這個集合就需要切紙，每個食品都需要單獨在一張廚房單上
                    for (OrderDetail orderDetail : entry.getValue()) {
                        List<OrderDetail> orders = new ArrayList<>();//這裡new集合是因為下面的方法需要的參數是list集合
                        orders.add(orderDetail);
                        Bitmap bitmap = getKitChenPrintBitmap(mContext, orders, deviceBean);
                        bitmaps.add(bitmap);
                    }
                } else {
                    Bitmap bitmap = getKitChenPrintBitmap(mContext, entry.getValue(), deviceBean);
                    //不帶*號，所有同樣廚房位置的食品都在一張紙上
                    bitmaps.add(bitmap);
                }
                bitmapMaps.put(key, bitmaps);
            }
        }
        return bitmapMaps;
    }

    @Override
    public String[] getPrintDatas(Context mContext, PrinterDeviceBean deviceBean) {
        return null;
    }

    @Override
    public int getPrintCount(Context context) {
        return 1;
    }

    private void addToMap(Map<String, List<OrderDetail>> foodMaps, OrderDetail food) {
        if (foodMaps.get(food.getPrintseting()) != null) {
            Objects.requireNonNull(foodMaps.get(food.getPrintseting())).add(food);
        } else {
            List<OrderDetail> newFoods = new ArrayList<>();
            newFoods.add(food);
            foodMaps.put(food.getPrintseting(), newFoods);
        }
    }

    /**
     * 獲取"廚房單"圖片
     *
     * @param context
     * @return
     */
    private Bitmap getKitChenPrintBitmap(Context context, List<OrderDetail> foodList, PrinterDeviceBean printerDeviceBean) {
        if (foodList == null || foodList.size() <= 0) {
            return null;
        }

        DoshokuOrder doshokuOrder = DoshokuOrder.getInstance();

        View view = LinearLayout.inflate(context, R.layout.print_kitchen, null);
        TextView tvTableNumber = view.findViewById(R.id.tv_kitchen_print_table_number);
        TextView tvOrderNumber = view.findViewById(R.id.tv_order_num);
        TextView tvOpeningTime = view.findViewById(R.id.tv_opening_time);
        TextView tvOrderTime = view.findViewById(R.id.tv_order_time);
        TextView tvKitChenLocation = view.findViewById(R.id.tv_kitchen_location);
        TextView tvPeople = view.findViewById(R.id.tv_people);
        TextView tvOperator = view.findViewById(R.id.tv_operator);
        RecyclerView rvFood = view.findViewById(R.id.rv_kitchen_food);
        TextView tvTableNumber2 = view.findViewById(R.id.tv_kitchen_print_table_number2);
        if (foodList.size() > 0 && foodList.get(0) != null) {
            KitChenPrintFoodAdapter foodAdapter = new KitChenPrintFoodAdapter(foodList);
            rvFood.setLayoutManager(new LinearLayoutManager(context));
            rvFood.setAdapter(foodAdapter);
            //廚房位置
            if (!TextUtil.isEmptyOrNullOrUndefined(foodList.get(0).getPrintseting())) {
                tvKitChenLocation.setText(foodList.get(0).getPrintseting());//.replace("*", "")
                tvKitChenLocation.setVisibility(View.VISIBLE);
            } else {
                tvKitChenLocation.setVisibility(View.GONE);
            }
        }
        TableBean.DataBean dataBean = doshokuOrder.getOpenTableInfo();
        if (dataBean != null) {
            //台號
            tvTableNumber.setText(dataBean.getTableName() + "");
            tvTableNumber2.setText(dataBean.getTableName() + "");
            //人數
            tvPeople.setText(dataBean.getPerson() + "");
            //訂單號
            tvOrderNumber.setText("" + dataBean.getOrderId());
            //開台時間
            tvOpeningTime.setText(TimeUtils.parseTimeRepeat(dataBean.getCreateTime(), TimeUtils.DEFAULT_DATE_FORMAT));
        }
        //落單時間，為當前時間
        tvOrderTime.setText(TimeUtils.getCurrentTimeInString(TimeUtils.DEFAULT_DATE_FORMAT));
        //操作人員
        tvOperator.setText(UserContext.newInstance().getMemberName());
        return viewToZoomBitmap(context, view, printerDeviceBean);
    }


}
