package com.gingersoft.gsa.cloud.main.mvp.ui.activity;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.ScrollView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.core.widget.NestedScrollView;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.billy.cc.core.component.CC;
import com.gingersoft.gsa.cloud.base.application.GsaCloudApplication;
import com.gingersoft.gsa.cloud.base.common.bean.PayMethod;
import com.gingersoft.gsa.cloud.base.utils.JsonUtils;
import com.gingersoft.gsa.cloud.base.utils.LanguageUtils;
import com.gingersoft.gsa.cloud.base.utils.MoneyUtil;
import com.gingersoft.gsa.cloud.base.utils.PrintTransitUtils;
import com.gingersoft.gsa.cloud.base.utils.other.SPUtils;
import com.gingersoft.gsa.cloud.base.utils.time.TimeUtils;
import com.gingersoft.gsa.cloud.constans.PrintConstans;
import com.gingersoft.gsa.cloud.main.R;
import com.gingersoft.gsa.cloud.main.R2;
import com.gingersoft.gsa.cloud.main.di.component.DaggerSettlementReportComponent;
import com.gingersoft.gsa.cloud.main.mvp.contract.SettlementReportContract;
import com.gingersoft.gsa.cloud.main.mvp.model.bean.SendSettlement;
import com.gingersoft.gsa.cloud.main.mvp.model.bean.SettlementReport;
import com.gingersoft.gsa.cloud.main.mvp.presenter.SettlementReportPresenter;
import com.gingersoft.gsa.cloud.ui.bean.view.SectionTextItem3;
import com.gingersoft.gsa.cloud.ui.bean.view.SectionTextItem5;
import com.gingersoft.gsa.cloud.ui.utils.AnimateUtils;
import com.gingersoft.gsa.cloud.ui.widget.dialog.LoadingDialog;
import com.jess.arms.base.BaseActivity;
import com.jess.arms.base.DefaultAdapter;
import com.jess.arms.di.component.AppComponent;
import com.jess.arms.integration.AppManager;
import com.jess.arms.utils.ArmsUtils;
import com.jess.arms.utils.DeviceUtils;
import com.qmuiteam.qmui.widget.QMUITopBar;
import com.qmuiteam.qmui.widget.dialog.QMUIDialog;
import com.qmuiteam.qmui.widget.dialog.QMUIDialogAction;
import org.jetbrains.annotations.NotNull;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.inject.Inject;
import butterknife.BindView;
import butterknife.OnClick;
import static com.jess.arms.utils.Preconditions.checkNotNull;


/**
 * ================================================
 * Description:
 * <p>
 * Created by MVPArmsTemplate on 03/04/2020 21:36
 * <a href="mailto:jess.yan.effort@gmail.com">Contact me</a>
 * <a href="https://github.com/JessYanCoding">Follow me</a>
 * <a href="https://github.com/JessYanCoding/MVPArms">Star me</a>
 * <a href="https://github.com/JessYanCoding/MVPArms/wiki">See me</a>
 * <a href="https://github.com/JessYanCoding/MVPArmsTemplate">模版请保持更新</a>
 * ================================================
 */
public class SettlementReportActivity extends BaseActivity<SettlementReportPresenter> implements SettlementReportContract.View {

    @Inject
    AppManager mAppManager;

    @BindView(R2.id.topbar)
    QMUITopBar mTopBar;

    @BindView(R2.id.tv_restaurant_name)
    TextView tv_restaurant_name;
    @BindView(R2.id.tv_business_area_title)
    TextView tv_business_area_title;
    @BindView(R2.id.tv_last_time)
    TextView tv_last_time;
    @BindView(R2.id.tv_start_time)
    TextView tv_start_time;
    @BindView(R2.id.tv_end_time)
    TextView tv_end_time;

    @BindView(R2.id.scrollView)
    NestedScrollView scrollView;

    @BindView(R2.id.sv_cross_days)
    ScrollView sv_cross_days;

    @BindView(R2.id.ll_cross_days)
    LinearLayout ll_cross_days;
    @BindView(R2.id.lv_order_condition)
    ListView lv_order_info;
    @BindView(R2.id.rb_condition)
    RadioGroup rb_condition;

    //    @BindView(R2.id.rv_settlement_report_item)
//    RecyclerView rv_settlement_report_item;
    @BindView(R2.id.rv_settlement_report_item2)
    RecyclerView rv_settlement_report_item2;

