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

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
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.Nullable;

import com.billy.cc.core.component.CC;
import com.billy.cc.core.component.CCResult;
import com.gingersoft.gsa.cloud.print.PrintExecutor;
import com.gingersoft.gsa.cloud.print.PrintSocketHolder;
import com.gingersoft.gsa.cloud.print.PrinterWriter58mm;
import com.gingersoft.gsa.cloud.print.PrinterWriter80mm;
import com.joe.print.R;
import com.joe.print.mvp.print.SendPrint;
import com.joe.print.mvp.print.TestPrintDataMaker;

import static com.billy.cc.core.component.CCUtil.EXTRA_KEY_CALL_ID;

/**
 * Created by Wyh on 2020/1/7.
 */
public class IpPrintActivity extends Activity implements PrintSocketHolder.OnStateChangedListener, PrintExecutor.OnPrintResultListener, DialogInterface.OnDismissListener {

    private Context mContext;
    private PrintExecutor executor;
    private SendPrint maker;

    private String callId;
    /**
     * -
     * 是否打印成功 true：成功
     */
    private boolean printStatus = false;

    private String ip;
    private Integer port;
    private int paperType = 1;//打印紙類型 1：58mm，2：:80mm
    private int printWidth = 560;//打印出來的內容寬度
    /**
     * -1：打印測試
     * 0：上菜紙
     * 1：印單
     * 2：結賬單
     * 3：廚房單
     */
    private int type = -1;

    private TextView mTvLoadingTip;
    private Dialog mLoadingDialog;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE
                | WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH);
        super.onCreate(savedInstanceState);
        mContext = this;
        getWindow().setBackgroundDrawable(null);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);

        initDialog();
        initIntent();
        callId = getIntent().getStringExtra(EXTRA_KEY_CALL_ID);
        printOrder(this);
    }


    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) {
        //點擊當前頁面任意地方自動關閉
        finish();
        return true;
    }

    private void initIntent() {
        Intent intent = getIntent();
        ip = intent.getStringExtra("ip");
        port = intent.getIntExtra("port", 0);
        paperType = intent.getIntExtra("paperType", 1);
        type = intent.getIntExtra("type", -1);
        if (ip == null || ip.equals("")) {
            ip = "192.168.1.217";
        }
        if (paperType == 1) {
            paperType = PrinterWriter58mm.TYPE_58;
            printWidth = 580 - 20;//兩邊留20的空隙
        } else {
            paperType = PrinterWriter80mm.TYPE_80;
            printWidth = 800 - 20;//兩邊留20的空隙
        }
    }

    public void printOrder(Context context) {
        if (executor == null) {
            executor = new PrintExecutor(ip, port, paperType);
            executor.setOnStateChangedListener(this);
            executor.setOnPrintResultListener(this);
        }
        if (maker == null) {
            maker = new SendPrint(context, 255, printWidth, type);
        }
        executor.setIp(ip, port);
        if (type == -1) {
            executor.doPrinterRequestAsync(new TestPrintDataMaker(context, 380, 255));
        } else {
            executor.doPrinterRequestAsync(maker);
        }
    }

    @Override
    public void onResult(int errorCode) {
        String tip;
        switch (errorCode) {
            case PrintSocketHolder.ERROR_0:
                Log.e("eee", "打印成功");
                tip = "打印成功";
                printStatus = true;
                setLoadingText(tip);
                dismiss();
                break;
            case PrintSocketHolder.ERROR_1:
                Log.e("eee", "生成測試頁面數據失敗");
                tip = "生成打印數據失敗";
                printStatus = false;
                setLoadingText(tip);
                dismiss();
                break;
            case PrintSocketHolder.ERROR_2:
                Log.e("eee", "連接打印機失敗" + System.currentTimeMillis());
            case PrintSocketHolder.ERROR_3:
                Log.e("eee", "獲取輸出流失敗");
                tip = "連接打印機失敗";
                printStatus = false;
                setLoadingText(tip);
                dismiss();
                break;
            case PrintSocketHolder.ERROR_4:
                Log.e("eee", "寫入測試頁面數據失敗");
                tip = "寫入測試頁面數據失敗";
                setLoadingText(tip);
                break;
            case PrintSocketHolder.ERROR_5:
                Log.e("eee", "必要的參數不能為空");
                tip = "必要的參數不能為空";
                setLoadingText(tip);
                break;
        }
    }

    @Override
    public void onStateChanged(int state) {
        String tip = "打印中...";
        switch (state) {
            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;
        }
        setLoadingText(tip);
    }


    private void dismiss() {
        //延遲一秒
        new Handler().postDelayed(() -> {
            if (mLoadingDialog != null) {
                mLoadingDialog.dismiss();
                //判断是否为CC调用打开本页面
                if (callId != null) {
                    CCResult result;
                    if (printStatus) {
                        result = CCResult.success();
                    } else {
                        result = CCResult.error("print error");
                    }
                    //为确保不管登录成功与否都会调用CC.sendCCResult，在onDestroy方法中调用
                    CC.sendCCResult(callId, result);
                }
            }
            finish();
        }, 1500);
    }

    @Override
    public void onDismiss(DialogInterface dialog) {
        finish();
    }
}
