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

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.gingersoft.gsa.cloud.base.application.GsaCloudApplication;
import com.gingersoft.gsa.cloud.database.bean.PrinterDeviceBean;
import com.gingersoft.gsa.cloud.ui.view.MyEditText;
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.R2;
import com.joe.print.di.component.DaggerPrinterAddComponent;
import com.joe.print.mvp.contract.PrinterAddContract;
import com.joe.print.mvp.presenter.PrinterAddPresenter;
import com.qmuiteam.qmui.widget.QMUITopBar;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import butterknife.BindView;
import butterknife.BindViews;
import butterknife.OnClick;

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


/**
 * 新增或編輯打印機
 */
public class PrinterAddActivity extends BaseActivity<PrinterAddPresenter> implements PrinterAddContract.View, View.OnClickListener {

    //    EditText ipEdit1, ipEdit2, ipEdit3, ipEdit4;
    @BindViews({R2.id.ip_edit_1, R2.id.ip_edit_2, R2.id.ip_edit_3, R2.id.ip_edit_4})
    EditText[] ipEdits = new EditText[4];
    @BindView(R2.id.add_printer_topbar)
    QMUITopBar topBar;
    @BindView(R2.id.add_printer_ed_port)
    EditText etPort;
    @BindView(R2.id.print_test)
    TextView printTest;
    @BindView(R2.id.printer_type)
    RadioGroup rgPaperType;

    private PrinterDeviceBean printerDeviceBean;
    private boolean isEditPrinter = false;//是否是編輯打印機

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

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

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {
//        etPort.setInputType(EditorInfo.TYPE_CLASS_NUMBER);
        String[] ips = new String[4];
        //如果不為空，則是編輯打印機，初始化信息
        if (printerDeviceBean != null) {
            ips = printerDeviceBean.getIp().split("[.]");
            etPort.setText(printerDeviceBean.getPort() + "");
            if (printerDeviceBean.getType() == 1) {
                rgPaperType.check(R.id.print_paper_size_58);
            } else {
                rgPaperType.check(R.id.print_paper_size_88);
            }
        }
        //添加監聽
        for (int i = 0; i < ipEdits.length; i++) {
            MyTextWatcher myTextWatchers = new MyTextWatcher(ipEdits[i]);
            ipEdits[i].addTextChangedListener(myTextWatchers);
            if (ips.length > i) {
                ipEdits[i].setText(ips[i]);
            }
        }
    }

    @Override
    public void initIntent() {
        printerDeviceBean = (PrinterDeviceBean) getIntent().getSerializableExtra("printerInfo");
        isEditPrinter = printerDeviceBean != null;
    }

    @Override
    public void initTopBar() {
        String title = "新增打印機";
        if (isEditPrinter) {
            title = "編輯打印機";
        }
        topBar.setTitle(title);
        topBar.setBackgroundColor(getResources().getColor(R.color.theme_color));
        topBar.addLeftImageButton(R.drawable.icon_return, R.id.iv_left_back).setOnClickListener(v -> finish());
        topBar.addRightTextButton("保存", R.id.printer_add).setOnClickListener(this);
    }

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

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

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

    @OnClick({R2.id.print_test})
    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.printer_add || v.getId() == R.id.print_test) {

            //保存打印機信息
            StringBuilder ipAddress = new StringBuilder();
            for (EditText editText : ipEdits) {
                if (editText.getText() == null || editText.getText().toString().equals("")) {
                    showMessage("請輸入完整的IP地址");
                    return;
                }
                ipAddress.append(editText.getText());
                ipAddress.append(".");
            }
            if (etPort.getText() == null || etPort.getText().toString().equals("")) {
                showMessage("請輸入端口號");
                return;
            }
            hideKeyBoard();

            int paperType = 1;//打印紙類型
            if (rgPaperType.getCheckedRadioButtonId() != R.id.print_paper_size_58) {
                paperType = 2;
            }
            //添加打印機
            if (v.getId() == R.id.printer_add) {
                if (isEditPrinter && printerDeviceBean != null) {
                    mPresenter.updatePrinterInfo(printerDeviceBean.getId(), GsaCloudApplication.getRestaurantId(mContext), ipAddress.substring(0, ipAddress.lastIndexOf(".")), etPort.getText().toString(), paperType);
                } else {
                    mPresenter.addPrinter(GsaCloudApplication.getRestaurantId(mContext), ipAddress.substring(0, ipAddress.lastIndexOf(".")), etPort.getText().toString(), paperType);
                }
            } else if(v.getId() == R.id.print_test){
                //打印測試
                Intent intent = new Intent(mContext, OldPrintActivity.class);
                intent.putExtra("ip", ipAddress.substring(0, ipAddress.lastIndexOf(".")));
                intent.putExtra("port", etPort.getText().toString());
                intent.putExtra("paperType", paperType);
                startActivity(intent);
            }
        }
    }

    private void hideKeyBoard() {
        //收起鍵盤
        InputMethodManager imm = (InputMethodManager) mContext.getSystemService(Context.INPUT_METHOD_SERVICE);
        // 隐藏软键盘
        imm.hideSoftInputFromWindow(getWindow().getDecorView().getWindowToken(), 0);
    }

    @Override
    public void addPrinterSuccess() {
        //添加或編輯打印機成功
        showMessage("保存成功");
        finish();
    }


    class MyTextWatcher implements TextWatcher {
        public EditText mEditText;

        public MyTextWatcher(EditText mEditText) {
            super();
            this.mEditText = mEditText;
        }

        @Override
        public void afterTextChanged(Editable s) {
            // TODO Auto-generated method stub
            if (s.length() == 3) {
                if (Integer.parseInt(mEditText.getEditableText().toString()) > 255) {
                    mEditText.setText("255");
                }
                if (this.mEditText == ipEdits[0]) {
                    ipEdits[1].requestFocus();

                } else if (this.mEditText == ipEdits[1]) {
                    ipEdits[2].requestFocus();

                } else if (this.mEditText == ipEdits[2]) {
                    ipEdits[3].requestFocus();
                }
                if (this.mEditText == ipEdits[3]) {
                    ipEdits[3].setSelection(3);
                }
            }
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

    }
}