    private Button rightBtn;

    private int type;

    /**
     * 1#全部計入到10號清機數據
     * 2#全部計入到12號清機數據
     * 3#分別按天結算
     */
    public static final int merge_settlement_type_1 = 1;
    public static final int merge_settlement_type_2 = 2;
    public static final int merge_settlement_type_3 = 3;

    //币種
    public String cashStr = "$";
    protected String dfformat = "#0.00";
    protected DecimalFormat df;


    @Override
    public void setupActivityComponent(@NonNull AppComponent appComponent) {
        DaggerSettlementReportComponent //如找不到该类,请编译一下项目
                .builder()
                .appComponent(appComponent)
                .view(this)
                .build()
                .inject(this);
    }

    @Override
    public int initView(@Nullable Bundle savedInstanceState) {
        return R.layout.activity_settlement_report; //如果你不需要框架帮你设置 setContentView(id) 需要自行设置,请返回 0
    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {
//        tv_last_time.setVisibility(View.GONE);
        scrollView.post(() -> scrollView.fullScroll(ScrollView.FOCUS_UP));
    }

    @Override
    public void initIntent() {
        Intent intent = getIntent();
        SettlementReport.DataBean settlementReportBean = (SettlementReport.DataBean) intent.getSerializableExtra("settlementReportBean");
        df = new DecimalFormat(dfformat);
        if (settlementReportBean != null) {
            mPresenter.initAdapter();
            returnSettlementData(settlementReportBean);
        } else {
            mPresenter.initAdapter();
            mPresenter.getSettlementReport();
        }
    }

    @Override
    public void initTopBar() {
        mTopBar.setBackgroundColor(ContextCompat.getColor(this, R.color.theme_color));
        mTopBar.addLeftBackImageButton().setOnClickListener(v -> {
            killMyself();
//                overridePendingTransition(R.anim.slide_still, R.anim.slide_out_right);
        });
        rightBtn = mTopBar.addRightTextButton("打印", R.id.tv_right);
        rightBtn.setTextColor(ArmsUtils.getColor(this, R.color.theme_white_color));
        rightBtn.setOnClickListener(v -> {
            String settlementReportJson = (String) SPUtils.get( PrintConstans.SETTLEMENT_REPORT, "");
            if (!TextUtils.isEmpty(settlementReportJson)) {
                SettlementReport.DataBean datasBean = JsonUtils.parseObject(settlementReportJson, SettlementReport.DataBean.class);
                if (datasBean != null) {
                    returnSettlementData(datasBean);
                    printRepore();
                }
            } else {
                showMessage("暫無可印報表");
            }
        });
        mTopBar.setTitle(LanguageUtils.get_language_system(this, "function.order.detail2", "清機報表")).setTextColor(ArmsUtils.getColor(this, R.color.theme_white_color));
    }

    @OnClick({R2.id.btn_send_settlement})
    public void onClick(View v) {
        if (v.getId() == R.id.btn_send_settlement) {
            type = 0;
            showSendSettlementDialog();
        }
    }


    @OnClick({R2.id.btn_sure_cross_days})
    public void onClickSure(View v) {
        if (v.getId() == R.id.btn_sure_cross_days) {
            showSendSettlementDialog();
        }
    }

    @OnClick({R2.id.btn_cancel_cross_days})
    public void onClickCancel(View v) {
        if (v.getId() == R.id.btn_cancel_cross_days) {
            type = 0;
            AnimateUtils.animateDown(sv_cross_days, 500);
            sv_cross_days.setVisibility(View.GONE);
        }
    }

    private void showSendSettlementDialog() {
        QMUIDialog.MessageDialogBuilder dialogBuilder = new QMUIDialog.MessageDialogBuilder(this);
        dialogBuilder.setTitle("溫馨提示");


        dialogBuilder.setMessage("是否確認清機");
        dialogBuilder.addAction(0, "確認", QMUIDialogAction.ACTION_PROP_NEGATIVE, (dialog, index) -> {
            mPresenter.sendSettlement(type);
            dialog.dismiss();
        });
        dialogBuilder.addAction("取消", (dialog, index) -> dialog.dismiss());
        dialogBuilder.create(com.gingersoft.gsa.cloud.base.R.style.MyDialogTheme2).show();
    }

    @Override
    public void initLanguage() {
        String brandName = "品牌名稱: " + GsaCloudApplication.getBrandName();
        String restaurantName = "店鋪名稱: " + GsaCloudApplication.getRestaurantName();
        tv_restaurant_name.setText(brandName + "\n" + restaurantName);
    }

    @Override
    public void initLayoutParams() {

    }

    @Override
    public void initLayoutVisible() {

    }

    @Override
    public void showLoading(String message) {
        if (message != null)
            LoadingDialog.showDialogForLoading(this, message, true);
        else
            LoadingDialog.showDialogForLoading(this);
    }

    @Override
    public void hideLoading() {
        LoadingDialog.cancelDialogForLoading();
    }

    @Override
    public void showMessage(@NonNull String message) {
        ArmsUtils.makeText(this, message);
    }

    @Override
    public void launchActivity(@NonNull Intent intent) {
        checkNotNull(intent);
        ArmsUtils.startActivity(intent);
    }

    @Override
    public void killMyself() {
        finish();
    }


    @Override
    public void setSettlementReportItemAdapter(DefaultAdapter adapter) {
        setSettlementReportItemRecycleLayoutManager();
//        rv_settlement_report_item.setAdapter(adapter);
    }

    @Override
    public void setSettlementReportItem5Adapter(DefaultAdapter adapter) {
        setSettlementReportItem5RecycleLayoutManager();
        rv_settlement_report_item2.setAdapter(adapter);
    }

    @Override
    public void returnSettlementData(SettlementReport.DataBean datasBean) {
        if (datasBean.getVo() != null && datasBean.getVo().getPrices() > 0) {
            //保存下次重印數據
            SPUtils.put( PrintConstans.SETTLEMENT_REPORT, JsonUtils.toJson(datasBean));
        }

        List<SectionTextItem3> settlementReportItems = new ArrayList<>();
        List<SectionTextItem5> settlementReportItem5s = new ArrayList<>();

        String lastSettlementText = LanguageUtils.get_language_system(this, "", "上次清機時間:");
        String dailyBusinessReportText = LanguageUtils.get_language_system(this, "", "每日營業報表");
        String byBusinessDateText = LanguageUtils.get_language_system(this, "", "由營業日期:");
        String toBusinessDateText = LanguageUtils.get_language_system(this, "", "到營業日期:");
        String headcountOrAverageConsumptionText = LanguageUtils.get_language_system(this, "", "統計:");
        String totalText = LanguageUtils.get_language_system(this, "", "總計");
        String canteenText = LanguageUtils.get_language_system(this, "", "堂食");
        String takewayText = LanguageUtils.get_language_system(this, "", "外賣");
        String selfFetchingText = LanguageUtils.get_language_system(this, "", "自取");
        String projectTotalSalesText = LanguageUtils.get_language_system(this, "total.project.sales", "項目銷售總額");
        String discountText = LanguageUtils.get_language_system(this, "", "折扣");
        String serviceFeeText = LanguageUtils.get_language_system(this, "", "服務費");
        String deliveryFeeText = LanguageUtils.get_language_system(this, "", "送貨費");

        String orderCountallText = LanguageUtils.get_language_system(this, "order.countall_litter", "賬單小數");
        String netTurnoverText = LanguageUtils.get_language_system(this, "net.turnover", "營業金額淨值");
        String cashAuditText = LanguageUtils.get_language_system(this, "cash.audit", "現金核數");
        String analysisStatisticsText = LanguageUtils.get_language_system(this, "analysis.statistics", "分析統計");
        String totalbillAmountText = LanguageUtils.get_language_system(this, "total.bill.amount", "賬單金額總數");
        String numberBillsOrAverageText = LanguageUtils.get_language_system(this, "number.bills.or.average", "賬單數目/平均");
        String headcountAndAverageConsumptionText = LanguageUtils.get_language_system(this, "headcount.or.average.consumption", "人數/平均消費");

        String billStatusText = LanguageUtils.get_language_system(this, "", "賬單現況");
//        String outstandingBillText = LanguageUtils.get_language_system(this, "", "未完成賬單");
//        String billsReceivedText = LanguageUtils.get_language_system(this, "", "已完成賬單");
        String outstandingBillText = LanguageUtils.get_language_system(this, "", "未完成賬單");
        String billsReceivedText = LanguageUtils.get_language_system(this, "", "已完成賬單");

        String cumulativeTurnoverMonthText = LanguageUtils.get_language_system(this, "", "本月累計營業額");

        String endReportText = LanguageUtils.get_language_system(this, "", "報表完結");
        String readersText = LanguageUtils.get_language_system(this, "", "讀取人員");

        SettlementReport.DataBean.RestaurantOperationBean restaurantOperationBean = datasBean.getRestaurantOperation();
        if (restaurantOperationBean != null) {
            tv_business_area_title.setText(dailyBusinessReportText);
            tv_last_time.setText(lastSettlementText + TimeUtils.getStringByFormat(restaurantOperationBean.getOperationTime(), TimeUtils.DEFAULT_DATE_FORMAT));
        }

        tv_start_time.setText(byBusinessDateText + datasBean.getStartTime());
        tv_end_time.setText(toBusinessDateText + datasBean.getCurrentTime());

        SettlementReport.DataBean.VoBean voBean = datasBean.getVo();
        if (voBean != null) {
            settlementReportItem5s.add(new SectionTextItem5(projectTotalSalesText, null, null, null, cashStr + df.format(voBean.getPrices())));
            settlementReportItem5s.add(new SectionTextItem5(discountText, null, null, null, "-" + cashStr + df.format(voBean.getDisamount())));
            settlementReportItem5s.add(new SectionTextItem5(serviceFeeText, null, null, null, cashStr + df.format(voBean.getScamount())));
            settlementReportItem5s.add(new SectionTextItem5(deliveryFeeText, null, null, null, cashStr + df.format(voBean.getDeliverycharge())));
            settlementReportItem5s.add(new SectionTextItem5(netTurnoverText, null, null, null, cashStr + df.format(voBean.getTotamount())));

//            if (voBean.getPayNum() > 0) {
//                String creditCardText = LanguageUtils.get_language_system(this, "credit.card", "信用卡");
//                SectionTextItem5 printItem = new SectionTextItem5(creditCardText, String.valueOf(voBean.getPayNum()), null,null,"$" + df.format(voBean.getPayamount()));
//                settlementReportItem5s.add(printItem);
//            }
            settlementReportItem5s.add(new SectionTextItem5(null, null, " ", null, null));
            settlementReportItem5s.add(new SectionTextItem5(cashAuditText, null, null, null, null));
            settlementReportItem5s.add(new SectionTextItem5(netTurnoverText, null, null, null, cashStr + df.format(voBean.getTotamount())));
            List<SettlementReport.DataBean.CashBean> cashList = datasBean.getCash();
            if (cashList != null && cashList.size() > 0) {
                for (int i = 0; i < cashList.size(); i++) {
                    SettlementReport.DataBean.CashBean cashBean = cashList.get(i);
                    settlementReportItem5s.add(new SectionTextItem5(cashBean.getPayName(), null, String.valueOf(cashBean.getPayNum()), null, cashStr + df.format(cashBean.getPayAmount())));
                }
            }
        }

        List<SettlementReport.DataBean.CashBean> cashList = datasBean.getCash();
        if (cashList != null && cashList.size() > 0) {
            for (int i = 0; i < cashList.size(); i++) {
                SettlementReport.DataBean.CashBean cashBean = cashList.get(i);
                if(cashBean.getPayType() == PayMethod.PAY_TYPE_CASH){
                    /**現金詳情*/
                    String cashDetailText = LanguageUtils.get_language_system(this, "credit.cash.detail", "現金詳情");
                    String cashText = LanguageUtils.get_language_system(this, "credit.cash", "現金");
                    settlementReportItem5s.add(new SectionTextItem5("==============================================================", null, null, null, null));
                    settlementReportItem5s.add(new SectionTextItem5(null, null, cashDetailText, null, null));
                    settlementReportItem5s.add(new SectionTextItem5(cashText, null, String.valueOf(cashBean.getPayNum()), null, cashStr + df.format(cashBean.getPayAmount())));
                    //統計
                    settlementReportItem5s.add(new SectionTextItem5(headcountOrAverageConsumptionText, null, null, null, cashStr + df.format(cashBean.getPayAmount())));
                    break;
                }
            }
        }

        List<SettlementReport.DataBean.AnalysisBean> analysisBeanList = datasBean.getAnalysis();
        Map<String, SettlementReport.DataBean.AnalysisBean> analysisBeanMap = null;
        if (analysisBeanList != null && analysisBeanList.size() > 0) {
            analysisBeanMap = getAnalysisBeanMap(analysisBeanList);
        }

        if (voBean != null) {
            /**分析統計*/
            settlementReportItem5s.add(new SectionTextItem5("==============================================================", null, null, null, null));
            settlementReportItem5s.add(new SectionTextItem5(null, null, analysisStatisticsText, null, null));
            //帳單金額總數
            settlementReportItem5s.add(new SectionTextItem5(totalbillAmountText, null, null, null, cashStr + df.format(voBean.getTotamount())));
            //帳單數目 / 平均
            String averagePrice = "0.00";
            if (voBean.getNum() != 0) {
                double number = voBean.getPrices() / voBean.getNum();
                averagePrice = df.format(Double.isNaN(number) ? 0 : number);
            }
            settlementReportItem5s.add(new SectionTextItem5(numberBillsOrAverageText, null, String.valueOf(voBean.getNum()), null, cashStr + averagePrice));
            //人數 / 平均消費
            String averageConsumption = "0.00";
            if (voBean.getPerson() != 0) {
                double number = voBean.getPrices() / voBean.getPerson();
                averageConsumption = df.format(Double.isNaN(number) ? 0 : number);
            }
            settlementReportItem5s.add(new SectionTextItem5(headcountAndAverageConsumptionText, null, String.valueOf(voBean.getPerson()), null, cashStr + averageConsumption));

            /** 帳單統計*/
            settlementReportItem5s.add(new SectionTextItem5("==============================================================", null, null, null, null));
            settlementReportItem5s.add(new SectionTextItem5(null, null, "帳單統計", null, null));
//            if (!GsaCloudApplication.mV2.contains(Build.MODEL) && !GsaCloudApplication.mN5.contains(Build.MODEL)) {
//                settlementReportItem5s.add(new SectionTextItem5("類別", "帳單", "金額", "平均", "金額%"));
//            }
            //總計
            //平均數
            String averagePrice2 = "0.00";
            if (voBean.getNum() != 0) {
                double number = voBean.getTotamount() / voBean.getNum();
                averagePrice2 = df.format(Double.isNaN(number) ? 0 : number);
            }
            //計算佔比
            int percentage = 0;
            if (voBean.getPrices() > 0) {
                percentage = (int) (MoneyUtil.divide(voBean.getTotamount(), voBean.getPrices(), 2) * 100);
            }
            //            settlementReportItem5s.add(new SectionTextItem5(totalText, String.valueOf(voBean.getNum()), "$" + df.format(voBean.getTotamount()), "$" + averagePrice2, percentage + "%"));
            //堂食
            String canteenNum = "";
            String canteenTotamout = "";
            String canteenAveragePrice = "";
            String canteenPercentage = "";
            if (analysisBeanMap != null && analysisBeanMap.containsKey(canteenText)) {
                double amount = analysisBeanMap.get(canteenText).getAmount();
                int num = analysisBeanMap.get(canteenText).getNum();
                canteenNum = num + "";
                canteenTotamout = cashStr + df.format(amount);
                if (voBean.getNum() != 0) {
                    double number = MoneyUtil.divide(amount, num, 2);
                    canteenAveragePrice = cashStr + df.format(number);
                }
                if (amount > 0) {
                    canteenPercentage = (int) (MoneyUtil.divide(amount, voBean.getTotamount(), 2) * 100) + "";
                }
//                if (!GsaCloudApplication.mV2.contains(Build.MODEL) && !GsaCloudApplication.mN5.contains(Build.MODEL)) {
//                    settlementReportItem5s.add(new SectionTextItem5(canteenText, canteenNum, canteenTotamout, canteenAveragePrice, canteenPercentage));
//                }
            } else {
                canteenText = "";
            }

            //外賣
            String takewayNum = "";
            String takewayTotamout = "";
            String takewayAveragePrice = "";
            String takewayPercentage = "";
            if (analysisBeanMap != null && analysisBeanMap.containsKey(takewayText)) {
                double amount = analysisBeanMap.get(takewayText).getAmount();
                int num = analysisBeanMap.get(takewayText).getNum();
                takewayNum = num + "";
                takewayTotamout = cashStr + df.format(amount);
                if (voBean.getNum() != 0) {
                    double number = MoneyUtil.divide(amount, num, 2);
                    takewayAveragePrice = cashStr + df.format(number);
                }
                if (amount > 0) {
                    takewayPercentage = (int) (MoneyUtil.divide(amount, voBean.getTotamount(), 2) * 100) + "";
                }
//                if (!GsaCloudApplication.mV2.contains(Build.MODEL ) && !GsaCloudApplication.mN5.contains(Build.MODEL)) {
//                    settlementReportItem5s.add(new SectionTextItem5(takewayText, takewayNum, takewayTotamout, takewayAveragePrice, takewayPercentage));
//                }
            } else {
                takewayText = "";
            }
            //自取
            String selfFetchingNum = "";
            String selfFetchingTotamout = "";
            String selfFetchingAveragePrice = "";
            String selfFetchingPercentage = "";
            if (analysisBeanMap != null && analysisBeanMap.containsKey(selfFetchingText)) {
                double amount = analysisBeanMap.get(selfFetchingText).getAmount();
                int num = analysisBeanMap.get(selfFetchingText).getNum();
                selfFetchingNum = num + "";
                selfFetchingTotamout = cashStr + df.format(amount);
                if (voBean.getNum() != 0) {
                    double number = MoneyUtil.divide(amount, num, 2);
                    selfFetchingAveragePrice = cashStr + df.format(number);
                }
                if (amount > 0) {
                    selfFetchingPercentage = (int) (MoneyUtil.divide(amount, voBean.getTotamount(), 2) * 100) + "";
                }
//                if (!GsaCloudApplication.mV2.contains(Build.MODEL ) && !GsaCloudApplication.mN5.contains(Build.MODEL)) {
//                    settlementReportItem5s.add(new SectionTextItem5(selfFetchingText, selfFetchingNum, selfFetchingTotamout, selfFetchingAveragePrice, selfFetchingPercentage));
//                }
            } else {
                selfFetchingText = "";
            }
//            if (GsaCloudApplication.mV2.contains(Build.MODEL ) || GsaCloudApplication.mN5.contains(Build.MODEL)) {
            settlementReportItem5s.add(new SectionTextItem5("類別", canteenText, takewayText, selfFetchingText, null));
            settlementReportItem5s.add(new SectionTextItem5("賬單", canteenNum, takewayNum, selfFetchingNum, null));
            settlementReportItem5s.add(new SectionTextItem5("金額", canteenTotamout, takewayTotamout, selfFetchingTotamout, null));
            settlementReportItem5s.add(new SectionTextItem5("平均", canteenAveragePrice, takewayAveragePrice, selfFetchingAveragePrice, null));
            settlementReportItem5s.add(new SectionTextItem5("金額%", canteenPercentage, takewayPercentage, selfFetchingPercentage, null));
//            }
        }

        if (analysisBeanMap != null && analysisBeanMap.size() > 0) {

            /**賬單現況*/
            settlementReportItem5s.add(new SectionTextItem5(null, null, null, null, null));
            settlementReportItem5s.add(new SectionTextItem5("==============================================================", null, null, null, null));
            settlementReportItem5s.add(new SectionTextItem5(null, null, "賬單現況", null, null));
            settlementReportItem5s.add(new SectionTextItem5("項目", "帳單", "人數", null, "金額"));
//            settlementReportItem5s.add(new SectionTextItem5("--------------------------------------------------------------------------------", null, null, null, null));
            //未完成帳單
            double item5Amount = 0.0;
            int item5num = 0;
            int item5PeopleNum = 0;
            if (analysisBeanMap.containsKey(outstandingBillText)) {
                SettlementReport.DataBean.AnalysisBean analysisBean = analysisBeanMap.get(outstandingBillText);
                settlementReportItem5s.add(new SectionTextItem5(analysisBean.getTypeName(), String.valueOf(analysisBean.getNum()), String.valueOf(analysisBean.getPerson()), null, cashStr + df.format(analysisBean.getAmount())));
                item5Amount += analysisBean.getAmount();
                item5num += analysisBean.getNum();
                item5PeopleNum += analysisBean.getPerson();
            }
            //已收款帳單
            if (analysisBeanMap.containsKey(billsReceivedText)) {
                SettlementReport.DataBean.AnalysisBean analysisBean = analysisBeanMap.get(billsReceivedText);
                settlementReportItem5s.add(new SectionTextItem5(analysisBean.getTypeName(), String.valueOf(analysisBean.getNum()), String.valueOf(analysisBean.getPerson()), null, cashStr + df.format(analysisBean.getAmount())));
                item5Amount += analysisBean.getAmount();
                item5num += analysisBean.getNum();
                item5PeopleNum += analysisBean.getPerson();
            }
            //總計
            settlementReportItem5s.add(new SectionTextItem5(totalText, String.valueOf(item5num), String.valueOf(item5PeopleNum), null, cashStr + df.format(item5Amount)));


            /**本月累計營業額*/
            if (analysisBeanMap.containsKey(cumulativeTurnoverMonthText)) {
                SettlementReport.DataBean.AnalysisBean analysisBean = analysisBeanMap.get(cumulativeTurnoverMonthText);
                String firstDayOfMonth = TimeUtils.getFirstDayOfMonth(TimeUtils.DATE_FORMAT_DATE) + " 00:00:00";
                String currentDate = TimeUtils.getCurrentDate(TimeUtils.DEFAULT_DATE_FORMAT);
                settlementReportItem5s.add(new SectionTextItem5(null, null, null, null, null));
                settlementReportItem5s.add(new SectionTextItem5("==============================================================", null, null, null, null));
                settlementReportItem5s.add(new SectionTextItem5(cumulativeTurnoverMonthText, null, null, null, null));
                settlementReportItem5s.add(new SectionTextItem5(byBusinessDateText + firstDayOfMonth, null, null, null, null));
                settlementReportItem5s.add(new SectionTextItem5(toBusinessDateText + currentDate, null, null, null, null));
                settlementReportItem5s.add(new SectionTextItem5(netTurnoverText, null, null, null, cashStr + df.format(analysisBean.getAmount())));
            }

            /**報表完結*/
            String memberName = GsaCloudApplication.getMemberName();
            String currentDate = TimeUtils.getCurrentDate(TimeUtils.DEFAULT_DATE_FORMAT);
            settlementReportItem5s.add(new SectionTextItem5(null, null, null, null, null));
            settlementReportItem5s.add(new SectionTextItem5("==============================================================", null, null, null, null));
            settlementReportItem5s.add(new SectionTextItem5("報表完結", null, null, null, null));
            settlementReportItem5s.add(new SectionTextItem5("讀取人員 " + memberName, null, null, null, null));
            settlementReportItem5s.add(new SectionTextItem5(currentDate + " v" + DeviceUtils.getVersionName(this), null, null, null, null));
            settlementReportItem5s.add(new SectionTextItem5(null, null, null, null, null));
        }

        mPresenter.notifyReportItem5Adapter(settlementReportItem5s);
        scrollView.post(() -> scrollView.fullScroll(ScrollView.FOCUS_UP));
    }

    @Override
    public void printRepore() {
        View view = initPrintView();
        //清機成功，打印
        PrintTransitUtils.getInstance().setPrintView(view);
        CC.obtainBuilder("Component.Print")
                .addParam(PrintConstans.PRINT_TYPE, PrintConstans.PRINT_CLEAN_MACHINE)//清機打印
                .setActionName("printActivity")
                .build()
                .callAsyncCallbackOnMainThread((cc, result) -> {
                    //打印完之後，清除view
                    PrintTransitUtils.getInstance().setPrintView(null);
//                    if (mPresenter != null) {
//                        mPresenter.getSettlementReport();
//                    }
                    mAppManager.killActivity(SettlementActivity.class);
                    killMyself();
                });
    }

    @Override
    public void showCrossDaysLayout(boolean show) {
        if (show) {
            AnimateUtils.animateUp(sv_cross_days, 500);
            sv_cross_days.setVisibility(View.VISIBLE);
            rightBtn.setVisibility(View.INVISIBLE);
        } else {
            AnimateUtils.animateDown(sv_cross_days, 500);
            sv_cross_days.setVisibility(View.GONE);
            rightBtn.setVisibility(View.VISIBLE);
        }
    }

    private RadioButton type1Button, type2Button, type3Button;

    @Override
    public void setOrderConditionList(List<SendSettlement.DataBean.DateNumBean> dateNum, String type1, String type2, String type3) {

        rb_condition.removeAllViews();

        int rbIndex = 0;
        if (!TextUtils.isEmpty(type1)) {
            type1Button = new RadioButton(this);
            type1Button.setText(type1);
            //默認選中第一個
//            type = 1;
//            type1Button.setChecked(true);
            rb_condition.addView(type1Button, rbIndex);
            rbIndex++;
        }
        if (!TextUtils.isEmpty(type2)) {
            type2Button = new RadioButton(this);
            type2Button.setText(type2);
            rb_condition.addView(type2Button, rbIndex);
            rbIndex++;
        }
        if (!TextUtils.isEmpty(type3)) {
            type3Button = new RadioButton(this);
            type3Button.setText(type3);
            rb_condition.addView(type3Button, rbIndex);
        }

        List<Map<String, Object>> lists = new ArrayList<>();

        for (int i = 0; i < dateNum.size(); i++) {
            SendSettlement.DataBean.DateNumBean dateNumBean = dateNum.get(i);
            Map<String, Object> map = new HashMap<>();
            map.put("date", TimeUtils.formatDate(dateNumBean.getDate(),TimeUtils.DATE_FORMAT_DATE ,TimeUtils.DEFAULT_DATE_MD));
            map.put("num", dateNumBean.getNum());
            lists.add(map);
        }

        SimpleAdapter adapter = new SimpleAdapter(this, lists, R.layout.item_settlement_cross_days_date_num
                , new String[]{"date", "num"}
                , new int[]{R.id.tv_date, R.id.tv_num});
        lv_order_info.setAdapter(adapter);

        rb_condition.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
//                if (type1Button != null) {
//                    type1Button.setChecked(false);
//                }
//                if (type2Button != null) {
//                    type2Button.setChecked(false);
//                }
//                if (type3Button != null) {
//                    type3Button.setChecked(false);
//                }
                if (type1Button != null && type1Button.getId() == checkedId) {
                    type = merge_settlement_type_1;
                }
                if (type2Button != null && type2Button.getId() == checkedId) {
                    type = merge_settlement_type_2;
                }
                if (type3Button != null && type3Button.getId() == checkedId) {
                    type = merge_settlement_type_3;
                }
            }
        });
    }

    private void setTypeRadioButton(int type) {
        if (type1Button != null) {
            type1Button.setChecked(false);
        }
        if (type2Button != null) {
            type2Button.setChecked(false);
        }
        if (type3Button != null) {
            type3Button.setChecked(false);
        }
        switch (type) {
            case 1:
                if (type1Button != null) {
                    type1Button.toggle();
                }
                break;
            case 2:
                if (type2Button != null) {
                    type2Button.toggle();
                }
                break;
            case 3:
                if (type3Button != null) {
                    type3Button.toggle();
                }
                break;
        }
    }

    @NotNull
    private View initPrintView() {
        View view = View.inflate(mContext, R.layout.layout_settlement_report, null);
        TextView mTvLastTime = view.findViewById(R.id.tv_last_time);
        TextView mTvBrandName = view.findViewById(R.id.tv_restaurant_name);
        TextView mTvStoreName = view.findViewById(R.id.tv_business_area_title);
        TextView mTvStartTime = view.findViewById(R.id.tv_start_time);
        TextView mTvEndTime = view.findViewById(R.id.tv_end_time);
        RecyclerView recyclerView = view.findViewById(R.id.rv_settlement_report_item2);
        mTvBrandName.setText(tv_restaurant_name.getText());
        mTvLastTime.setText(tv_last_time.getText());
        mTvStoreName.setText(tv_business_area_title.getText());
        mTvStartTime.setText(tv_start_time.getText());
        mTvEndTime.setText(tv_end_time.getText());
        int textSize = 24;
        mTvLastTime.setTextSize(textSize);
        mTvBrandName.setTextSize(textSize);
        mTvStoreName.setTextSize(textSize);
        mTvStartTime.setTextSize(textSize);
        mTvEndTime.setTextSize(textSize);

        recyclerView.setLayoutManager(new LinearLayoutManager(mContext));
        recyclerView.setAdapter(mPresenter.mPrintAdapter);
        return view;
    }

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

    public void setSettlementReportItemRecycleLayoutManager() {
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
//        rv_settlement_report_item.setLayoutManager(linearLayoutManager);
//        rv_settlement_report_item.setItemAnimator(new DefaultItemAnimator());
    }

    public void setSettlementReportItem5RecycleLayoutManager() {
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
        if (rv_settlement_report_item2 != null) {
            rv_settlement_report_item2.setLayoutManager(linearLayoutManager);
            rv_settlement_report_item2.setItemAnimator(new DefaultItemAnimator());
        }
    }

    public void setType(int type) {
        this.type = type;
    }
}
