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.LinearLayout;
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.common.constans.PrintConstans;
import com.gingersoft.gsa.cloud.common.core.restaurant.RestaurantInfoManager;
import com.gingersoft.gsa.cloud.common.core.user.UserContext;
import com.gingersoft.gsa.cloud.common.logan.LoganManager;
import com.gingersoft.gsa.cloud.common.utils.other.TextUtil;
import com.gingersoft.gsa.cloud.common.utils.toast.ToastUtils;
import com.gingersoft.gsa.cloud.component.ComponentName;
import com.gingersoft.gsa.cloud.database.bean.PrintModelBean;
import com.gingersoft.gsa.cloud.database.bean.PrinterDeviceBean;
import com.gingersoft.gsa.cloud.ui.utils.DialogUtils;
import com.gingersoft.gsa.cloud.ui.view.WheelView;
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.ui.adapter.SelectPrintAdapter;
import com.qmuiteam.qmui.widget.QMUITopBar;

import java.util.ArrayList;
import java.util.Arrays;
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;
    @BindView(R2.id.tv_print_type)
    TextView tvPrintType;
    @BindView(R2.id.layout_print_path)
    LinearLayout prjOutPath;
    @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;
    @BindView(R2.id.tv_food_font_size)
    TextView mTvFoodNameSize;//食品字體大小
    @BindView(R2.id.tv_details_font_size)
    TextView mTvdetailsFontSize;//細項字體大小
    //    @BindView(R2.id.switch_print_device_food_font_thickness)
//    Switch mSwitchFontThickness;//食品是否加粗
    @BindView(R2.id.tv_print_device_food_bold)
    TextView tvFoodIsBold;//食品是否加粗
    @BindView(R2.id.tv_print_device_modifier_bold)
    TextView tvModifierIsBold;//細項是否加粗
    //    @BindView(R2.id.switch_food_items_thickness)
//    Switch mSwitchFoodItemsThickness;//細項是否加粗
//    @BindView(R2.id.switch_food_italic)
//    Switch mSwitchFoodItalic;//食品是否斜體
    @BindView(R2.id.tv_print_food_italic)
    TextView tvFoodItalic;//食品斜體
    //    @BindView(R2.id.switch_food_items_italic)
//    Switch mSwitchFoodItemsItalic;//細項是否斜體
    @BindView(R2.id.tv_print_modifier_italic)
    TextView tvModifierItalic;//細項斜體
    //    @BindView(R2.id.switch_color_flip)
//    Switch mSwitchColorFlip;//是否翻轉
    @BindView(R2.id.tv_print_flip)
    TextView tvFlip;
    @BindView(R2.id.tv_food_language)
    TextView tvLanguage;
    @BindView(R2.id.layout_ip)
    LinearLayout layoutIp;
    @BindView(R2.id.layout_port)
    LinearLayout layoutPort;
    @BindView(R2.id.print_port_line)
    View printPortLine;
    @BindView(R2.id.print_ip_line)
    View printIpLine;
    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;
    private int foodFondSize = 0;//食品字體大小 0為預設
    private int modifierFontSize = 0; //細項字體大小 0為預設
    private int printType = 1;//打印類型：1：網絡打印，2：本機打印 3：USB打印 4：PRJ模式 5：藍牙打印
    private int foodIsBoldPosition = 0;//食品是否加粗
    private int modifierIsBoldPosition = 0;//細項是否加粗
    private int foodIsItalic = 0;//食品是否斜體
    private int modifierIsItalic = 0;//細項是否斜體
    private int flipPosition = 0;//數量大於1是否翻轉
    private String[] languageType = new String[]{"1"};

    public static List<String> printTypes = Arrays.asList("網路打印", "本機打印", "USB打印", "PRJ模式");
    private List<String> fontSize = Arrays.asList("預設", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30");
    private List<String> booleanSelect = Arrays.asList("預設", "是", "否");
    private List<String> languageSelect = Arrays.asList("語言一", "語言二", "語言三");

    @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() + "");
            printType = printerDeviceBean.getPrinterDeviceType();
            hideIpPrint();
            if (printerDeviceBean.getFoodFont().equals("請選擇") || printerDeviceBean.getFoodFont().equals("")) {
                foodFondSize = 0;
            } else {
                foodFondSize = Integer.parseInt(printerDeviceBean.getFoodFont());
            }
            if (printerDeviceBean.getModifierFont().equals("請選擇") || printerDeviceBean.getModifierFont().equals("")) {
                modifierFontSize = 0;
            } else {
                modifierFontSize = Integer.parseInt(printerDeviceBean.getModifierFont());
            }
            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.getPrinterDeviceDefaultId() != null);
            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().equals(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().equals(printerDeviceBean.getFlyPrinterDeviceId2())) {
                            mTvFailNameTwo.setText(devicess.get(i).getName());
                            twoFailPosition = i;
                            mTvFailNameTwo.setTextColor(getResources().getColor(R.color.color_3c));
                        }
                    }
                }
            }
