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.InputMethodManager;
import android.widget.EditText;
import android.widget.RadioGroup;
import android.widget.TextView;

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

import com.gingersoft.gsa.cloud.base.application.GsaCloudApplication;
import com.gingersoft.gsa.cloud.base.utils.other.SPUtils;
import com.gingersoft.gsa.cloud.base.utils.other.TextUtil;
import com.gingersoft.gsa.cloud.base.utils.toast.ToastUtils;
import com.gingersoft.gsa.cloud.database.bean.PrinterDeviceBean;
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.gingersoft.gsa.cloud.constans.PrintConstans;
import com.qmuiteam.qmui.widget.QMUITopBar;

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;
    @BindView(R2.id.add_printer_ed_name)
    EditText mEdPrintName;
    @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;//是否是編輯打印機
    private boolean isDefault = 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) {
        isDefault = getIntent().getBooleanExtra("isDefault", false);

//        etPort.setInputType(EditorInfo.TYPE_CLASS_NUMBER);
        String[] ips = new String[4];
//        if (BuildConfig.DEBUG) {
//            ips[0] = "192";
//            ips[1] = "168";
//            ips[2] = "1";
//            ips[3] = "240";
//        }
        //如果不為空，則是編輯打印機，初始化信息
        if (printerDeviceBean != null) {
            mEdPrintName.setText(String.valueOf(printerDeviceBean.getName()));
            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);
        ToastUtils.show(mContext, 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) {
            if (mEdPrintName.getText().toString().contains("/")) {
                ToastUtils.show(mContext, "打印機名稱禁止帶/字符");
                return;
            }
            //保存打印機信息
            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;
            }

            String port = etPort.getText().toString();
            PrinterDeviceBean deviceBean;
            if (TextUtil.isEmptyOrNullOrUndefined(port)) {
                deviceBean = new PrinterDeviceBean(mEdPrintName.getText().toString().trim(), 0, GsaCloudApplication.getRestaurantId(mContext), ipAddress.substring(0, ipAddress.lastIndexOf(".")), null, paperType);
            } else {
                deviceBean = new PrinterDeviceBean(mEdPrintName.getText().toString().trim(), 0, GsaCloudApplication.getRestaurantId(mContext), ipAddress.substring(0, ipAddress.lastIndexOf(".")), Integer.parseInt(port), paperType);
            }

            //添加打印機
            if (v.getId() == R.id.printer_add) {
                if (isEditPrinter && printerDeviceBean != null) {
                    deviceBean.setRestaurantId(null);
                    deviceBean.setId(printerDeviceBean.getId());
                    mPresenter.updatePrinterInfo(deviceBean);
                } else {
                    mPresenter.addPrinter(deviceBean);
                }
            } else if (v.getId() == R.id.print_test) {
                //打印測試
                Intent intent = new Intent(mContext, PrintActivity.class);
                intent.putExtra("deviceBean", deviceBean);
                startActivity(intent);
            }
        }
    }

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

    @Override
    public void addPrinterSuccess(PrinterDeviceBean printerDeviceBean) {
        //添加或編輯打印機成功
        showMessage("保存成功");
        Intent data = new Intent();
        data.putExtra("printDevice", printerDeviceBean);
        setResult(PrintActivity.ADD_PRINT_CODE, data);
        finish();
    }

    @Override
    public void updatePrinterSuccess(PrinterDeviceBean item) {
        //修改打印機成功，如果這個打印機是用戶設置的默認打印機，則需要更新信息
        if (isDefault) {
            SPUtils.put(mContext, PrintConstans.DEFAULT_PRINT_IP, item.getIp());
            SPUtils.put(mContext, PrintConstans.DEFAULT_PRINT_PORT, item.getPort());
            SPUtils.put(mContext, PrintConstans.DEFAULT_PRINT_PAPER, item.getType());
        }
    }


    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) {

        }

    }
}
