package com.joe.print.mvp.print;

import android.content.Context;
import android.graphics.Bitmap;
import android.view.View;

import com.gingersoft.gsa.cloud.common.core.restaurant.ResturantInfoManager;
import com.gingersoft.gsa.cloud.common.core.user.UserContext;
import com.gingersoft.gsa.cloud.common.core.pay.PayMethod;
import com.gingersoft.gsa.cloud.common.utils.MoneyUtil;
import com.gingersoft.gsa.cloud.common.utils.PrintTransitUtils;
import com.gingersoft.gsa.cloud.common.utils.time.TimeUtils;
import com.gingersoft.gsa.cloud.common.core.settlement.SettlementReport;
import com.gingersoft.gsa.cloud.common.constans.AppConstans;
import com.gingersoft.gsa.cloud.database.bean.PrinterDeviceBean;
import com.gingersoft.gsa.cloud.common.core.print.bean.PrintCleanMachineContent;
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.ATTRIBUTES_ALIGN;
import static com.joe.print.mvp.print.common.HtmlContract.ATTRIBUTES_FONT_SIZE;
import static com.joe.print.mvp.print.common.HtmlContract.ATTRIBUTES_OFFSET;
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.value_align_center;
import static com.joe.print.mvp.print.common.HtmlContract.value_offset_last;
import static com.joe.print.mvp.print.common.HtmlContract.value_offset_percentage30;
import static com.joe.print.mvp.print.common.HtmlContract.value_offset_percentage35;
import static com.joe.print.mvp.print.common.HtmlContract.value_offset_percentage60;
import static com.joe.print.mvp.print.common.HtmlContract.value_offset_percentage65;

/**
 * 清機打印
 */
public class PrintCleanMachine extends PrinterRoot<PrintCleanMachineContent> {

    private PrintCleanMachineContent mCleanMachineContent;
    private Map<String, SettlementReport.AnalysisBean> mAnalysisBeanMap = null;

    @Override
    protected void setPrintContent(PrintCleanMachineContent printContent) {
        if (printContent != null) {
            this.mCleanMachineContent = printContent;
            this.mAnalysisBeanMap = getAnalysisBeanMap(mCleanMachineContent.getAnalysis());
        }
    }

    private Map<String, SettlementReport.AnalysisBean> getAnalysisBeanMap(List<SettlementReport.AnalysisBean> analysisBeanList) {
        Map<String, SettlementReport.AnalysisBean> analysisBeanMap = new HashMap<>();
        for (int i = 0; i < analysisBeanList.size(); i++) {
            analysisBeanMap.put(analysisBeanList.get(i).getTypeName(), analysisBeanList.get(i));
        }
        return analysisBeanMap;
    }

