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 com.gingersoft.gsa.cloud.base.application.GsaCloudApplication;
import com.gingersoft.gsa.cloud.base.order.bean.OrderDetail;
import com.gingersoft.gsa.cloud.base.order.bean.mealManger.MyOrderManage;
import com.gingersoft.gsa.cloud.base.utils.MoneyUtil;
import com.gingersoft.gsa.cloud.base.utils.RestaurantExpandInfoUtils;
import com.gingersoft.gsa.cloud.base.utils.other.TextUtil;
import com.gingersoft.gsa.cloud.base.utils.time.TimeUtils;
import com.gingersoft.gsa.cloud.constans.ExpandConstant;
import com.gingersoft.gsa.cloud.database.bean.PrinterDeviceBean;
import com.gingersoft.gsa.cloud.print.bean.OrderDetails;
import com.joe.print.R;
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 java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

/**
 * 外送接單，印單   已改新版
 */
public class PrintOtherOrder extends PrinterRoot {


    @Override
    public Map<String, List<Bitmap>> getPrintBitmap(Context mContext, PrinterDeviceBean deviceBean) {
        OrderDetails.DataBean dataBean = MyOrderManage.getDataBean();
        if (dataBean != null) {
            Map<String, List<Bitmap>> bitmapMaps = new HashMap<>();
            //廚房單，可能會有多個IP打印
            //獲得ip打印列表，
            //再將食品數據根據打印位置分組。
            //打印一組之後，關閉連接，切換第二台打印機ip，如此循環
            //打印完成之後，返回所有打印結果。
            //如果需要打印印單，加上
            List<Bitmap> bitmaps = new ArrayList<>();
//            Bitmap bitmap = initPrintView(mContext, dataBean);
            Bitmap bitmap = getBitmap(mContext, dataBean, deviceBean);
//            for (int i = 0; i < getPrintCount(mContext); i++) {
            bitmaps.add(bitmap);
//            }
            merge2ResultMap(bitmapMaps, "", bitmaps);
            return bitmapMaps;
        }
        return null;
    }

    @Override
    public int getPrintCount(Context context) {
        return RestaurantExpandInfoUtils.getValue(ExpandConstant.DeliveryPrintCount,1);
    }

    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());
        //創建時間
        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 getBitmap(Context mContext, OrderDetails.DataBean data, PrinterDeviceBean deviceBean) {
        LinearLayout layout = new LinearLayout(mContext);
        layout.setOrientation(LinearLayout.VERTICAL);
        //頭部
        layout.addView(getHeader(mContext));
        //訂單信息
        layout.addView(getTakeawayOrderInfo(mContext, data));
        //食品
        layout.addView(getTextLine(mContext, "項目"));
        layout.addView(getDiningFoodList(mContext, OrderDetail.productMameBeanToOrderDetail(0, data.getPRODUCT_NAME()), deviceBean, 1, true));
        layout.addView(getLine(mContext));
        //訂單金額信息
        List<PrintBillBean> billData = new ArrayList<>();
        billData.add(getBillBean("合計：", MONETARY_UNIT + MoneyUtil.sub(MoneyUtil.sub(Double.parseDouble(data.getTOTAL_AMOUNT()), data.getLunchbox()), data.getDELIVERY_CHARGE())));
        if (data.getLunchbox() != 0) {
            billData.add(getBillBean("餐盒費：", MONETARY_UNIT + data.getLunchbox()));
        }
        if (data.getDELIVERY_CHARGE() != 0) {
            billData.add(getBillBean("送貨費：", MONETARY_UNIT + data.getDELIVERY_CHARGE()));
        }
        if (data.getCouponList() != null && data.getCouponList().size() > 0) {
            for (OrderDetails.DataBean.CouponBean coupon : data.getCouponList()) {
                billData.add(getBillBean(coupon.getCouponName() + "：", "-" + MONETARY_UNIT + coupon.getDiscount_amount()));
            }
        }
        layout.addView(getTakeawayBillInfoView(mContext, billData));
        layout.addView(getLine(mContext));
        //總金額34sp
        layout.addView(getTakeawayLargeAmount(mContext, "總金額：", MONETARY_UNIT + data.getTOTAL_AMOUNT()));
        layout.addView(getLine(mContext));
        //支付信息
        addTakeawayPayViews(mContext, layout, data.getPayMultiple(), MoneyUtil.sub(Double.parseDouble(data.getTOTAL_AMOUNT()), data.getDiscount_amount()));
        //用戶信息
        getTakeawayReceiver(mContext, data, layout);
        //尾部
        return viewToZoomBitmap(mContext, layout, deviceBean);
    }


    private Bitmap initPrintView(Context context, OrderDetails.DataBean data) {
        View view = LayoutInflater.from(context).inflate(R.layout.print_confirm_order_view, null, false);
        TextView tvOrderClosing = view.findViewById(R.id.tv_order_closing);
        TextView tvBillNumber = view.findViewById(R.id.tv_bill_number);
        //品牌名
        setText(view, R.id.tv_brand_name, GsaCloudApplication.getBrandName());
        //餐廳名
        setText(view, R.id.tv_restaurant_name, GsaCloudApplication.getRestaurantName());
        // 訂單類型
        setText(view, R.id.tv_order_type, data.getOrder_type() == 2 ? "外送" : "自取");
        // 訂單號
        setText(view, R.id.tv_order_number, "單號：" + data.getORDER_NO());
        if (data.getOrder_type() == 7) {
            //自取  顯示 取餐碼+訂單碼
            if (!TextUtil.isEmptyOrNullOrUndefined(data.getTakeFoodCode())) {
                setText(view, R.id.tv_order_take_food_code, "取餐碼：" + data.getTakeFoodCode());
            }
        } else {
            //外送  顯示訂單碼
            setText(view, R.id.tv_order_take_food_code, "訂單碼：" + data.getTakeFoodCode());
        }
        if (data.getTakeFoodCode() == null || data.getTakeFoodCode().equals("0")) {
            view.findViewById(R.id.tv_order_take_food_code).setVisibility(View.GONE);
        }

        if (data.getBillNo() == null || data.getBillNo().length() <= 0) {
            tvBillNumber.setVisibility(View.GONE);
        } else {
            tvBillNumber.setText("訂單碼：" + data.getBillNo());
        }
        //訂單創建時間
        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);
        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()));
        if (data.getOrderPayType() == 1) {
            //貨到付款
            setText(view, R.id.tv_pay_type, "貨到付款");
        } else if (data.getOrderPayType() == 0) {
            setText(view, R.id.tv_pay_type, "店內支付");
        } else if (data.getOrderPayType() == 2) {
            setText(view, R.id.tv_pay_type, "在線支付");
            //顯示支付時間
            if (data.getPayTime() != null) {
                tvOrderClosing.setText("支付時間：" + data.getPayTime());
                tvOrderClosing.setVisibility(View.VISIBLE);
            }
        }
        setText(view, R.id.tv_pay_amount_text, "支付金額：" + amountUnit + MoneyUtil.sub(Double.parseDouble(data.getTOTAL_AMOUNT()), data.getDiscount_amount()));
        //收貨時間
        setText(view, R.id.tv_delivery_time, data.getOrder_type() == 2 ? data.getSEND_TIME() : data.getTakeTime());
        if (data.getOrder_type() != 2) {
            //自取，隱藏地址和收貨人
            view.findViewById(R.id.tv_address).setVisibility(View.GONE);
            view.findViewById(R.id.tv_receiver).setVisibility(View.GONE);
        } else {
            //收貨地址
            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());
        }
    }

}
