package com.joe.print.mvp.print;

import android.content.Context;
import android.graphics.Bitmap;
import android.text.TextUtils;
import android.widget.LinearLayout;
import com.gingersoft.gsa.cloud.common.constans.AppConstans;
import com.gingersoft.gsa.cloud.common.constans.ExpandConstant;
import com.gingersoft.gsa.cloud.common.core.delivery.OrderDetails;
import com.gingersoft.gsa.cloud.common.core.member.MemberInfo;
import com.gingersoft.gsa.cloud.common.core.restaurant.utils.RestaurantExpandInfoUtils;
import com.gingersoft.gsa.cloud.common.core.table.TableBean;
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.billItem.BillItem;
import com.gingersoft.gsa.cloud.order.cart.ShoppingCart;
import com.gingersoft.gsa.cloud.order.commodity.OrderDetail;
import com.gingersoft.gsa.cloud.order.order.DoshokuOrder;
import com.gingersoft.gsa.cloud.print.bean.PrintBillContent;
import com.gingersoft.gsa.cloud.print.bean.base.PrintBillItem;
import com.joe.print.mvp.model.bean.BillingBean;
import com.joe.print.mvp.model.bean.HtmlLable;
import com.joe.print.mvp.print.common.HtmlContract;

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

import static com.joe.print.mvp.print.common.HtmlContract.LABLE_COLUMN;
import static com.joe.print.mvp.print.common.HtmlContract.LABLE_DIV;
import static com.joe.print.mvp.print.common.HtmlContract.LABLE_P;
import static com.joe.print.mvp.print.common.HtmlContract.LABLE_QRCODE;

/**
 * 結賬單  已改新版
 */
public class PrintBill extends PrinterRoot<PrintBillContent> {


    private PrintBillContent mPrintBillContent;

    @Override
    protected void setPrintContent(PrintBillContent printContent) {
        this.mPrintBillContent = printContent;
    }

    @Override
    public Map<String, List<Bitmap>> getPrintBitmap(Context mContext, PrinterDeviceBean deviceBean) {
        Map<String, List<Bitmap>> bitmapMaps = new HashMap<>();
        List<Bitmap> bitmaps = new ArrayList<>();
        bitmaps.add(getBitmap(mContext, deviceBean));
        bitmapMaps.put("", bitmaps);
        return bitmapMaps;
    }

    @Override
    public String[] getPrintDatas(Context mContext, PrinterDeviceBean deviceBean) {

        if (mPrintBillContent == null) {
            return new String[]{"<html><body></body></html>"};
        }

        String stringBuilder = "<html><body>" +
                getHtmlContent(deviceBean) +
                "</body></html>";

        int printCount = getPrintCount(mContext);
        String[] pritContent = new String[printCount];
        for (int i = 0; i < printCount; i++) {
            pritContent[i] = stringBuilder;
        }
        return pritContent;

//        DoshokuOrder doshokuOrder = DoshokuOrder.getInstance();
//        ShoppingCart shoppingCart = doshokuOrder.getShoppingCart();
//
//        List<OrderDetail> foodList = shoppingCart.getOrderCommodityList();
//        TableBean.DataBean tableBean = doshokuOrder.getOpenTableInfo();
//
//        StringBuilder payInfo = new StringBuilder();
//        for (PayMethod payMethod : doshokuOrder.getBillMoney()) {
//            payInfo.append(payMethod.getPayName() + " ").append(payMethod.getPayMoney());
//        }
//
//        StringBuilder memberIntegerInfo = new StringBuilder();
//        OrderDetails.DataBean data = getOrderMemberInfo();
//        if (data.getAddPoints() != 0 || data.getOldPoints() != 0 || data.getAddPoints() != 0) {
//            memberIntegerInfo.append(getPLable("本次積分：" + data.getAddPoints(), HTML_PRINT_GRAVITY_LEFT))
//                    .append(getPLable("結餘積分：" + data.getNowPoints(), HTML_PRINT_GRAVITY_LEFT))
//                    .append(getPLable("上次積分：" + data.getOldPoints(), HTML_PRINT_GRAVITY_LEFT));
//            //名稱中間替換為*號
//            if (data.getMEMBER_NAME() != null && data.getMEMBER_NAME().length() > 0) {
//                memberIntegerInfo.append(getPLable("會員名稱：" + getReplaceAfter(data.getMEMBER_NAME()), HTML_PRINT_GRAVITY_LEFT));
//            }
//            if (data.getPHONE() != null && data.getPHONE().length() > 0) {
//                memberIntegerInfo.append(getPLable("會員電話：" + getReplaceAfter(data.getPHONE()), HTML_PRINT_GRAVITY_LEFT));
//            }
//        }
//
//        String stringBuilder = "<html><body>" +
//                getHtmlPrintHeadInfo() +
//                getHtmlPrintHeadOrderInfo(tableBean) +
//                generateHtmlFoodInfo(foodList) +
//                getHtmlBillInfo() +
//                getWholeLine() +
//                getPLable(payInfo.toString(), HTML_PRINT_GRAVITY_LEFT) +
//                getWholeLine() +
//                getPLable(memberIntegerInfo.toString(), HTML_PRINT_GRAVITY_LEFT);
//
//        String integralQrCode = doshokuOrder.getIntegralQrcode();
//        if (!TextUtils.isEmpty(integralQrCode) && (boolean) RestaurantExpandInfoUtils.getValue(ExpandConstant.ToPrintQRCode, false)) {
//            stringBuilder += getPLable("請掃描二維碼", HTML_PRINT_GRAVITY_CENTER) +
//                             getHtmlQrCode(doshokuOrder.getIntegralQrcode()) +
//                             getPLable("《追加積分到個人賬戶》", HTML_PRINT_GRAVITY_CENTER);
//        }
//        stringBuilder += "</body></html>";
//        String[] pritContent = new String[1];
//        pritContent[0] = stringBuilder;
//        return pritContent;
    }