//            mSwitchFontThickness.setChecked(printerDeviceBean.getFoodIsBold() == 1);
//            mSwitchFoodItemsThickness.setChecked(printerDeviceBean.getModifierIsBold() == 1);
//            mSwitchFoodItalic.setChecked(printerDeviceBean.getFoodIsItalic() == 1);
//            mSwitchFoodItemsItalic.setChecked(printerDeviceBean.getModifierIsItalic() == 1);
//            mSwitchColorFlip.setChecked(printerDeviceBean.getNumberIsFlip() == 1);
            foodIsBoldPosition = printerDeviceBean.getFoodIsBold();
            modifierIsBoldPosition = printerDeviceBean.getModifierIsBold();
            foodIsItalic = printerDeviceBean.getFoodIsItalic();
            modifierIsItalic = printerDeviceBean.getModifierIsItalic();
            flipPosition = printerDeviceBean.getNumberIsFlip();
            if (printerDeviceBean.getLanguageType() != null) {
                languageType = printerDeviceBean.getLanguageType().split(",");
            }
        } else {
            mTvFoodNameSize.setText("1");
            mTvdetailsFontSize.setText("1");
        }
        //打印類型，USB，網路
        if (printType - 1 >= 0 && printType - 1 < printTypes.size()) {
            tvPrintType.setText(printTypes.get(printType - 1));
            prjOutPath.setVisibility(printType == 4 ? View.VISIBLE : View.GONE);
        }
        //食品和細項字體大小
        if (foodFondSize > fontSize.size()) {
            foodFondSize = 0;
        }
        mTvFoodNameSize.setText(fontSize.get(foodFondSize));

        if (modifierFontSize > fontSize.size()) {
            modifierFontSize = 0;
        }
        mTvdetailsFontSize.setText(fontSize.get(modifierFontSize));

        tvFoodIsBold.setText(booleanSelect.get(foodIsBoldPosition));
        tvModifierIsBold.setText(booleanSelect.get(modifierIsBoldPosition));
        tvFoodItalic.setText(booleanSelect.get(foodIsItalic));
        tvModifierItalic.setText(booleanSelect.get(modifierIsItalic));
        tvFlip.setText(booleanSelect.get(flipPosition));

        setLanguage();

        //添加監聽
        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]);
            }
            ipEdits[i].clearFocus();
        }
    }

    private void setLanguage() {
        StringBuilder stringBuilder = new StringBuilder();
        for (int i = 0; i < languageType.length; i++) {
            int index;
            if (languageType[i].contains(".")) {
                index = Integer.parseInt(languageType[i].substring(0, languageType[i].indexOf("."))) - 1;
            } else {
                index = Integer.parseInt(languageType[i]) - 1;
            }
            if (index >= 0 && index < languageSelect.size()) {
                stringBuilder.append(languageSelect.get(index));
                if (i != languageType.length - 1) {
                    stringBuilder.append(",");
                }
            }
        }
        tvLanguage.setText(stringBuilder.toString());
    }

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

    private void showSelectFoodFontSize(TextView textView, int defaultSelect) {
        DialogUtils.showSelectPopop(this, fontSize, "字體大小", defaultSelect, i -> {
            textView.setText(fontSize.get(i));
            if (textView.getId() == R.id.tv_food_font_size) {
                //食品字體大小
                foodFondSize = i;
            } else if (textView.getId() == R.id.tv_details_font_size) {
                modifierFontSize = i;
            }
        });
    }


    private void showSelectPrintType() {
//        types.add("藍牙打印");
        DialogUtils.showSelectPopop(this, printTypes, "打印機類型", printType - 1, i -> {
            printType = i + 1;
            hideIpPrint();
            tvPrintType.setText(printTypes.get(i));
            prjOutPath.setVisibility(printType == 4 ? View.VISIBLE : View.GONE);
        });
    }

    private void hideIpPrint() {
        //只要不是網絡打印，就不需要輸入打印機IP和端口號
        int isVisible = printType != 1 ? View.GONE : View.VISIBLE;
        layoutIp.setVisibility(isVisible);
        layoutPort.setVisibility(isVisible);
        printPortLine.setVisibility(isVisible);
        printIpLine.setVisibility(isVisible);
    }

    @OnClick({R2.id.layout_print_device_food_language, R2.id.layout_flip, R2.id.layout_modifier_italic, R2.id.layout_food_italic, R2.id.layout_print_modifier_isbold, R2.id.layout_print_food_isbold, R2.id.layout_print_type, R2.id.printer_add, R2.id.layout_select_fail_one, R2.id.layout_select_fail_two, R2.id.layout_print_device, R2.id.layout_print_device_food_font_size, R2.id.layout_print_device_food_item_font_size})
    @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) {
            //選擇飛單
            selectFailPrint(id);
        } else if (id == R.id.layout_print_device) {
            //選擇打印機機型
            selectPrintModel();
        } else if (id == R.id.layout_print_device_food_font_size) {
            //選擇食品字體大小
            showSelectFoodFontSize(mTvFoodNameSize, foodFondSize);
        } else if (id == R.id.layout_print_device_food_item_font_size) {
            //選擇食品細項字體大小
            showSelectFoodFontSize(mTvdetailsFontSize, modifierFontSize);
        } else if (id == R.id.layout_print_type) {
            //選擇打印機類型
            showSelectPrintType();
        } else if (id == R.id.layout_print_food_isbold) {
            //食品是否加粗
            showSelectFoodIsBold("是否加粗", tvFoodIsBold);
        } else if (id == R.id.layout_print_modifier_isbold) {
            showSelectFoodIsBold("是否加粗", tvModifierIsBold);
        } else if (id == R.id.layout_food_italic) {
            showSelectFoodIsBold("是否斜體", tvFoodItalic);
        } else if (id == R.id.layout_modifier_italic) {
            showSelectFoodIsBold("是否斜體", tvModifierItalic);
        } else if (id == R.id.layout_flip) {
            showSelectFoodIsBold("是否翻轉", tvFlip);
        } else if (id == R.id.layout_print_device_food_language) {
            //prj語言
            showSelectLanguage();
        }
    }

    private void showSelectLanguage() {
        List<Integer> selectedLanguage = new ArrayList<>();
        for (String language : languageType) {
            if (language.equals("1")) {
                selectedLanguage.add(0);
            } else if (language.equals("2")) {
                selectedLanguage.add(1);
            } else if (language.equals("3")) {
                selectedLanguage.add(2);
            }
        }
        DialogUtils.showMultipleChoicePopop(this, languageSelect, "食品語言", selectedLanguage, i -> {
            String[] newLanguageType = i.split(",");
            for (int j = 0; j < newLanguageType.length; j++) {
                String oldValue = newLanguageType[j];
                newLanguageType[j] = String.valueOf(Integer.parseInt(oldValue) + 1);
            }
            languageType = newLanguageType;
            setLanguage();
        });
    }

    private void showSelectFoodIsBold(String title, TextView textView) {
        int defaultSelect = 0;
        int viewId = textView.getId();
        if (viewId == R.id.tv_print_device_food_bold) {
            defaultSelect = foodIsBoldPosition;
        } else if (viewId == R.id.tv_print_device_modifier_bold) {
            defaultSelect = modifierIsBoldPosition;
        } else if (viewId == R.id.tv_print_food_italic) {
            defaultSelect = foodIsItalic;
        } else if (viewId == R.id.tv_print_modifier_italic) {
            defaultSelect = modifierIsItalic;
        } else if (viewId == R.id.tv_print_flip) {
            defaultSelect = flipPosition;
        }
        DialogUtils.showSelectPopop(this, booleanSelect, title, defaultSelect, i -> {
            if (viewId == R.id.tv_print_device_food_bold) {
                foodIsBoldPosition = i;
            } else if (viewId == R.id.tv_print_device_modifier_bold) {
                modifierIsBoldPosition = i;
            } else if (viewId == R.id.tv_print_food_italic) {
                foodIsItalic = i;
            } else if (viewId == R.id.tv_print_modifier_italic) {
                modifierIsItalic = i;
            } else if (viewId == R.id.tv_print_flip) {
                flipPosition = i;
            }
            textView.setText(booleanSelect.get(i));
        });
    }

    /**
     * 選擇打印機機型
     */
    private void selectPrintModel() {
        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) {
        if (devicess == null || devicess.size() <= 0) {
            showMessage("沒有其他打印機");
            return;
        }
        // 彈窗，顯示除當前打印機外所有打印機，
        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) {
        LoganManager.w_code(TAG, "addOrTestPrint start");
        if (!editTextIsNull(mEdPrintName)) {
            ToastUtils.show(mContext, "請輸入打印機名稱");
            return;
        }
        if (mEdPrintName.getText().toString().contains("%")) {
            ToastUtils.show(mContext, "打印機名稱禁止輸入%字符");
            return;
        }
        if (printerDeviceBean == null) {
            printerDeviceBean = new PrinterDeviceBean();
        }
        //保存打印機信息
        StringBuilder ipAddress = new StringBuilder();
        if (printType == 1) {
            for (EditText editText : ipEdits) {
                if (editText.getText() == null || editText.getText().toString().equals("")) {
                    showMessage("請輸入完整的IP地址");
                    return;
                }
                ipAddress.append(editText.getText());
                ipAddress.append(".");
            }
            printerDeviceBean.setIp(ipAddress.substring(0, ipAddress.lastIndexOf(".")));
            String port = etPort.getText().toString();
            if (TextUtil.isEmptyOrNullOrUndefined(port)) {
                printerDeviceBean.setPort(9100);
            } else {
                printerDeviceBean.setPort(Integer.parseInt(port));
            }
        } else {
            printerDeviceBean.setIp("");
            printerDeviceBean.setPort(0);
        }
        hideKeyBoard();

        printerDeviceBean.setName(mEdPrintName.getText().toString().trim());
        printerDeviceBean.setRestaurantId(RestaurantInfoManager.newInstance().getRestaurantId());

        //飛單打印機
        if (oneFailPosition != -1) {
            printerDeviceBean.setFlyPrinterDeviceId(devicess.get(oneFailPosition).getId());
        }
        if (twoFailPosition != -1) {
            printerDeviceBean.setFlyPrinterDeviceId2(devicess.get(twoFailPosition).getId());
        }
        //是否默認
        printerDeviceBean.setType(mSwitchDefalute.isChecked() ? 2 : 1);
        //打印機機型
        if (modelPosition >= 0) {
            //如果用戶選擇了打印機機型，判斷機型數據是否為空，不為空就設置機型信息
            if (printModelBeans != null && printModelBeans.size() > modelPosition) {
                printerDeviceBean.setPrinterModelId((long) printModelBeans.get(modelPosition).getId());
                printerDeviceBean.setPaperSpecification(printModelBeans.get(modelPosition).getPaperSpecification());
            }
        }
        if (printerDeviceBean.getPrinterModelId() == null) {
            ToastUtils.show(mContext, "請選擇打印機機型");
            return;
        }
        printerDeviceBean.setFoodFont("" + foodFondSize);
        printerDeviceBean.setModifierFont("" + modifierFontSize);

        printerDeviceBean.setFoodIsBold(foodIsBoldPosition);
        printerDeviceBean.setModifierIsBold(modifierIsBoldPosition);
        printerDeviceBean.setFoodIsItalic(foodIsItalic);
        printerDeviceBean.setModifierIsItalic(modifierIsItalic);
        printerDeviceBean.setNumberIsFlip(flipPosition);

        StringBuilder languageSb = new StringBuilder();
        for (int i = 0; i < languageType.length; i++) {
            languageSb.append(languageType[i]);
            if (i != languageType.length - 1) {
                languageSb.append(",");
            }
        }
        printerDeviceBean.setLanguageType(languageSb.toString());
        printerDeviceBean.setPrinterDeviceType(printType);
        //添加打印機
        if (v.getId() == R.id.printer_add) {
            if (isEditPrinter) {
                printerDeviceBean.setRestaurantId(null);
                printerDeviceBean.setUid((long) UserContext.newInstance().getMemberId());
                mPresenter.updatePrinterInfo(printerDeviceBean);
            } else {
                printerDeviceBean.setUid(null);
                printerDeviceBean.setRestaurantId(RestaurantInfoManager.newInstance().getRestaurantId());
                mPresenter.addPrinter(printerDeviceBean);
            }
        } else if (v.getId() == R.id.print_test) {
            //打印測試
            LoganManager.w_code(TAG, "打印測試 start");
            CC.obtainBuilder(ComponentName.COMPONENT_PRINT)
                    .addParam(PrintConstans.PRINT_TYPE, PrintConstans.PRINT_TEST)
                    .addParam("deviceBean", printerDeviceBean)
                    .setActionName("printActivity")
                    .build()
                    .callAsyncCallbackOnMainThread((cc, result) -> {
                        //打印完之後
//                        if (!result.isSuccess()) {
//                            ToastUtils.show(this, "打印失敗");
//                        }
                        LoganManager.w_code(TAG, "打印測試 end");
                    });
        }
        LoganManager.w_code(TAG, "addOrTestPrint end");

    }

    private boolean editTextIsNull(TextView edit) {
        return (edit != null && edit.getText() != null && !TextUtil.isEmptyOrNullOrUndefined(edit.getText().toString()));
    }

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

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

        }

    }
}
