package com.gingersoft.gsa.cloud.table.mvp.action.table;

import android.app.Activity;
import android.text.TextUtils;

import com.billy.cc.core.component.CC;
import com.gingersoft.gsa.cloud.app.GsaCloudApplication;
import com.gingersoft.gsa.cloud.common.bean.BaseResult;
import com.gingersoft.gsa.cloud.common.constans.HttpsConstans;
import com.gingersoft.gsa.cloud.common.constans.PrintConstans;
import com.gingersoft.gsa.cloud.print.bean.PrintQRCodeContent;
import com.gingersoft.gsa.cloud.common.core.restaurant.RestaurantInfoManager;
import com.gingersoft.gsa.cloud.common.core.table.TableBean;
import com.gingersoft.gsa.cloud.common.core.user.UserContext;
import com.gingersoft.gsa.cloud.common.utils.JsonUtils;
import com.gingersoft.gsa.cloud.common.utils.time.TimeUtils;
import com.gingersoft.gsa.cloud.component.ComponentName;
import com.gingersoft.gsa.cloud.table.mvp.action.OnNetworkCallbackListener;
import com.gingersoft.gsa.cloud.table.mvp.model.bean.FoodSummary;
import com.gingersoft.gsa.cloud.table.mvp.model.bean.response.PrintQRCodeResponse;
import com.gingersoft.gsa.cloud.table.mvp.presenter.TablePresenter;
import com.gingersoft.gsa.cloud.table.mvp.ui.widget.SkyOrderDialog;
import com.gingersoft.gsa.cloud.ui.widget.dialog.BaseRetryDialog;
import com.gingersoft.gsa.cloud.ui.widget.dialog.DialogAnimationListener;
import com.jess.arms.utils.ArmsUtils;

import java.util.ArrayList;
import java.util.List;


/**
 * 作者：ELEGANT_BIN
 * 版本：1.6.0
 * 创建日期：2020-09-23
 * 修订历史：2020-09-23
 * 描述：餐檯模式-打印skyorder碼{@link com.gingersoft.gsa.cloud.table.mvp.ui.activity.TableActivity}
 */
public class PrintSkyorderAction extends TableAction {

    private TablePresenter mTablePresenter;
    private SkyOrderDialog mSkyOrderDialog;

    private static final byte PRINT_type = 2;

    public PrintSkyorderAction(Activity context, TablePresenter tablePresenter) {
        super(context, "打印skyorder", "請選擇檯號", "");
        this.mTablePresenter = tablePresenter;
    }

    @Override
    public void action(TableBean.DataBean dataBean) {
        showSkyOrderDialog(dataBean);
    }

    @Override
    public boolean filterTableCondition(TableBean.DataBean dataBean) {
        return true;
    }

    @Override
    public void destroy() {
        mTablePresenter = null;
        if (mSkyOrderDialog != null) {
            mSkyOrderDialog.dismiss();
            mSkyOrderDialog = null;
        }
    }