    private String getHtmlContent(PrinterDeviceBean deviceBean) {

        List<HtmlLable> htmlLables = new ArrayList<>();

        /**
         * 頭部
         */
        htmlLables.add(new HtmlLable(LABLE_DIV, mPrintBillContent.getBrand(),
                new HtmlLable.Attributes(HtmlContract.ATTRIBUTES_ALIGN, HtmlContract.value_align_center, HtmlContract.value_type_string),
                new HtmlLable.Attributes(HtmlContract.ATTRIBUTES_FONT_SIZE, "28")));
        htmlLables.add(new HtmlLable(LABLE_DIV, mPrintBillContent.getResturantName(),
                new HtmlLable.Attributes(HtmlContract.ATTRIBUTES_ALIGN, HtmlContract.value_align_center, HtmlContract.value_type_string),
                new HtmlLable.Attributes(HtmlContract.ATTRIBUTES_FONT_SIZE, "28")));
        htmlLables.add(new HtmlLable(LABLE_P, HtmlContract.dividing_line));
        /**
         * 訂單
         */
        String orderNum = "單號：";
        if (TextUtil.isNotEmptyOrNullOrUndefined(DoshokuOrder.getInstance().getOrderNo())) {
            orderNum = "單號：" + DoshokuOrder.getInstance().getOrderNo();
        }
        htmlLables.addAll(getRowInformation(new HtmlLable[]{new HtmlLable(LABLE_COLUMN, "餐檯：" + mPrintBillContent.getTableName())}, 24));
        htmlLables.addAll(getRowInformation(new HtmlLable[]{new HtmlLable(LABLE_COLUMN, "人數：" + mPrintBillContent.getPerson())}, 24));
        htmlLables.addAll(getRowInformation(new HtmlLable[]{new HtmlLable(LABLE_COLUMN, orderNum)}, 24));
        htmlLables.addAll(getRowInformation(new HtmlLable[]{new HtmlLable(LABLE_COLUMN, "日期：" + TimeUtils.parseTimeRepeat(mPrintBillContent.getCreateTime(), TimeUtils.DEFAULT_DATE_FORMAT))}, 24));
        htmlLables.add(new HtmlLable(LABLE_P, HtmlContract.dividing_line));
        /**
         * 食品
         */
        if (mPrintBillContent.getFoodItemList() != null && mPrintBillContent.getFoodItemList().size() > 0) {
            htmlLables.addAll(getBBPosFoodLineString(mPrintBillContent.getFoodItemList(), deviceBean));
            htmlLables.add(new HtmlLable(LABLE_P, HtmlContract.dividing_line));
        }
        /**
         * 合計、賬單項、總金額、支付方式
         */
        //合計
        htmlLables.addAll(getRowInformation(new HtmlLable[]{
                new HtmlLable(LABLE_COLUMN, "合計:"),
                new HtmlLable(LABLE_COLUMN, AppConstans.CARSH_STR + mPrintBillContent.getWholeAmount(), new HtmlLable.Attributes(HtmlContract.ATTRIBUTES_OFFSET, HtmlContract.value_offset_last))}, 28));

        List<PrintBillItem> billItemList = mPrintBillContent.getBillItemList();
        if (billItemList.size() > 0) {
            for (PrintBillItem billItem : billItemList) {
                htmlLables.addAll(getRowInformation(new HtmlLable[]{
                        new HtmlLable(LABLE_COLUMN, billItem.getBillName()),
                        new HtmlLable(LABLE_COLUMN, billItem.getBillAmount(), new HtmlLable.Attributes(HtmlContract.ATTRIBUTES_OFFSET, HtmlContract.value_offset_last))}, 28));
            }
            htmlLables.add(new HtmlLable(LABLE_P, HtmlContract.dividing_line));
        }
        //總金額
        htmlLables.addAll(getRowInformation(new HtmlLable[]{
                new HtmlLable(LABLE_COLUMN, "總金額:"),
                new HtmlLable(LABLE_COLUMN, AppConstans.CARSH_STR + mPrintBillContent.getTotalAmount(), new HtmlLable.Attributes(HtmlContract.ATTRIBUTES_OFFSET, HtmlContract.value_offset_last))}, 35));

        htmlLables.add(new HtmlLable(LABLE_P, HtmlContract.dividing_line));
        //支付方式
        List<PrintBillItem> payMethodItemList = mPrintBillContent.getPayMethodItemList();
        if (payMethodItemList.size() > 0) {
            for (PrintBillItem billItem : payMethodItemList) {
                htmlLables.addAll(getRowInformation(new HtmlLable[]{
                        new HtmlLable(LABLE_COLUMN, billItem.getBillName()),
                        new HtmlLable(LABLE_COLUMN, billItem.getBillAmount(), new HtmlLable.Attributes(HtmlContract.ATTRIBUTES_OFFSET, HtmlContract.value_offset_last))}, 28));
            }
            htmlLables.add(new HtmlLable(LABLE_P, HtmlContract.dividing_line));
        }

        /**
         * 會員積分
         */
        if (mPrintBillContent.getAddPoints() != 0 || mPrintBillContent.getOldPoints() != 0 || mPrintBillContent.getNowPoints() != 0) {
            List<String> items = new ArrayList<>();
            items.add("本次積分: " + mPrintBillContent.getAddPoints());
            items.add("上次積分: " + mPrintBillContent.getOldPoints());
            items.add("結餘積分: " + mPrintBillContent.getNowPoints());
            items.add("會員名稱: " + mPrintBillContent.getMemberName());
            items.add("會員電話: " + mPrintBillContent.getPhone());
            for (String item : items) {
                htmlLables.addAll(getRowInformation(new HtmlLable[]{new HtmlLable(LABLE_COLUMN, item)}, 24));
            }
        }
        //qrcode
        if ((boolean) RestaurantExpandInfoUtils.getValue(ExpandConstant.ToPrintQRCode, false) == true &&
                !TextUtils.isEmpty(mPrintBillContent.getIntegralQrCode())) {
            htmlLables.add(new HtmlLable(LABLE_DIV, mPrintBillContent.getIntegralHead(),
                    new HtmlLable.Attributes(HtmlContract.ATTRIBUTES_ALIGN, HtmlContract.value_align_center, HtmlContract.value_type_string),
                    new HtmlLable.Attributes(HtmlContract.ATTRIBUTES_FONT_SIZE, "24")));
            htmlLables.add(new HtmlLable(LABLE_QRCODE, mPrintBillContent.getIntegralQrCode(),
                    new HtmlLable.Attributes(HtmlContract.ATTRIBUTES_SCALE, HtmlContract.value_scale_1, HtmlContract.value_type_string)));
            htmlLables.add(new HtmlLable(LABLE_DIV, mPrintBillContent.getIntegralFoot(),
                    new HtmlLable.Attributes(HtmlContract.ATTRIBUTES_ALIGN, HtmlContract.value_align_center, HtmlContract.value_type_string),
                    new HtmlLable.Attributes(HtmlContract.ATTRIBUTES_FONT_SIZE, "24")));
        }
        /**
         * 底部
         */
        htmlLables.add(new HtmlLable(LABLE_DIV, mPrintBillContent.getPoliteLanguage(),
                new HtmlLable.Attributes(HtmlContract.ATTRIBUTES_ALIGN, HtmlContract.value_align_center, HtmlContract.value_type_string),
                new HtmlLable.Attributes(HtmlContract.ATTRIBUTES_FONT_SIZE, "24")));

        htmlLables.add(new HtmlLable(LABLE_DIV, TimeUtils.getCurrentTimeInString(TimeUtils.DEFAULT_DATE_FORMAT),
                new HtmlLable.Attributes(HtmlContract.ATTRIBUTES_ALIGN, HtmlContract.value_align_center, HtmlContract.value_type_string),
                new HtmlLable.Attributes(HtmlContract.ATTRIBUTES_FONT_SIZE, "24")));

        return getHtmlLables(htmlLables.toArray(new HtmlLable[htmlLables.size()]));
    }

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

