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.gingersoft.gsa.cloud.base.utils.view.ImageUtils;
import com.gingersoft.gsa.cloud.constans.ExpandConstant;
import com.gingersoft.gsa.cloud.database.bean.ExpandInfo;
import com.gingersoft.gsa.cloud.database.utils.ExpandInfoDaoUtils;
import com.joe.print.mvp.model.bean.PrintBillBean;
import com.joe.print.mvp.ui.adapter.BillItemAdapter;
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<>();
            Bitmap bitmap = initPrintView(mContext, dataBean);
            bitmaps.add(bitmap);
            merge2ResultMap(bitmapMaps, "", bitmaps);
            return bitmapMaps;
        }
        return null;
    }

    @Override
    public int getPrintCount(Context context) {
        ExpandInfoDaoUtils expandInfoDaoUtils = new ExpandInfoDaoUtils(context);
        List<ExpandInfo> expandInfos = expandInfoDaoUtils.queryAllExpandInfo();
        int printCount = 1;
        if (expandInfos != null) {
            for (ExpandInfo expandInfo : expandInfos) {
                if (expandInfo.getSettingName().equals(ExpandConstant.DeliveryPrintCount)) {
                    printCount = expandInfo.getValueInt();
                }
            }
        }
        return printCount;
    }

    private void addCountBitmap(List<Bitmap> bitmaps, int count, Bitmap bitmap) {
        for (int i = 0; i < count; i++) {
            bitmaps.add(bitmap);
        }
    }


    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);
        TextView tvTakeCode = view.findViewById(R.id.tv_order_take_code);
        if (dataBean.getOrder_type() == 2) {
            tvOrderType.setText("外送");
        } else {
            tvOrderType.setText("自取");
        }
        if (dataBean.getTakeFoodCode() != null && !dataBean.getTakeFoodCode().equals("0")) {
            tvTakeCode.setText("取餐碼：#" + dataBean.getTakeFoodCode());
        } else {
            view.findViewById(R.id.tv_order_take_code).setVisibility(View.GONE);
        }
        //送貨時間
        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, false));
        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_brand_name, GsaCloudApplication.getBrandName(context));
        //餐廳名
        setText(view, R.id.tv_restaurant_name, GsaCloudApplication.getRestaurantName(context));
        // 訂單類型
        setText(view, R.id.tv_order_type, data.getOrder_type() == 2 ? "外送" : "自取");
        // 訂單號
        setText(view, R.id.tv_order_number, "單號：" + data.getORDER_NO());
        if (data.getTakeFoodCode() != null && !data.getTakeFoodCode().equals("0")) {
            setText(view, R.id.tv_order_take_food_code, "取餐碼：#" + data.getTakeFoodCode());
        } else {
            view.findViewById(R.id.tv_order_take_food_code).setVisibility(View.GONE);
        }
        //訂單創建時間
        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);

        RecyclerView rvBill = view.findViewById(R.id.rv_bill);
        List<PrintBillBean> billData = new ArrayList<>();
        billData.add(getBillBean("合計：", amountUnit + MoneyUtil.sub(MoneyUtil.sub(Double.parseDouble(data.getTOTAL_AMOUNT()), data.getLunchbox()),data.getDELIVERY_CHARGE())));
        if (data.getLunchbox() != 0) {
            billData.add(getBillBean("餐盒費：", amountUnit + data.getLunchbox()));
        }
        if (data.getDELIVERY_CHARGE() != 0) {
            billData.add(getBillBean("送貨費：", amountUnit + data.getDELIVERY_CHARGE()));
        }
        if (data.getCouponList() != null && data.getCouponList().size() > 0) {
            for (OrderDetails.DataBean.CouponBean coupon : data.getCouponList()) {
                billData.add(getBillBean(coupon.getCouponName() + "：", "-$" + coupon.getDiscount_amount()));
            }
        }
        //總金額減去餐盒費之後的價格
//        double amount1 = MoneyUtil.sub(Double.parseDouble(Objects.requireNonNull(data.getTOTAL_AMOUNT())), data.getLunchbox());
        //總金額減去餐盒費、減去配送費之後的價格
//        double amount2 = MoneyUtil.sub(amount1, data.getDELIVERY_CHARGE());
        //總金額減去餐盒費、減去配送費、減去折扣之後的價格
//        double amount3 = MoneyUtil.sub(amount2, data.getDiscount_amount());

//        billData.add(getBillBean("總金額：", amountUnit + data.getTOTAL_AMOUNT()));

        BillItemAdapter adapter = new BillItemAdapter(billData, context);
        rvBill.setLayoutManager(new LinearLayoutManager(context));
        rvBill.setAdapter(adapter);
        //總金額
        setText(view, R.id.tv_total, amountUnit + data.getTOTAL_AMOUNT());
        //支付金額
        setText(view, R.id.tv_pay_amount_text, "支付金額：" + amountUnit + MoneyUtil.sub(Double.parseDouble(data.getTOTAL_AMOUNT()), data.getDiscount_amount()));
        //支付類型：貨到付款，在線支付
        String payType = "";
        if (data.getPayType() == 1) {
            payType = "：積分支付";
        } else if (data.getPayType() == 2) {
            payType = "：支付寶";
        } else if (data.getPayType() == 3) {
            payType = "：财付通";
        } else if (data.getPayType() == 4) {
            payType = "：微信支付";
        } else if (data.getPayType() == 5) {
            payType = "：貨到付款";
        } else if (data.getPayType() == 6) {
            payType = "：其他支付";
        }
        if (data.getOrderPayType() == 1) {
            //貨到付款
            setText(view, R.id.tv_pay_type, "貨到付款");
        } else {
            setText(view, R.id.tv_pay_type, "在線支付" + payType);
        }
        //收貨時間
        setText(view, R.id.tv_delivery_time, data.getOrder_type() == 2 ? data.getSEND_TIME() : data.getTakeTime());
        //收貨地址
        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_bottom_time, "手機號：" + data.getPHONE());

        //備註
        if (data.getRemark() != null && !data.getRemark().isEmpty()) {
            setText(view, R.id.tv_remark, "備註：" + data.getRemark());
            view.findViewById(R.id.tv_remark).setVisibility(View.VISIBLE);
        } else {
            view.findViewById(R.id.tv_remark).setVisibility(View.GONE);
        }

        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(), true));
        }
        return viewToBitmap(context, view);
    }

    private PrintBillBean getBillBean(String title, String value) {
        return new PrintBillBean(title, value);
    }

    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());
        }
    }

}