    public void showSkyOrderDialog(TableBean.DataBean tableBean) {
        mSkyOrderDialog = new SkyOrderDialog(mContext).build();
        mSkyOrderDialog.setTvTableName("餐檯:" + tableBean.getTableName());
        mSkyOrderDialog.setDialogAnimationListener(new DialogAnimationListener() {
            @Override
            public void showAnimEnd() {
                //防止加載出現卡頓 在動畫結束後再做邏輯處理
                getFoodSummarys();
                mSkyOrderDialog.addMealMinutes(createMealMinutes());
            }

            @Override
            public void dismissAnimEnd() {

            }
        });
        mSkyOrderDialog.setOnRetryListener(new BaseRetryDialog.OnRetryListener() {
            @Override
            public void onRetryClick() {
                getFoodSummarys();
            }
        });
        mSkyOrderDialog.setCallbackListener(new SkyOrderDialog.OnCallbackListener() {

            @Override
            public void onPrint(FoodSummary foodSummary, int person, String endTime) {
                mTablePresenter.addScan(RestaurantInfoManager.newInstance().getGsPosShopId(), tableBean.getId(), tableBean.getTableNumber(), tableBean.getTableName(),
                        person, UserContext.newInstance().getMemberName(), endTime, foodSummary.getId(), new OnNetworkCallbackListener<BaseResult>() {

                            @Override
                            public void onResult(BaseResult resultBean) {
                                if (resultBean.isSuccess()) {

                                    PrintQRCodeResponse printQRCodeResponse = JsonUtils.parseObject(resultBean.getData(), PrintQRCodeResponse.class);

                                    String printTime = TimeUtils.getStringByFormat(System.currentTimeMillis(), TimeUtils.DEFAULT_DATE_FORMAT_YMDHM);

                                    String printTopInfo = GsaCloudApplication.functionConfiguration.getSkyQRCodePrintTopInfoVaule();
                                    String printBottomInfo = GsaCloudApplication.functionConfiguration.getSkyQRCodePrintBottomInfoVaule();

                                    String QR = "\"" + printQRCodeResponse.getQrcode() + "\"";
                                    String QRCodeContent = HttpsConstans.PRINT_SKY_QRCODE_ADDRESS + "{\"type\":" + PRINT_type + ",\"QR\":" + QR + "}";
                                    QRCodeContent = QRCodeContent.replace("WMP0", "WMP" + printQRCodeResponse.getIsWeChatMiniProgram());

                                    PrintQRCodeContent printQRCodeBean = new PrintQRCodeContent();
                                    printQRCodeBean.setPrintTableName("餐檯:" + tableBean.getTableName());
                                    printQRCodeBean.setPrintTopInfo(printTopInfo);
                                    printQRCodeBean.setPrintBottonInfo(printBottomInfo);
                                    printQRCodeBean.setPrintQrcode(QRCodeContent);
                                    printQRCodeBean.setPrintTime("打印時間:" + printTime);
                                    printQRCodeBean.setPrintPeopleNum("人數:" + person);
                                    printQRCodeBean.setPrintMealEndTime("交檯時間:" + endTime);

                                    CC.obtainBuilder(ComponentName.COMPONENT_PRINT)
                                            .setActionName("printActivity")
                                            .addParam(PrintConstans.PRINT_CONTENT, printQRCodeBean)
                                            .addParam(PrintConstans.PRINT_TYPE, PrintConstans.PRINT_SKYORDER_QRCODE)
                                            .build()
                                            .callAsyncCallbackOnMainThread((cc, result) -> {
                                                if (result.isSuccess()) {
                                                    printSkyorderSuccess();
                                                } else {
                                                    if (!TextUtils.isEmpty(result.getErrorMessage())) {
                                                        ArmsUtils.makeText(mContext, result.getErrorMessage());
                                                    } else {
                                                        ArmsUtils.makeText(mContext, "打印失敗");
                                                    }
                                                }
                                                mSkyOrderDialog.dismiss();
                                            });
                                } else {
                                    ArmsUtils.makeText(mContext, resultBean.getErrMsg());
                                }
                            }

                            @Override
                            public void onError(Throwable t) {
                                ArmsUtils.makeText(mContext, "打印失敗:" + t.getMessage());
                            }

                            @Override
                            public void onComplete() {

                            }
                        });
            }
        });
        mSkyOrderDialog.show();
    }

    private List<Integer> createMealMinutes() {
        String QRCodeTimeSlice = GsaCloudApplication.functionConfiguration.getQRCodeTimeSliceVaule();
        if (!TextUtils.isEmpty(QRCodeTimeSlice)) {
            List<Integer> mMealMinute = new ArrayList<>();
            String[] timeSlice = QRCodeTimeSlice.split(",");
            for (String time : timeSlice) {
                mMealMinute.add(Integer.parseInt(time));
            }
            return mMealMinute;
        }
        return null;
    }

    private void getFoodSummarys() {
        mTablePresenter.getFoodSummarys(new OnNetworkCallbackListener<BaseResult>() {

            @Override
            public void onResult(BaseResult result) {
                if (result.isSuccess()) {
                    if (result.getData() != null) {
                        List<FoodSummary> foodSummaryList = JsonUtils.parseArray(result.getData(), FoodSummary.class);
                        if (foodSummaryList.size() > 0) {
                            mSkyOrderDialog.updateFoodSummaryList(foodSummaryList);
                        } else {
                            mSkyOrderDialog.showEmptyView(true, 0, null);
                        }
                    } else {
                        mSkyOrderDialog.showEmptyView(true, 0, null);
                    }
                } else {
                    mSkyOrderDialog.showEmptyView(false, 0, null);
                }
                mSkyOrderDialog.setProgressVisibility(false);
            }

            @Override
            public void onError(Throwable t) {
                mSkyOrderDialog.showEmptyView(false, 0, t);
                mSkyOrderDialog.setProgressVisibility(false);
            }

            @Override
            public void onComplete() {

            }
        });
        mSkyOrderDialog.setProgressVisibility(true);
    }
}