    private Bitmap getBitmap(Context mContext, PrinterDeviceBean deviceBean) {

        DoshokuOrder doshokuOrder = DoshokuOrder.getInstance();
        ShoppingCart shoppingCart = doshokuOrder.getShoppingCart();


        List<OrderDetail> foodList = shoppingCart.getOrderCommodityList();
        TableBean.DataBean tableBean = doshokuOrder.getOpenTableInfo();

        LinearLayout layout = new LinearLayout(mContext);
        layout.setOrientation(LinearLayout.VERTICAL);

        //訂單頭
        layout.addView(getHeader(mContext));
        layout.addView(getLine(mContext));

        //訂單信息
        String tableName = "餐檯：" + tableBean.getTableName();
        String peopleNum = "人數：" + doshokuOrder.getOpenTableInfo().getPerson();
        String orderNum = "單號：";
        if (TextUtil.isNotEmptyOrNullOrUndefined(doshokuOrder.getOrderNo())) {
            orderNum = "單號：" + doshokuOrder.getOrderNo();
        }
        String createTime = "日期：" + TimeUtils.parseTimeRepeat(tableBean.getCreateTime(), TimeUtils.DEFAULT_DATE_FORMAT);
        layout.addView(getDiningTableOrderInfo(mContext, tableName, peopleNum, orderNum, createTime));
        layout.addView(getLine(mContext));

        //食品信息
        layout.addView(getDiningFoodList(mContext, foodList, deviceBean, 1, true));
        layout.addView(getHalfLine(mContext));

        //訂單金額信息
        List<BillingBean> billingBeans = new ArrayList<>();
        //添加合計項
        billingBeans.add(new BillingBean("合計", shoppingCart.getWholeAmount()));
        //添加其他金額項
        if (shoppingCart.getBillItemList().size() > 0) {
            for (BillItem item : shoppingCart.getBillItemList()) {
                billingBeans.add(new BillingBean(item.getName(), item.getMoney()));
            }
        }
        layout.addView(getDiningBillInfo(mContext, billingBeans));
        layout.addView(getHalfLine(mContext));

//        BigDecimal totalAmount = new BigDecimal(0);
//        for (OrderDetail OrderDetail : MyOrderManage.getInstance().getOrderFoodList()) {
//            totalAmount = MoneyUtil.sum(totalAmount, OrderDetail.getPrice());
//        }
        layout.addView(getAmountText(mContext, "總金額：" + shoppingCart.getTotalAmount()));
        layout.addView(getLine(mContext));
        layout.addView(getDiningBillPayMethod(mContext, doshokuOrder.getBillMoney()));
        layout.addView(getLine(mContext));

        layout.addView(getTableMealMemberIntegerView(mContext, getOrderMemberInfo(), doshokuOrder.getIntegralQrcode()));

        return zoomBitmap(deviceBean, viewToBitmap(mContext, layout));
    }


    private OrderDetails.DataBean getOrderMemberInfo() {
        OrderDetails.DataBean dataBean = new OrderDetails.DataBean();
        MemberInfo memberInfo = DoshokuOrder.getInstance().getMemberInfo();
        if (memberInfo != null) {
            dataBean.setMEMBER_NAME(memberInfo.getMemberName());
            dataBean.setPHONE(memberInfo.getPhone());
            dataBean.setNowPoints(DoshokuOrder.getInstance().getNowPoints());
            dataBean.setAddPoints(DoshokuOrder.getInstance().getAddPoints());
            dataBean.setOldPoints(DoshokuOrder.getInstance().getOldPoints());
        }
        return dataBean;
    }

}
