package com.joe.print.mvp.print;

import android.content.Context;
import android.graphics.Bitmap;
import android.view.LayoutInflater;
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.base.application.GsaCloudApplication;
import com.gingersoft.gsa.cloud.base.common.bean.mealManage.MyOrderManage;
import com.gingersoft.gsa.cloud.base.utils.MoneyUtil;
import com.gingersoft.gsa.cloud.base.utils.other.TextUtil;
import com.gingersoft.gsa.cloud.base.utils.time.TimeUtils;
import com.joe.print.mvp.ui.adapter.OtherOrderAdapter;
import com.gingersoft.gsa.cloud.print.bean.OrderDetails;
import com.joe.print.R;

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

public class PrintOtherOrder extends PrinterRoot {


    @Override
    public Map<String, List<Bitmap>> getPrintBitmap(Context mContext) {
        OrderDetails.DataBean dataBean = MyOrderManage.getDataBean();
        if (dataBean != null) {
            Map<String, List<Bitmap>> bitmapMaps = new HashMap<>();
            //廚房單，可能會有多個IP打印
            //獲得ip打印列表，
            //再將食品數據根據打印位置分組。
            //打印一組之後，關閉連接，切換第二台打印機ip，如此循環
            //打印完成之後，返回所有打印結果。
            Map<String, List<OrderDetails.DataBean.PRODUCTNAMEBean>> foodMaps = new HashMap<>();
            String emptyPrintLocation = "";//部分食品沒有打印位置時設置為此key，比如這是第一個食品，沒有打印位置時
            int lastEmptyPrintLocationIndex = 0;//上一次遍歷到第一個食品時都沒有打印位置時，開始的食品位置
            //獲取這個訂單的一級食品
            if (dataBean.getPRODUCT_NAME() != null) {
                for (int i = 0; i < dataBean.getPRODUCT_NAME().size(); i++) {
                    OrderDetails.DataBean.PRODUCTNAMEBean food = dataBean.getPRODUCT_NAME().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(dataBean.getPRODUCT_NAME().get(j).getPrintseting())) {
                                    //一直遍歷，直到找到有打印位置的食品
                                    //判斷是否帶*號
                                    if (Objects.requireNonNull(dataBean.getPRODUCT_NAME().get(j).getPrintseting()).contains("*")) {
                                        //帶*號，則需要取得通過下標加去掉*號的標識來取得map中的集合，將i食品裝進去，這樣就能打印在一張紙上
                                        //如果沒取得集合，則通過打印位置去map取得集合，將j食品從map中移除，將這個j食品的和i食品裝一起
                                        // 生成新的key。為當前下標+"標識符"+去掉*的打印位置，不帶*的key取得的食品集合才能打印在一張紙上。
                                        String newKey = j + DELIMITER + dataBean.getPRODUCT_NAME().get(j).getPrintseting().replaceAll("\\*", "");
                                        //通過newKey取得map中的集合
                                        List<OrderDetails.DataBean.PRODUCTNAMEBean> newKeyfoods = foodMaps.get(newKey);
                                        if (newKeyfoods != null) {
                                            newKeyfoods.add(food);
                                        } else {
                                            List<OrderDetails.DataBean.PRODUCTNAMEBean> printsetingFoods = foodMaps.get(dataBean.getPRODUCT_NAME().get(j).getPrintseting());
                                            if (printsetingFoods != null) {//理論上不會為空
                                                printsetingFoods.remove(printsetingFoods.lastIndexOf(dataBean.getPRODUCT_NAME().get(j)));
                                                //移除掉之後，put到newkey中
                                                List<OrderDetails.DataBean.PRODUCTNAMEBean> newFoods = new ArrayList<>();
                                                newFoods.add(dataBean.getPRODUCT_NAME().get(j));
                                                newFoods.add(food);
                                                foodMaps.put(newKey, newFoods);
                                            }
                                        }
                                        break;
                                    } else {
                                        //沒有*號，不需要做多餘的操作
                                        food.setPrintseting(dataBean.getPRODUCT_NAME().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<OrderDetails.DataBean.PRODUCTNAMEBean>> entry : foodMaps.entrySet()) {
                String key = entry.getKey();
                List<Bitmap> bitmaps = new ArrayList<>();
                if (key.contains("*")) {
                    //如果帶*號，這個集合就需要切紙，每個食品都需要單獨在一張廚房單上
                    for (OrderDetails.DataBean.PRODUCTNAMEBean orderDetail : entry.getValue()) {
                        List<OrderDetails.DataBean.PRODUCTNAMEBean> orders = new ArrayList<>();//這裡new集合是因為下面的方法需要的參數是list集合
                        orders.add(orderDetail);
                        //獲取廚房單圖片
                        Bitmap bitmap = getOrderKitchenBitmap(mContext, orders, dataBean);
                        bitmaps.add(bitmap);
                    }
                } else {
                    //獲取廚房單圖片
                    Bitmap bitmap = getOrderKitchenBitmap(mContext, entry.getValue(), dataBean);
                    //不帶*號，所有同樣廚房位置的食品都在一張紙上
                    bitmaps.add(bitmap);
                }
                bitmapMaps.put(key, bitmaps);
            }
            //如果需要打印印單，加上
            List<Bitmap> bitmaps = new ArrayList<>();
            bitmaps.add(initPrintView(mContext, dataBean));
            merge2ResultMap(bitmapMaps, "", bitmaps);
            return bitmapMaps;
        }
        return null;
    }

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

    //獲取廚房單圖片
    private Bitmap getOrderKitchenBitmap(Context context, List<OrderDetails.DataBean.PRODUCTNAMEBean> orderDetail, OrderDetails.DataBean dataBean) {
        View view = LinearLayout.inflate(context, R.layout.print_other_order_food, null);
        TextView tvOrderType = view.findViewById(R.id.tv_order_type);//訂單類型。外賣or自取
        TextView tvCreateTime = view.findViewById(R.id.tv_order_create_time);
        TextView tvOperator = view.findViewById(R.id.tv_operator_name);//操作人員
        TextView tvSendTime = view.findViewById(R.id.tv_order_send_time);
        TextView tvOrderNum = view.findViewById(R.id.tv_order_number);
        RecyclerView rvFood = view.findViewById(R.id.rv_order_food);
        if (dataBean.getOrder_type() == 2) {
            tvOrderType.setText("外賣");
        } else {
            tvOrderType.setText("自取");
        }
        //送貨時間
        if (!TextUtil.isEmptyOrNullOrUndefined(dataBean.getSEND_TIME())) {
            tvSendTime.setVisibility(View.VISIBLE);
            tvSendTime.setText("送貨時間：" + dataBean.getSEND_TIME());
        } else {
            tvSendTime.setVisibility(View.GONE);
        }
        tvOperator.setText("操作：" + GsaCloudApplication.getMemberName(context));
        //創建時間
        tvCreateTime.setText(TimeUtils.parseTimeRepeat(dataBean.getCREATE_TIME(), TimeUtils.DEFAULT_DATE_FORMAT));
        //訂單號
        tvOrderNum.setText("訂單號：" + dataBean.getORDER_NO());

        rvFood.setLayoutManager(new LinearLayoutManager(context));
        rvFood.setAdapter(new OtherOrderAdapter(context, orderDetail));

        return viewToBitmap(context, view);
    }


    private Bitmap initPrintView(Context context, OrderDetails.DataBean data) {
        View view = LayoutInflater.from(context).inflate(R.layout.print_confirm_order_view, null, false);
        // 訂單類型
        setText(view, R.id.tv_order_type, data.getOrder_type() == 2 ? "外賣" : "自取");
        // 訂單號
        setText(view, R.id.tv_order_number, "訂單號：" + data.getORDER_NO());
        //訂單創建時間
        setText(view, R.id.tv_order_create, context.getString(R.string.create_order_time) + TimeUtils.parseTimeRepeat(data.getCREATE_TIME(), TimeUtils.DEFAULT_DATE_FORMAT));
        String amountUnit = context.getString(R.string.amount_unit);
        //總金額
        setText(view, R.id.tv_total, amountUnit + MoneyUtil.sub(MoneyUtil.sub(Double.parseDouble(Objects.requireNonNull(data.getTOTAL_AMOUNT())), data.getLunchbox()), data.getDELIVERY_CHARGE()));

        //餐盒費
        setAmount(data.getLunchbox(), view.findViewById(R.id.tv_lunchbox_cost_text), view.findViewById(R.id.tv_lunchbox_cost), amountUnit);
        //配送費
        setAmount(data.getDELIVERY_CHARGE(), view.findViewById(R.id.tv_delivery_fee_text), view.findViewById(R.id.tv_delivery_fee), amountUnit);
        //折扣
        setAmount(data.getDiscount_amount(), view.findViewById(R.id.tv_discount_text), view.findViewById(R.id.tv_discount), amountUnit);
        //總金額
        setText(view, R.id.tv_total_amount, amountUnit + MoneyUtil.sub(Double.parseDouble(data.getTOTAL_AMOUNT()), data.getDiscount_amount()));
        //支付金額
        setText(view, R.id.tv_pay_amount, amountUnit + MoneyUtil.sub(Double.parseDouble(data.getTOTAL_AMOUNT()), data.getDiscount_amount()));
        //支付類型：貨到付款，在線支付
        setText(view, R.id.tv_pay_type, data.getOrderPayType() == 1 ? "貨到付款" : "在線支付");
        //收貨地址
        setText(view, R.id.tv_address, context.getString(R.string.address) + data.getAddressDetail());
        //收貨人
        setText(view, R.id.tv_receiver, "收貨人：" + data.getRECEIVER());
        //手機號
        setText(view, R.id.tv_phone, "手機號：" + data.getPHONE());
        //備註
        setText(view, R.id.tv_remark, "備註：" + data.getRemark());
        if (data.getPRODUCT_NAME() != null) {
            RecyclerView rvFoodList = view.findViewById(R.id.rv_order_print_food);
            rvFoodList.setLayoutManager(new LinearLayoutManager(context));
            rvFoodList.setAdapter(new OtherOrderAdapter(context, data.getPRODUCT_NAME()));
        }
        return viewToBitmap(context, view);
    }

    private void setAmount(Double data, TextView tvText, TextView tvAmount, String amountUnit) {
        if (data <= 0) {
            tvText.setVisibility(View.GONE);
            tvAmount.setVisibility(View.GONE);
        } else {
            tvText.setVisibility(View.VISIBLE);
            tvAmount.setVisibility(View.VISIBLE);
            tvAmount.setText(amountUnit + data.toString());
        }
    }

}
