package com.joe.print.mvp.ui.activity;

import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Build;
import android.os.Bundle;
import android.os.IBinder;
import android.os.Looper;
import android.os.RemoteException;

import com.billy.cc.core.component.CC;
import com.billy.cc.core.component.CCResult;
import com.billy.cc.core.component.CCUtil;
import com.gingersoft.gsa.cloud.base.application.GsaCloudApplication;
import com.gingersoft.gsa.cloud.base.common.bean.PrinterManger.PrinterManager;
import com.gingersoft.gsa.cloud.base.utils.PrintUtils;
import com.gingersoft.gsa.cloud.base.utils.constans.Constans;
import com.gingersoft.gsa.cloud.base.utils.other.SPUtils;
import com.gingersoft.gsa.cloud.base.utils.toast.ToastUtils;
import com.gingersoft.gsa.cloud.base.utils.view.ImageUtils;
import com.gingersoft.gsa.cloud.base.widget.DialogUtils;
import com.gingersoft.gsa.cloud.database.bean.PrinterDeviceBean;
import com.hyweb.n5.lib.constant.PrinterConstant;
import com.hyweb.n5.lib.exception.NoInitPrinterException;
import com.hyweb.n5.lib.util.PrinterUtil;
import com.hyweb.n5.server.aidl.IOnPrintCallback;
import com.jess.arms.base.BaseActivity;
import com.jess.arms.di.component.AppComponent;
import com.jess.arms.utils.ArmsUtils;
import com.joe.print.R;
import com.joe.print.di.component.DaggerPrintComponent;
import com.joe.print.mvp.contract.PrintContract;
import com.joe.print.mvp.presenter.PrintPresenter;
import com.joe.print.mvp.print.SunMiPrint;
import com.joe.print.mvp.ui.adapter.DialogPrinterListAdapter;
import com.yanzhenjie.recyclerview.widget.DefaultItemDecoration;

import java.util.List;
import java.util.Objects;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import static com.jess.arms.utils.Preconditions.checkNotNull;


/**
 * ================================================
 * Description:
 * <p>
 * Created by MVPArmsTemplate on 01/18/2020 14:57
 * <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>
 * ================================================
 * 透明activity
 * 打印入口
 * 選擇打印方式
 * ----本機打印
 * ----調用本機打印方法
 * ----網絡打印
 * ----获取網絡打印機列表
 */
public class PrintActivity extends BaseActivity<PrintPresenter> implements PrintContract.View, DialogInterface.OnDismissListener {

    private int dialogCount = 0;
    private DialogUtils selectDialog;
    /**
     * 商米:V2、V2_PRO   N5:N5
     */
    private String mV2 = "V2,V2_PRO";
    private String mN5 = "N5";
    /**
     * 0：上菜紙
     * 1：印單
     * 2：結賬單
     * 3：廚房單
     */
    private int type = -1;

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

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

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {
        type = CCUtil.getNavigateParam(this, "type", 1001);
        List<Bitmap> bitmaps = PrintUtils.getPrintBitmap(mContext, type, 500);
        if (bitmaps.size() <= 0) {
            printFile();
            finish();
            return;
        }
        if (Objects.equals(SPUtils.get(mContext, Constans.DEFAULT_PRINT_METHOD, ""), "")) {
            //如果沒有默認打印位置
            noDefaultPrintMethod(bitmaps);
        } else if (Objects.equals(SPUtils.get(mContext, Constans.DEFAULT_PRINT_METHOD, ""), Constans.LOCAL_PRINT)) {
            //默認打印方式為本地，進行本地打印
            for (int i = 0; i < bitmaps.size(); i++) {
                locationPrint(bitmaps.get(i));
            }
        } else if (Objects.equals(SPUtils.get(mContext, Constans.DEFAULT_PRINT_METHOD, ""), Constans.IP_PRINT)) {
            //默認打印方式為ip打印，調用ip打印方法
            ipPrint();
        }
    }

    private void noDefaultPrintMethod(List<Bitmap> bitmaps) {
        selectDialog = new DialogUtils(mContext, R.layout.print_dialog_select_device) {
            @Override
            public void initLayout(ViewHepler hepler, Dialog dialog) {
                dialogCount++;
                hepler.setViewClick(R.id.local_print, v -> {
                    for (int i = 0; i < bitmaps.size(); i++) {
                        locationPrint(bitmaps.get(i));
                    }
                    //修改默認打印方式為本地
                    SPUtils.put(mContext, Constans.DEFAULT_PRINT_METHOD, Constans.LOCAL_PRINT);
                    dialog.dismiss();
                });
                hepler.setViewClick(R.id.internet_print, v -> {
                    //修改默認打印方式為IP打印
                    SPUtils.put(mContext, Constans.DEFAULT_PRINT_METHOD, Constans.LOCAL_PRINT);
                    ipPrint();
                });
            }
        }.createDialogView().show().setOnDismissListener(this);
    }

