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

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.Switch;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.billy.cc.core.component.CC;
import com.gingersoft.gsa.cloud.base.application.GsaCloudApplication;
import com.gingersoft.gsa.cloud.base.utils.other.TextUtil;
import com.gingersoft.gsa.cloud.base.utils.toast.ToastUtils;
import com.gingersoft.gsa.cloud.base.widget.DialogUtils;
import com.gingersoft.gsa.cloud.constans.PrintConstans;
import com.gingersoft.gsa.cloud.database.bean.PrintModelBean;
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.joe.print.mvp.print.PrinterRoot;
import com.joe.print.mvp.ui.adapter.SelectPrintAdapter;
import com.joe.print.mvp.ui.view.WheelView;
import com.qmuiteam.qmui.widget.QMUITopBar;

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

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.switch_set_default)
    Switch mSwitchDefalute;
    @BindView(R2.id.tv_print_fail_one)
    TextView mTvFailNameOne;
    @BindView(R2.id.tv_print_fail_two)
    TextView mTvFailNameTwo;
    @BindView(R2.id.print_device_name)
    TextView mTvModel;

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

    private int oneFailPosition = -1, twoFailPosition = -1;
    private List<PrintModelBean> printModelBeans;

    private List<String> printModelLabels;

    private int modelPosition = -1;

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

        String[] ips = new String[4];
        //如果不為空，則是編輯打印機，初始化信息
        if (printerDeviceBean != null) {
            mEdPrintName.setText(String.valueOf(printerDeviceBean.getName()));
            ips = printerDeviceBean.getIp().split("[.]");
            etPort.setText(printerDeviceBean.getPort() + "");

            if (printerDeviceBean.getPrinterName() != null) {
                mTvModel.setTextColor(getResources().getColor(R.color.color_3c));
                mTvModel.setText(printerDeviceBean.getPrinterName());
                if (printerDeviceBean.getModel() != null) {
                    mTvModel.setText(printerDeviceBean.getPrinterName() + "\u3000" + printerDeviceBean.getModel());
                }
            }
            mSwitchDefalute.setChecked(printerDeviceBean.getType() == 2);
            if (devicess != null && devicess.size() > 0) {
                if (printerDeviceBean.getFlyPrinterDeviceId() != null && printerDeviceBean.getFlyPrinterDeviceId() != 0) {
                    //有飛單
                    for (int i = 0; i < devicess.size(); i++) {
                        if (devicess.get(i).getId() == printerDeviceBean.getFlyPrinterDeviceId()) {
                            mTvFailNameOne.setText(devicess.get(i).getName());
                            oneFailPosition = i;
                            mTvFailNameOne.setTextColor(getResources().getColor(R.color.color_3c));
                        }
                    }
                }
                if (printerDeviceBean.getFlyPrinterDeviceId2() != null && printerDeviceBean.getFlyPrinterDeviceId2() != 0) {
                    //有飛單2222
                    for (int i = 0; i < devicess.size(); i++) {
                        if (devicess.get(i).getId() == printerDeviceBean.getFlyPrinterDeviceId2()) {
                            mTvFailNameTwo.setText(devicess.get(i).getName());
                            twoFailPosition = i;
                            mTvFailNameTwo.setTextColor(getResources().getColor(R.color.color_3c));
                        }
                    }
                }
            }
        }
        //添加監聽
        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() {
        int position = getIntent().getIntExtra("printer_position", -1);
        devicess = (List<PrinterDeviceBean>) getIntent().getSerializableExtra("printList");
        printModelBeans = (List<PrintModelBean>) getIntent().getSerializableExtra("printModelList");

        if (devicess != null && position != -1) {
            printerDeviceBean = devicess.get(position);
            if (printerDeviceBean != null) {
                devicess.remove(position);//從打印機列表中移除掉當前打印機，選擇飛單時不能選擇當前打印機
            }
        }
        isEditPrinter = printerDeviceBean != null;

        if (printModelBeans != null) {
            printModelLabels = new ArrayList<>();
            for (int i = 0; i < printModelBeans.size(); i++) {
                printModelLabels.add(printModelBeans.get(i).getPrinterName() + "\u3000" + printModelBeans.get(i).getModel());
                if (printerDeviceBean != null && printerDeviceBean.getPrinterModelId() == printModelBeans.get(i).getId()) {
                    modelPosition = i;
                }
            }
        }
    }

    @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.print_test).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.printer_add, R2.id.layout_select_fail_one, R2.id.layout_select_fail_two, R2.id.layout_print_device})
    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.printer_add || id == R.id.print_test) {
            addOrTestPrint(v);
        } else if (id == R.id.layout_select_fail_one || id == R.id.layout_select_fail_two) {
            if (devicess == null || devicess.size() <= 0) {
                showMessage("沒有其他打印機");
                return;
            }
            selectFailPrint(id);
        } else if (id == R.id.layout_print_device) {
            if (printModelBeans == null || printModelBeans.size() <= 0) {
                ToastUtils.show(mContext, "請先添加打印機機型");
                return;
            }
            //選擇打印機機型
            new DialogUtils(this, R.layout.dialog_select_print_device) {
                @Override
                public void initLayout(ViewHepler hepler, Dialog dialog) {
                    WheelView wheelView = hepler.getView(R.id.wv_model);
                    wheelView.setOffset(1);
                    if (modelPosition >= 0) {
                        wheelView.setSeletion(modelPosition);
                    }

                    wheelView.setItems(printModelLabels);

                    hepler.getView(R.id.btn_cancel).setOnClickListener(v -> dialog.dismiss());
                    hepler.getView(R.id.btn_confirm).setOnClickListener(v -> {
                        modelPosition = wheelView.getSeletedIndex();
                        mTvModel.setText(wheelView.getSeletedItem());
                        mTvModel.setTextColor(getResources().getColor(R.color.color_3c));
                        dialog.dismiss();
                    });
                }
            }
                    .setWidth(WindowManager.LayoutParams.MATCH_PARENT)
                    .setGravity(Gravity.BOTTOM)
                    .show();
        }
    }

    private void selectFailPrint(int viewId) {
        // 彈窗，顯示除當前打印機外所有打印機，
        new DialogUtils(this, R.layout.dialog_select_print) {
            @Override
            public void initLayout(ViewHepler hepler, Dialog dialog) {
                RecyclerView rv = hepler.getView(R.id.rv_select_print);
                SelectPrintAdapter adapter = new SelectPrintAdapter(devicess);
                adapter.setSelectPosion(viewId == R.id.layout_select_fail_one ? oneFailPosition : twoFailPosition);
                adapter.setOnItemClickListener((adapter1, view, position1) -> {
                    if (viewId == R.id.layout_select_fail_one) {
                        oneFailPosition = position1;
                    } else {
                        twoFailPosition = position1;
                    }
                    adapter.setSelectPosion(position1);
                    dismiss();
                });
                rv.setLayoutManager(new LinearLayoutManager(mContext));
                rv.setAdapter(adapter);
            }
        }.setWidth((int) (ArmsUtils.getScreenWidth(this) * 0.8))
                .setHeight((int) (ArmsUtils.getScreenHeidth(this) * 0.6))
                .setOnDismissListener(dialog -> {
                    if (viewId == R.id.layout_select_fail_one) {
                        if (oneFailPosition < devicess.size() && oneFailPosition >= 0) {
                            mTvFailNameOne.setText(devicess.get(oneFailPosition).getName());
                            mTvFailNameOne.setTextColor(getResources().getColor(R.color.color_3c));
                        }
                    } else {
                        if (twoFailPosition < devicess.size() && twoFailPosition >= 0) {
                            mTvFailNameTwo.setText(devicess.get(twoFailPosition).getName());
                            mTvFailNameTwo.setTextColor(getResources().getColor(R.color.color_3c));
                        }
                    }
                })
                .show();
    }

    /**
     * 添加或測試打印機
     */
    private void addOrTestPrint(View v) {
        if (mEdPrintName.getText() == null || mEdPrintName.getText().toString().isEmpty()) {
            ToastUtils.show(mContext, "請輸入打印機名稱");
            return;
        }
        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(".");
        }

        hideKeyBoard();

        int paperType = 1;//打印紙類型
