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.gingersoft.gsa.cloud.ui.view.WheelView;
import com.qmuiteam.qmui.widget.QMUITopBar;

import org.w3c.dom.Text;

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;
    @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.switch_food_items_thickness)
    Switch mSwitchFoodItemsThickness;//細項是否加粗
    @BindView(R2.id.switch_food_italic)
    Switch mSwitchFoodItalic;//食品是否斜體
    @BindView(R2.id.switch_food_items_italic)
    Switch mSwitchFoodItemsItalic;//細項是否斜體
    @BindView(R2.id.switch_color_flip)
    Switch mSwitchColorFlip;//是否翻轉

    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.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));
                        }
                    }
                }
            }
            if (!TextUtil.isEmptyOrNullOrUndefined(printerDeviceBean.getFoodFont())) {
                mTvFoodNameSize.setText(printerDeviceBean.getFoodFont());
            }
            if (!TextUtil.isEmptyOrNullOrUndefined(printerDeviceBean.getModifierFont())) {
                mTvdetailsFontSize.setText(printerDeviceBean.getModifierFont());
            }
            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);
        } else {
            mTvFoodNameSize.setText("1");
            mTvdetailsFontSize.setText("1");
        }
        //添加監聽
        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();
        }
    }

    @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) {
        List<String> types = new ArrayList<>();
        types.add("1");
        types.add("2");
        types.add("3");
        types.add("4");
        types.add("5");
        DialogUtils.showSelectPopop(this, types, "餐檯模式", 0, i -> textView.setText(types.get(i)));
    }


    @OnClick({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);
        } else if (id == R.id.layout_print_device_food_item_font_size) {
            //選擇食品細項字體大小
            showSelectFoodFontSize(mTvdetailsFontSize);
        }
    }


    /**
     * 選擇打印機機型
     */
    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) {
        if (!editTextIsNull(mEdPrintName)) {
            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();
        String port = etPort.getText().toString();
        if (printerDeviceBean == null) {
            printerDeviceBean = new PrinterDeviceBean();
        }
        printerDeviceBean.setName(mEdPrintName.getText().toString().trim());
        printerDeviceBean.setRestaurantId(GsaCloudApplication.getRestaurantId(mContext));
        printerDeviceBean.setIp(ipAddress.substring(0, ipAddress.lastIndexOf(".")));

        if (TextUtil.isEmptyOrNullOrUndefined(port)) {
            printerDeviceBean.setPort(9100);
        } else {
            printerDeviceBean.setPort(Integer.parseInt(port));
        }
        //飛單打印機
        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;
        }

        if (editTextIsNull(mTvFoodNameSize)) {
            printerDeviceBean.setFoodFont(mTvFoodNameSize.getText().toString());
        }
        if (editTextIsNull(mTvdetailsFontSize)) {
            printerDeviceBean.setModifierFont(mTvdetailsFontSize.getText().toString());
        }
        printerDeviceBean.setFoodIsBold(mSwitchFontThickness.isChecked() ? 1 : 2);
        printerDeviceBean.setModifierIsBold(mSwitchFoodItemsThickness.isChecked() ? 1 : 2);
        printerDeviceBean.setFoodIsItalic(mSwitchFoodItalic.isChecked() ? 1 : 2);
        printerDeviceBean.setModifierIsItalic(mSwitchFoodItemsItalic.isChecked() ? 1 : 2);
        printerDeviceBean.setNumberIsFlip(mSwitchColorFlip.isChecked() ? 1 : 2);
        //添加打印機
        if (v.getId() == R.id.printer_add) {
            if (isEditPrinter) {
                printerDeviceBean.setRestaurantId(null);
                printerDeviceBean.setUid((long) GsaCloudApplication.getMemberId(mContext));
                mPresenter.updatePrinterInfo(printerDeviceBean);
            } else {
                printerDeviceBean.setUid(null);
                printerDeviceBean.setRestaurantId(GsaCloudApplication.getRestaurantId(mContext));
                mPresenter.addPrinter(printerDeviceBean);
            }
        } else if (v.getId() == R.id.print_test) {
            //打印測試
            CC.obtainBuilder("Component.Print")
                    .addParam(PrintConstans.PRINT_TYPE, PrinterRoot.PRINT_TEST)
                    .addParam("deviceBean", printerDeviceBean)
                    .setActionName("printActivity")
                    .build()
                    .callAsyncCallbackOnMainThread((cc, result) -> {
                        //打印完之後
                        if (!result.isSuccess()) {
                            ToastUtils.show(this, "打印失敗");
                        }
                    });
        }
    }

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

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

        }

    }
}