    /**
     * IP打印
     */
    private void ipPrint() {
        if (PrinterManager.getPrinterManager().getDeviceBeans() != null
                && PrinterManager.getPrinterManager().getDeviceBeans().size() > 0) {
            //如果本地保存有打印設備
            showPrinterList();
        } else {
            //網絡獲取打印設備
            mPresenter.getPrinterList(GsaCloudApplication.getRestaurantId(mContext));
        }
    }

    /**
     * 本地打印
     */
    private void locationPrint(Bitmap bitmap) {
        //本機打印
        if (bitmap == null) {
            ToastUtils.show(mContext, "未獲取到打印內容");
            printFile();
            return;
        }
        String model = Build.MODEL;
        if (mV2.contains(model)) {
            //商米打印
            boolean isSuccess = SunMiPrint.printBitmap(mContext, bitmap);
            if (isSuccess) {
                ToastUtils.show(mContext, "商米打印機連接成功");
                printSuccess();
            } else {
                ToastUtils.show(mContext, "商米打印機連接失敗");
                printFile();
            }
        } else if (mN5.contains(model)) {
            //N5打印
            try {
                PrinterUtil.initPrinter(mContext);
                PrinterUtil.appendImage(bitmap, PrinterConstant.ALIGN_CENTER);
                PrinterUtil.startPrint(true, new IOnPrintCallback() {
                    @Override
                    public void onPrintResult(int i) {
                        Looper.prepare();
                        if (i == 0) {
                            //打印成功
                            ToastUtils.show(mContext, "N5打印結果：成功");
                            printSuccess();
                        } else {
                            //打印失敗
                            ToastUtils.show(mContext, "N5打印結果：失敗");
                            printFile();
                        }
                    }

                    @Override
                    public IBinder asBinder() {
                        return null;
                    }
                });
            } catch (RemoteException | NoInitPrinterException e) {
                e.printStackTrace();
                printFile();
            }
        } else {
            ToastUtils.show(mContext, "暫不支持本機型打印");
            printFile();
        }
    }

    /**
     * 打印失敗
     */
    private void printFile() {
        String callId = CCUtil.getNavigateCallId(this);
        CC.sendCCResult(callId, CCResult.error("print error"));
        finish();
    }

    /**
     * 打印成功
     */
    private void printSuccess() {
        String callId = CCUtil.getNavigateCallId(this);
        CC.sendCCResult(callId, CCResult.success());
        finish();
    }

    //初始化打印內容
    public Bitmap initPrintBitmap(int width) {
        Bitmap bitmap = getIntent().getParcelableExtra("bitmap");
        if (bitmap == null) {
            return null;
        }
        return ImageUtils.zoomDrawable(bitmap, width, bitmap.getHeight());
    }

    @Override
    public void initIntent() {

    }

    @Override
    public void initTopBar() {

    }

    @Override
    public void initLanguage() {

    }

    @Override
    public void initLayoutParams() {

    }

    @Override
    public void initLayoutVisible() {

    }

    @Override
    public void showLoading(String message) {

    }

    @Override
    public void hideLoading() {

    }

    @Override
    public void showMessage(@NonNull String message) {
        checkNotNull(message);
//        ArmsUtils.snackbarText(message);
        ToastUtils.show(mContext, message);
    }

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

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

    @Override
    public void showPrinterList() {
        if (selectDialog != null && selectDialog.isShowing()) {
            selectDialog.dismiss();
        }
        //有打印機，彈出彈窗，選擇打印機
        new DialogUtils(mContext, R.layout.print_dialog_internet_list) {
            @Override
            public void initLayout(ViewHepler hepler, Dialog dialog) {
                dialogCount++;
                RecyclerView mRvPrintList = hepler.getView(R.id.rv_print_list);
                List<PrinterDeviceBean> deviceBeans = PrinterManager.getPrinterManager().getDeviceBeans();
                DialogPrinterListAdapter printListAdapter = new DialogPrinterListAdapter(deviceBeans, mContext);
                mRvPrintList.setLayoutManager(new LinearLayoutManager(mContext));
                //分割线
                mRvPrintList.addItemDecoration(new DefaultItemDecoration(ContextCompat.getColor(mContext, R.color.line_color)));
                mRvPrintList.setAdapter(printListAdapter);
                printListAdapter.setOnItemClickListener((adapter, view, position) -> {
                    Intent intent = new Intent(mContext, OldPrintActivity.class);
                    intent.putExtra("ip", deviceBeans.get(position).getIp());
                    intent.putExtra("port", deviceBeans.get(position).getPort());
                    intent.putExtra("paperType", deviceBeans.get(position).getType());
                    intent.putExtra("type", type);
                    startActivity(intent);
                });
                dialog.setOnDismissListener(dialog1 -> finish());
            }
        }
//        .setWidth(ArmsUtils.getScreenHeidth(mContext))
                .setHeight(ArmsUtils.getScreenHeidth(mContext) / 2)
                .createDialogView()
                .show();
    }

    @Override
    public void onDismiss(DialogInterface dialog) {
        dialogCount--;
        if (dialogCount <= 0) {
            finish();
        }
    }
}
