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

import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

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.utils.toast.ToastUtils;
import com.gingersoft.gsa.cloud.database.bean.PrinterDeviceBean;
import com.gingersoft.gsa.cloud.print.PrintSocketHolder;
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.PrintListener;
import com.joe.print.mvp.print.PrinterInIt;

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

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, PrintListener {

    public final static int ADD_PRINT_CODE = 1001;//添加打印機回調
    public final static int DIMISS_LOADING = 1002;//關閉加載窗
    public final static int FINISH = 1003;//關閉頁面
    public final static int ADD_PRINT_DEVICE = 1004;//添加打印機

    private String callId;
    private PrinterInIt printerInIt;

    private Dialog mLoadingDialog;
    private TextView mTvLoadingTip;

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

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


    @Override
    public void initData(@Nullable Bundle savedInstanceState) {
        callId = CCUtil.getNavigateCallId(this);
        //獲取打印類型，根據打印類型生成對應的bitmap
        /**
         * 0：上菜紙
         * 1：印單
         * 2：結賬單
         * 3：廚房單
         * 4：清機報表
         */
        int type = CCUtil.getNavigateParam(this, "type", -1);

        initDialog();

        PrinterDeviceBean deviceBean = (PrinterDeviceBean) getIntent().getSerializableExtra("deviceBean");

        if (type != PrinterInIt.PRINT_TEST) {
            //不是测试才去获取打印机列表，获取到打印机列表之后就进行打印
            mPresenter.getPrinterList(GsaCloudApplication.getRestaurantId(mContext));
        }

        printerInIt = PrinterInIt.getPrinterByType(type);
        if (printerInIt != null) {
            printerInIt.setmContext(mContext).setPrintListener(this);
        }
        if (type == PrinterInIt.PRINT_TEST) {
            if (deviceBean != null) {
                printerInIt.ipDevicePrint(deviceBean, printerInIt.getPrintBitmap(mContext).get(""));
            } else {
                ToastUtils.show(mContext, "测试失败");
            }
        }
    }

    private void initDialog() {
        try {
            View view = LayoutInflater.from(mContext).inflate(R.layout.ui_dialog_loading, null);
            mTvLoadingTip = view.findViewById(R.id.tv_loading_dialog_text);
            mLoadingDialog = new Dialog(mContext, R.style.ui_loading_dialog);
            mLoadingDialog.setCancelable(true);
            mLoadingDialog.setCanceledOnTouchOutside(false);
            Window window = mLoadingDialog.getWindow();
            window.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
//            window.getDecorView().setBackgroundResource(android.R.color.transparent);

            mLoadingDialog.setContentView(view, new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT));
            mLoadingDialog.show();
//            mLoadingDialog.setOnDismissListener(dialog -> dismiss());
            setLoadingText("加載中...");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void setLoadingText(String tip) {
        if (mLoadingDialog != null && mLoadingDialog.isShowing()) {
            mTvLoadingTip.setText(tip);
        }
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        //doSomeTing，點擊當前頁面任意地方自動關閉
        finish();
        return true;
    }

    /**
     * 打印失敗
     */
    @Override
    public void printFile() {
        CC.sendCCResult(callId, CCResult.error("print error"));
        finish();
        Log.e("eee", "打印失敗，關閉頁面");
    }

    @Override
    public void printStateChanged(int state) {
        String tip = "加載中...";
        switch (state) {
            case PrintSocketHolder.ERROR_0:
                Log.e("eee", "打印成功");
                tip = "打印成功";
                break;
            case PrintSocketHolder.ERROR_1:
                Log.e("eee", "生成測試頁面數據失敗");
                tip = "生成打印數據失敗";
                break;
            case PrintSocketHolder.ERROR_2:
                Log.e("eee", "連接打印機失敗" + System.currentTimeMillis());
            case PrintSocketHolder.ERROR_3:
                Log.e("eee", "獲取輸出流失敗");
                tip = "連接打印機失敗";
                break;
            case PrintSocketHolder.ERROR_4:
                Log.e("eee", "寫入測試頁面數據失敗");
                tip = "寫入測試頁面數據失敗";
                break;
            case PrintSocketHolder.ERROR_5:
                Log.e("eee", "必要的參數不能為空");
                tip = "必要的參數不能為空";
                break;
            case PrintSocketHolder.STATE_0:
                Log.e("eee", "生成測試頁數據");
            case PrintSocketHolder.STATE_1:
                Log.e("eee", "開始創建連接");
                tip = "開始創建連接";
                break;
            case PrintSocketHolder.STATE_2:
                Log.e("eee", "創建連接成功，開始發送數據");
                tip = "創建連接成功，開始發送數據";
                break;
            case PrintSocketHolder.STATE_3:
                Log.e("eee", "開始寫入數據");
                tip = "開始寫入數據";
                break;
            case PrintSocketHolder.STATE_4:
                Log.e("eee", "關閉中");
                tip = "關閉中";
                break;
            case DIMISS_LOADING:
                if (mLoadingDialog != null) {
                    mLoadingDialog.dismiss();
                }
                break;
            case FINISH:
                finish();
                printSuccess();
                break;
            case ADD_PRINT_DEVICE:
                addPrintDevice();
                break;
        }
        setLoadingText(tip);
    }

    /**
     * 打印成功
     */
    @Override
    public void printSuccess() {
        CC.sendCCResult(callId, CCResult.success());
        finish();
        Log.e("eee", "打印成功，關閉頁面");
    }

    @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);
        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(List<PrinterDeviceBean> deviceBeans) {
        if (deviceBeans != null && deviceBeans.size() > 0) {
            printerInIt.print(deviceBeans);
        } else {
            //沒有配置打印機
            addPrintDevice();
        }
    }

    private void addPrintDevice() {
        ToastUtils.show(mContext, "沒有打印機，請添加");
        startActivityForResult(new Intent(mContext, PrinterAddActivity.class), ADD_PRINT_CODE);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == ADD_PRINT_CODE && resultCode == PrintActivity.ADD_PRINT_CODE) {
            //添加打印機成功，
            if (data != null && data.getSerializableExtra("printDevice") != null) {
                List<PrinterDeviceBean> printerDeviceBeans = new ArrayList<>();
                printerDeviceBeans.add((PrinterDeviceBean) data.getSerializableExtra("printDevice"));
                printerInIt.print(printerDeviceBeans);
            } else {
                ToastUtils.show(mContext, "未獲取到打印機");
                printFile();
            }
        } else {
            ToastUtils.show(mContext, "未獲取到打印機");
            printFile();
        }
    }

    @Override
    public void onDismiss(DialogInterface dialog) {

    }

}