    @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(getServeBitmap(mContext, deviceBean));
        bitmapMaps.put("", bitmaps);
        return bitmapMaps;
    }

    @Override
    public String[] getPrintDatas(Context mContext, PrinterDeviceBean deviceBean) {
        if (mCleanMachineContent == null) {
            return new String[]{"<html><body></body></html>"};
        }
        String stringBuilder = "<html><body>" +
                getHtmlHeadInfo() +
                getHtmlBusinessTotal() +
                getHtmlCashDetails() +
                getHtmlAnalysisAndStatistics() +
                getHtmlBillingStatisticsItems() +
                getHtmlBillStatusItems() +
                getHtmlCumulativeThisMonth() +
                getHtmlEndInfo()
                + "</body></html>";
        int printCount = getPrintCount(mContext);
        String[] pritContent = new String[printCount];
        for (int i = 0; i < printCount; i++) {
            pritContent[i] = stringBuilder;
        }
        return pritContent;
    }

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

    /**
     * 獲取"清機報表"圖片
     *
     * @param mContext
     * @return
     */
    private Bitmap getServeBitmap(Context mContext, PrinterDeviceBean deviceBean) {
        View view = PrintTransitUtils.getInstance().getPrintView();
        if (view != null) {
            return viewToZoomBitmap(mContext, view, deviceBean);
        }
        return null;
    }

    private String getHtmlHeadInfo() {
        List<HtmlLable> htmlLables = new ArrayList<>();

        List<String> items = new ArrayList<>();
        items.add("上次清機時間:" + mCleanMachineContent.getRestaurantOperationTime());
        items.add("品牌名稱:" + ResturantInfoManager.newInstance().getBrandName());
        items.add("店鋪名稱:" + ResturantInfoManager.newInstance().getRestaurantName());
        items.add("每日營業報表");
        items.add("由營業日期:" + mCleanMachineContent.getStartTime());
        items.add("到營業日期:" + mCleanMachineContent.getCurrentTime());
        for (String item : items) {
            htmlLables.addAll(getRowInformation(new HtmlLable[]{new HtmlLable(LABLE_COLUMN, item)}, 24));
        }
        htmlLables.add(new HtmlLable(LABLE_DIV, HtmlContract.dividing_line));
        return getHtmlLables(htmlLables.toArray(new HtmlLable[htmlLables.size()]));
    }

    private String getHtmlBusinessTotal() {

        SettlementReport.VoBean voBean = mCleanMachineContent.getVo();
        List<SettlementReport.CashBean> cashs = mCleanMachineContent.getCash();

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

        String[] items = {"項目銷售總額", "折扣", "服務費", "送貨費", "營業今個淨值", "", "現金核數", "營業金額淨值"};
        List<String> items2 = new ArrayList<>();
        items2.add(AppConstans.CARSH_STR + voBean.getPrices());
        items2.add(AppConstans.CARSH_STR + voBean.getDisamount());
        items2.add(AppConstans.CARSH_STR + voBean.getScamount());
        items2.add(AppConstans.CARSH_STR + voBean.getDeliverycharge());
        items2.add(AppConstans.CARSH_STR + voBean.getTotamount());
        items2.add("");
        items2.add("");
        items2.add(AppConstans.CARSH_STR + voBean.getTotamount());

        for (int i = 0; i < items.length; i++) {
            htmlLables.addAll(getRowInformation(new HtmlLable[]{
                            new HtmlLable(LABLE_COLUMN, items[i]),
                            new HtmlLable(LABLE_COLUMN, String.valueOf(items2.get(i)), new HtmlLable.Attributes(ATTRIBUTES_OFFSET, value_offset_last))},
                    24));
        }

        if (cashs != null) {
            for (SettlementReport.CashBean cashBean : cashs) {
                htmlLables.addAll(getRowInformation(new HtmlLable[]{
                        new HtmlLable(LABLE_COLUMN, cashBean.getPayName()),
                        new HtmlLable(LABLE_COLUMN, String.valueOf(cashBean.getPayNum()), new HtmlLable.Attributes(ATTRIBUTES_OFFSET, value_offset_percentage60)),
                        new HtmlLable(LABLE_COLUMN, AppConstans.CARSH_STR + cashBean.getPayAmount(), new HtmlLable.Attributes(ATTRIBUTES_OFFSET, value_offset_last))
                }, 24));
            }
        }
//        htmlLables.add(new HtmlLable(LABLE_P, HtmlContract.dividing_line));
        htmlLables.add(new HtmlLable(LABLE_P, HtmlContract.dividing_line));
        return getHtmlLables(htmlLables.toArray(new HtmlLable[htmlLables.size()]));
    }

    /**
     * 現金詳情
     *
     * @return
     */
    private String getHtmlCashDetails() {
        List<SettlementReport.CashBean> cashs = mCleanMachineContent.getCash();
        if (cashs == null || cashs.size() == 0) {
            return "";
        }
        List<HtmlLable> htmlLables = new ArrayList<>();
        htmlLables.add(new HtmlLable(LABLE_P, "現金詳情",
                new HtmlLable.Attributes(ATTRIBUTES_FONT_SIZE, "26"),
                new HtmlLable.Attributes(ATTRIBUTES_ALIGN, value_align_center, HtmlContract.value_type_string)));

        for (SettlementReport.CashBean cashBean : cashs) {
            if (cashBean.getPayType() == PayMethod.PAY_TYPE_CASH) {
                htmlLables.addAll(getRowInformation(new HtmlLable[]{
                        new HtmlLable(LABLE_COLUMN, cashBean.getPayName()),
                        new HtmlLable(LABLE_COLUMN, String.valueOf(cashBean.getPayNum()), new HtmlLable.Attributes(ATTRIBUTES_OFFSET, value_offset_percentage60)),
                        new HtmlLable(LABLE_COLUMN, AppConstans.CARSH_STR + cashBean.getPayAmount(), new HtmlLable.Attributes(ATTRIBUTES_OFFSET, value_offset_last))
                }, 22));
                break;
            }
        }
        if (htmlLables.size() > 0) {
            htmlLables.add(new HtmlLable(LABLE_P, HtmlContract.dividing_line));
//            htmlLables.add(new HtmlLable(LABLE_P, HtmlContract.dividing_line));
        }
        if (htmlLables.size() == 1) {
            return "";
        }
        return getHtmlLables(htmlLables.toArray(new HtmlLable[htmlLables.size()]));
    }

    /**
     * 分析統計
     *
     * @return
     */
    private String getHtmlAnalysisAndStatistics() {

        SettlementReport.VoBean voBean = mCleanMachineContent.getVo();

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

        htmlLables.add(new HtmlLable(LABLE_P, "分析統計",
                new HtmlLable.Attributes(ATTRIBUTES_FONT_SIZE, "26"),
                new HtmlLable.Attributes(ATTRIBUTES_ALIGN, value_align_center, HtmlContract.value_type_string)));

        htmlLables.addAll(getRowInformation(new HtmlLable[]{
                new HtmlLable(LABLE_COLUMN, "帳單金額總數"),
                new HtmlLable(LABLE_COLUMN, AppConstans.CARSH_STR + voBean.getTotamount(), new HtmlLable.Attributes(ATTRIBUTES_OFFSET, value_offset_last))
        }, 22));

        htmlLables.add(new HtmlLable(getRowLableStart()));
        String averagePrice = "0.00";
        if (voBean.getNum() != 0) {
            averagePrice = String.valueOf(MoneyUtil.get_ItemDecimals_money(voBean.getPrices() / voBean.getNum()));
        }

        htmlLables.addAll(getRowInformation(new HtmlLable[]{
                new HtmlLable(LABLE_COLUMN, "帳單數目"),
                new HtmlLable(LABLE_COLUMN, String.valueOf(voBean.getNum()), new HtmlLable.Attributes(ATTRIBUTES_OFFSET, value_offset_percentage60)),
                new HtmlLable(LABLE_COLUMN, AppConstans.CARSH_STR + averagePrice, new HtmlLable.Attributes(ATTRIBUTES_OFFSET, value_offset_last))
        }, 22));

        String averageConsumption = "0.00";
        if (voBean.getPerson() != 0) {
            averageConsumption = String.valueOf(MoneyUtil.get_ItemDecimals_money(voBean.getPrices() / voBean.getPerson()));
        }

        htmlLables.addAll(getRowInformation(new HtmlLable[]{
                new HtmlLable(LABLE_COLUMN, "人數 / 平均消費"),
                new HtmlLable(LABLE_COLUMN, String.valueOf(voBean.getPerson()), new HtmlLable.Attributes(ATTRIBUTES_OFFSET, value_offset_percentage60)),
                new HtmlLable(LABLE_COLUMN, AppConstans.CARSH_STR + averageConsumption, new HtmlLable.Attributes(ATTRIBUTES_OFFSET, value_offset_last))
        }, 22));

//        htmlLables.add(new HtmlLable(LABLE_P, HtmlContract.dividing_line));
        htmlLables.add(new HtmlLable(LABLE_P, HtmlContract.dividing_line));

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

    /**
     * 賬單統計
     *
     * @return
     */
    private String getHtmlBillingStatisticsItems() {

        List<HtmlLable> htmlLables = new ArrayList<>();
        htmlLables.add(new HtmlLable(LABLE_P, "賬單統計",
                new HtmlLable.Attributes(ATTRIBUTES_FONT_SIZE, "26"),
                new HtmlLable.Attributes(ATTRIBUTES_ALIGN, value_align_center, HtmlContract.value_type_string)));

        List<SettlementReport.AnalysisBean> analysisBeanList = mCleanMachineContent.getAnalysis();
        SettlementReport.VoBean voBean = mCleanMachineContent.getVo();
        for (int i = 0; i < analysisBeanList.size(); i++) {
            //當前餐廳有幾種訂單：堂食，外賣,自取
            SettlementReport.AnalysisBean analysisBean = analysisBeanList.get(i);
            if (analysisBean.equals("堂食") || analysisBean.equals("外賣") || analysisBean.equals("自取")) {
                htmlLables.addAll(getHtmlBillingStatisticsItem(analysisBean, voBean));
            }
        }
        if (htmlLables.size() == 1) {
            return "";
        }
        return getHtmlLables(htmlLables.toArray(new HtmlLable[htmlLables.size()]));
    }

    private List<HtmlLable> getHtmlBillingStatisticsItem(SettlementReport.AnalysisBean analysisBean, SettlementReport.VoBean voBean) {

        String[] items = {"類別", "賬單", "金額", "平均", "金額%"};
        List<String> items2 = new ArrayList<>();

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

        htmlLables.addAll(getRowInformation(new HtmlLable[]{
                new HtmlLable(LABLE_COLUMN, "類別"),
                new HtmlLable(LABLE_COLUMN, analysisBean.getTypeName(), new HtmlLable.Attributes(ATTRIBUTES_OFFSET, value_offset_last)),
        }, 24));

        String averagePrice = "";
        String percentage = "";
        double amount = analysisBean.getAmount();
        int num = analysisBean.getNum();
        if (voBean.getNum() != 0) {
            double number = MoneyUtil.divide(amount, num, 2);
            averagePrice = AppConstans.CARSH_STR + MoneyUtil.get_ItemDecimals_money(number);
        }
        if (amount > 0) {
            percentage = AppConstans.CARSH_STR + MoneyUtil.get_ItemDecimals_money((MoneyUtil.divide(amount, voBean.getTotamount(), 2) * 100));
        }
        items2.add(analysisBean.getTypeName());
        items2.add(String.valueOf(analysisBean.getNum()));
        items2.add(AppConstans.CARSH_STR + analysisBean.getAmount());
        items2.add(AppConstans.CARSH_STR + averagePrice);
        items2.add(AppConstans.CARSH_STR + percentage);
        for (int i = 0; i < items.length; i++) {
            htmlLables.add(new HtmlLable(getRowLableStart(new HtmlLable.Attributes(ATTRIBUTES_FONT_SIZE, "22"))));
            htmlLables.add(new HtmlLable(LABLE_COLUMN, items[i]));
            if (items2.size() > i) {
                htmlLables.add(new HtmlLable(LABLE_COLUMN, items2.get(i), new HtmlLable.Attributes(ATTRIBUTES_OFFSET, value_offset_last)));
            }
            htmlLables.add(new HtmlLable(getRowLableEnd()));
        }
        return htmlLables;
    }


    /**
     * 賬單現況:已完成賬單，未完成賬單,總計...
     *
     * @return
     */
    private String getHtmlBillStatusItems() {

        List<SettlementReport.AnalysisBean> analysisBeanList = mCleanMachineContent.getAnalysis();

        List<String> items = new ArrayList<>();
        List<String> items2 = new ArrayList<>();
        List<String> items3 = new ArrayList<>();
        List<String> items4 = new ArrayList<>();

        items.add("項目");
        items2.add("賬單");
        items3.add("人數");
        items4.add("金額");

        List<HtmlLable> htmlLables = new ArrayList<>();
        htmlLables.add(new HtmlLable(LABLE_P, "賬單現況",
                new HtmlLable.Attributes(ATTRIBUTES_FONT_SIZE, "26"),
                new HtmlLable.Attributes(ATTRIBUTES_ALIGN, value_align_center, HtmlContract.value_type_string)));

        for (int i = 0; i < analysisBeanList.size(); i++) {
            SettlementReport.AnalysisBean analysisBean = analysisBeanList.get(i);
            if ("已完成賬單".equals(analysisBean.getTypeName()) || "未完成賬單".equals(analysisBean.getTypeName()) || "總計".equals(analysisBean.getTypeName())) {
                items.add(analysisBean.getTypeName());
                items2.add(String.valueOf(analysisBean.getNum()));
                items3.add(String.valueOf(analysisBean.getPerson()));
                items4.add(AppConstans.CARSH_STR + analysisBean.getAmount());
            }
        }

        for (int i = 0; i < items.size(); i++) {
            htmlLables.add(new HtmlLable(getRowLableStart(new HtmlLable.Attributes(ATTRIBUTES_FONT_SIZE, "22"))));
            htmlLables.add(new HtmlLable(LABLE_COLUMN, items.get(i)));
            if (items2.size() > i) {
                if (i > 0) {
                    htmlLables.add(new HtmlLable(LABLE_COLUMN, items2.get(i), new HtmlLable.Attributes(ATTRIBUTES_OFFSET, value_offset_percentage35)));
                } else {
                    htmlLables.add(new HtmlLable(LABLE_COLUMN, items2.get(i), new HtmlLable.Attributes(ATTRIBUTES_OFFSET, value_offset_percentage30)));
                }
            }
            if (items3.size() > i) {
                if (i > 0) {
                    htmlLables.add(new HtmlLable(LABLE_COLUMN, items3.get(i), new HtmlLable.Attributes(ATTRIBUTES_OFFSET, value_offset_percentage65)));
                } else {
                    htmlLables.add(new HtmlLable(LABLE_COLUMN, items3.get(i), new HtmlLable.Attributes(ATTRIBUTES_OFFSET, value_offset_percentage60)));
                }
            }
            if (items4.size() > i) {
                if (i > 0) {
                    htmlLables.add(new HtmlLable(LABLE_COLUMN, items4.get(i), new HtmlLable.Attributes(ATTRIBUTES_OFFSET, value_offset_last)));
                } else {
                    htmlLables.add(new HtmlLable(LABLE_COLUMN, items4.get(i), new HtmlLable.Attributes(ATTRIBUTES_OFFSET, value_offset_last)));
                }
            }
            htmlLables.add(new HtmlLable(getRowLableEnd()));
        }
        htmlLables.add(new HtmlLable(LABLE_P, HtmlContract.dividing_line));
        htmlLables.add(new HtmlLable(getBrLable()));

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


    private String getHtmlCumulativeThisMonth() {

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

        SettlementReport.AnalysisBean analysisBean = mAnalysisBeanMap.get("本月累計營業額");

        String firstDayOfMonth = TimeUtils.getFirstDayOfMonth(TimeUtils.DATE_FORMAT_DATE) + " 00:00:00";
        String currentDate = TimeUtils.getCurrentDate(TimeUtils.DEFAULT_DATE_FORMAT);

        List<String> items = new ArrayList<>();
        items.add("本月累計營業額");
        items.add("由營業日期:" + firstDayOfMonth);
        items.add("到營業日期:" + currentDate);
        items.add("營業金額淨值");

        List<String> items2 = new ArrayList<>();
        items2.add("");
        items2.add("");
        items2.add("");
        if (analysisBean != null) {
            items2.add(AppConstans.CARSH_STR + analysisBean.getAmount());
        } else {
            items2.add(AppConstans.CARSH_STR + "0.00");
        }

        for (int i = 0; i < items.size(); i++) {
            htmlLables.add(new HtmlLable(getRowLableStart(new HtmlLable.Attributes(ATTRIBUTES_FONT_SIZE, "24"))));
            htmlLables.add(new HtmlLable(LABLE_COLUMN, items.get(i)));
            if (items2.size() > i) {
                htmlLables.add(new HtmlLable(LABLE_COLUMN, items2.get(i), new HtmlLable.Attributes(ATTRIBUTES_OFFSET, value_offset_last)));
            }
            htmlLables.add(new HtmlLable(getRowLableEnd()));
        }
        htmlLables.add(new HtmlLable(LABLE_P, HtmlContract.dividing_line));

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


    private String getHtmlEndInfo() {

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

        String currentDate = TimeUtils.getCurrentDate(TimeUtils.DEFAULT_DATE_FORMAT);

        List<String> items = new ArrayList<>();
        items.add("報表完結");
        items.add("讀取人員:" + UserContext.newInstance().getMemberName());
        items.add(currentDate);
        for (int i = 0; i < items.size(); i++) {
            htmlLables.add(new HtmlLable(getRowLableStart(new HtmlLable.Attributes(ATTRIBUTES_FONT_SIZE, "24"))));
            htmlLables.add(new HtmlLable(LABLE_COLUMN, items.get(i)));
            htmlLables.add(new HtmlLable(getRowLableEnd()));
        }
        return getHtmlLables(htmlLables.toArray(new HtmlLable[htmlLables.size()]));
    }

}