//        if (rgPaperType.getCheckedRadioButtonId() != R.id.print_paper_size_58) {
//            paperType = 2;
//        }

        String port = etPort.getText().toString();
        PrinterDeviceBean deviceBean;
        if (printerDeviceBean != null) {
            deviceBean = printerDeviceBean;
        } else {
            deviceBean = new PrinterDeviceBean();
        }
        deviceBean.setName(mEdPrintName.getText().toString().trim());
        deviceBean.setRestaurantId(GsaCloudApplication.getRestaurantId(mContext));
        deviceBean.setIp(ipAddress.substring(0, ipAddress.lastIndexOf(".")));

        if (TextUtil.isEmptyOrNullOrUndefined(port)) {
            deviceBean.setPort(9100);
        } else {
            deviceBean.setPort(Integer.parseInt(port));
        }
        //飛單打印機
        if (oneFailPosition != -1) {
            deviceBean.setFlyPrinterDeviceId(devicess.get(oneFailPosition).getId());
        }
        if (twoFailPosition != -1) {
            deviceBean.setFlyPrinterDeviceId2(devicess.get(twoFailPosition).getId());
        }
        //是否默認
        deviceBean.setType(mSwitchDefalute.isChecked() ? 2 : 1);

        //打印機機型
        if (modelPosition < 0) {
            //modelPosition小於0，說明用戶沒有選擇機型
            if (printerDeviceBean != null) {
                //如果打印機以前的信息不為空，則用之前的機型信息
                deviceBean.setPrinterModelId(printerDeviceBean.getPrinterModelId());
                deviceBean.setPaperSpecification(printerDeviceBean.getPaperSpecification());
            }
        } else {
            //如果用戶選擇了打印機機型，判斷機型數據是否為空，不為空就設置機型信息
            if (printModelBeans != null && printModelBeans.size() > modelPosition) {
                deviceBean.setPrinterModelId((long) printModelBeans.get(modelPosition).getId());
                deviceBean.setPaperSpecification(printModelBeans.get(modelPosition).getPaperSpecification());
            }
        }
        if (deviceBean.getPrinterModelId() == null) {
            ToastUtils.show(mContext, "請選擇打印機機型");
            return;
        }
        //添加打印機
        if (v.getId() == R.id.printer_add) {
            if (isEditPrinter && printerDeviceBean != null) {
                deviceBean.setId(printerDeviceBean.getId());
                deviceBean.setRestaurantId(null);
                deviceBean.setUid((long) GsaCloudApplication.getMemberId(mContext));
                mPresenter.updatePrinterInfo(deviceBean);
            } else {
                deviceBean.setUid(null);
                deviceBean.setRestaurantId(GsaCloudApplication.getRestaurantId(mContext));
                mPresenter.addPrinter(deviceBean);
            }
        } else if (v.getId() == R.id.print_test) {
            //打印測試
            CC.obtainBuilder("Component.Print")
                    .addParam(PrintConstans.PRINT_TYPE, PrinterRoot.PRINT_TEST)
                    .addParam("deviceBean", deviceBean)
                    .setActionName("printActivity")
                    .build()
                    .callAsyncCallbackOnMainThread((cc, result) -> {
                        //打印完之後
                        if (!result.isSuccess()) {
                            ToastUtils.show(this, "打印失敗");
                        }
                    });
        }
    }

    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) {
        //修改打印機成功，如果這個打印機是用戶設置的默認打印機，則需要更新信息

    }


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

        }

    }
}
