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

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ScrollView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
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.utils.LanguageUtils;
import com.gingersoft.gsa.cloud.base.utils.PrintTransitUtils;
import com.gingersoft.gsa.cloud.base.utils.time.TimeUtil;
import com.gingersoft.gsa.cloud.base.utils.time.TimeUtils;
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.SettlementReport;
import com.gingersoft.gsa.cloud.main.mvp.model.bean.SettlementReportItem;
import com.gingersoft.gsa.cloud.main.mvp.model.bean.SettlementReportItem5;
import com.gingersoft.gsa.cloud.main.mvp.presenter.SettlementReportPresenter;
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.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 java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

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 {

    @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)
    ScrollView scrollView;

    //    @BindView(R2.id.rv_settlement_report_item)
//    RecyclerView rv_settlement_report_item;
    @BindView(R2.id.rv_settlement_report_item2)
    RecyclerView rv_settlement_report_item2;
    //币種
    public String cashStr = "$";
    protected String dfformat = "#0.00";
    protected DecimalFormat df;


    private SettlementReport.DataBean mSettlementReportBean;
    private static SettlementReportActivity settlementReportActivity;

    public static SettlementReportActivity getInstance() {
        return settlementReportActivity;
    }


    @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) {
    }

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

    @Override
    public void initTopBar() {
        mTopBar.setBackgroundColor(ContextCompat.getColor(this, R.color.theme_color));
        mTopBar.addLeftBackImageButton().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                killMyself();
//                overridePendingTransition(R.anim.slide_still, R.anim.slide_out_right);
            }
        });
        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) {
            showSendSettlementDialog();
        }
    }

    private void showSendSettlementDialog() {
        QMUIDialog.MessageDialogBuilder dialogBuilder = new QMUIDialog.MessageDialogBuilder(this);
        dialogBuilder.setTitle("溫馨提示");
        dialogBuilder.setMessage("是否確認清機");
        dialogBuilder.addAction("取消", (dialog, index) -> dialog.dismiss());
        dialogBuilder.addAction(0, "確認", QMUIDialogAction.ACTION_PROP_NEGATIVE, (dialog, index) -> {
            mPresenter.sendSettlement();
            dialog.dismiss();
        });
        dialogBuilder.create(com.gingersoft.gsa.cloud.base.R.style.MyDialogTheme2).show();
    }

    @Override
    public void initLanguage() {
        String brandName = "品牌名稱: " + GsaCloudApplication.getBrandName(this);
        String restaurantName = "店鋪名稱: " + GsaCloudApplication.getRestaurantName(this);
        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) {

        List<SettlementReportItem> settlementReportItems = new ArrayList<>();
        List<SettlementReportItem5> 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 projectTotalSalesText = LanguageUtils.get_language_system(this, "total.project.sales", "項目銷售總額");
        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 cumulativeTurnoverMonthText = LanguageUtils.get_language_system(this, "", "本月累計營業額");

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

        tv_last_time.setText(lastSettlementText + datasBean.getYesterdayTime());

        SettlementReport.DataBean.RestaurantOperationBean restaurantOperationBean = datasBean.getRestaurantOperation();
        if (restaurantOperationBean != null) {
            String currentDate = TimeUtil.getCurrentDate(TimeUtil.dateFormatYMDHMS);
            tv_business_area_title.setText(dailyBusinessReportText);
            tv_start_time.setText(byBusinessDateText + TimeUtils.getStringByFormat(restaurantOperationBean.getOpenTime(), TimeUtils.dateFormatYMDHMS));
//            tv_end_time.setText(toBusinessDateText + TimeUtils.getStringByFormat(restaurantOperationBean.getOperationTime(), TimeUtils.dateFormatYMDHMS));
            tv_end_time.setText(toBusinessDateText + currentDate);
        }

        SettlementReport.DataBean.VoBean voBean = datasBean.getVo();
        if (voBean != null) {
            settlementReportItem5s.add(new SettlementReportItem5(projectTotalSalesText, " ", " ", " ", "$" + df.format(voBean.getPrices())));
            settlementReportItem5s.add(new SettlementReportItem5(netTurnoverText, " ", " ", " ", "$" + df.format(voBean.getTotamount())));
//            if (voBean.getPayNum() > 0) {
//                String creditCardText = LanguageUtils.get_language_system(this, "credit.card", "信用卡");
//                SettlementReportItem5 printItem = new SettlementReportItem5(creditCardText, String.valueOf(voBean.getPayNum()), " "," ","$" + df.format(voBean.getPayamount()));
//                settlementReportItem5s.add(printItem);
//            }
            settlementReportItem5s.add(new SettlementReportItem5(" ", " ", " ", " ", " "));
            settlementReportItem5s.add(new SettlementReportItem5(cashAuditText, " ", " ", " ", " "));
            settlementReportItem5s.add(new SettlementReportItem5(netTurnoverText, " ", " ", " ", "$" + df.format(voBean.getPrices())));
            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 SettlementReportItem5(cashBean.getPayName(), " ", String.valueOf(cashBean.getPayNum()), " ", "$" + df.format(cashBean.getPayAmount())));
                }
            }
        }

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

        if (voBean != null) {
            /**分析統計*/
            settlementReportItem5s.add(new SettlementReportItem5("==============================================================", "", "", "", ""));
            settlementReportItem5s.add(new SettlementReportItem5("", "", analysisStatisticsText, "", ""));
            //帳單金額總數
            settlementReportItem5s.add(new SettlementReportItem5(totalbillAmountText, " ", " ", " ", "$" + df.format(voBean.getTotamount())));
            //帳單數目 / 平均
            String averagePrice = df.format(voBean.getPrices() / voBean.getNum());
            settlementReportItem5s.add(new SettlementReportItem5(numberBillsOrAverageText, " ", String.valueOf(voBean.getNum()), " ", "$" + averagePrice));
            //人數 / 平均消費
            String averageConsumption = df.format(voBean.getPrices() / voBean.getPerson());
            settlementReportItem5s.add(new SettlementReportItem5(headcountAndAverageConsumptionText, " ", String.valueOf(voBean.getPerson()), " ", "$" + averageConsumption));

            /** 帳單統計*/
            settlementReportItem5s.add(new SettlementReportItem5("==============================================================", "", "", "", ""));
            settlementReportItem5s.add(new SettlementReportItem5("", "", "帳單統計", "", ""));
            settlementReportItem5s.add(new SettlementReportItem5("類別", "帳單", "金額", "平均", "金額%"));
//            settlementReportItem5s.add(new SettlementReportItem5("--------------------------------------------------------------------------------", "", "", "", ""));
            //總計
            String averagePrice2 = df.format(voBean.getTotamount() / voBean.getNum());
            settlementReportItem5s.add(new SettlementReportItem5(totalText, String.valueOf(voBean.getNum()), "$" + df.format(voBean.getTotamount()), "$" + averagePrice2, " "));
        }

        List<SettlementReport.DataBean.AnalysisBean> analysisBeanList = datasBean.getAnalysis();
        if (analysisBeanList != null && analysisBeanList.size() > 0) {

            Map<String, SettlementReport.DataBean.AnalysisBean> analysisBeanMap = getAnalysisBeanMap(analysisBeanList);

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


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

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

        mPresenter.notifyReportItem5Adapter(settlementReportItem5s);
        scrollView.post(new Runnable() {
            @Override
            public void run() {
                scrollView.fullScroll(ScrollView.FOCUS_UP);
            }
        });
    }

    @Override
    public void printRepore() {
        //清機成功，打印
        PrintTransitUtils.getInstance().setPrintView(scrollView);
        CC.obtainBuilder("Component.Print")
                .addParam("type", 4)//清機打印
                .setActionName("printActivity")
                .build()
                .callAsyncCallbackOnMainThread((cc, result) -> {
                    //打印完之後，清除view
                    PrintTransitUtils.getInstance().setPrintView(null);
                    if (mPresenter != null) {
                        mPresenter.getSettlementReport();
                    }
//                    Log.e("error", "是否成功打印：" + result.isSuccess());
//                    if (result.isSuccess()) {
//                        //打印成功
//                        showMessage("打印成功!");
//                    } else {
//                        showMessage("打印失敗!");
//                    }
                });
    }

    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);
        rv_settlement_report_item2.setLayoutManager(linearLayoutManager);
        rv_settlement_report_item2.setItemAnimator(new DefaultItemAnimator());
    }

}
