package com.gingersoft.gsa.delivery_pick_mode.mvp.ui.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.billy.cc.core.component.CC;
import com.gingersoft.gsa.cloud.common.constans.AppConstans;
import com.gingersoft.gsa.cloud.common.constans.PrintConstans;
import com.gingersoft.gsa.cloud.common.utils.gson.GsonUtils;
import com.gingersoft.gsa.cloud.print.bean.PrjBean;
import com.gingersoft.gsa.cloud.print.bean.UpdateBean;
import com.gingersoft.gsa.cloud.common.utils.okhttpUtils.OkHttp3Utils;
import com.gingersoft.gsa.cloud.common.utils.other.TextUtil;
import com.gingersoft.gsa.cloud.component.ComponentName;
import com.gingersoft.gsa.cloud.ui.recylcler.decorator.DividerItemDecoration;
import com.gingersoft.gsa.cloud.ui.utils.AppDialog;
import com.gingersoft.gsa.cloud.ui.widget.dialog.LoadingDialog;
import com.gingersoft.gsa.delivery_pick_mode.R;
import com.gingersoft.gsa.delivery_pick_mode.R2;
import com.gingersoft.gsa.delivery_pick_mode.di.component.DaggerPrjQueryComponent;
import com.gingersoft.gsa.delivery_pick_mode.mvp.bean.PrjQueryBean;
import com.gingersoft.gsa.delivery_pick_mode.mvp.contract.PrjQueryContract;
import com.gingersoft.gsa.delivery_pick_mode.mvp.presenter.PrjQueryPresenter;
import com.gingersoft.gsa.delivery_pick_mode.mvp.ui.adapter.PrjStateAdapter;
import com.jess.arms.base.BaseActivity;
import com.jess.arms.di.component.AppComponent;
import com.jess.arms.utils.ArmsUtils;
import com.qmuiteam.qmui.widget.QMUITopBar;

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

import butterknife.BindView;
import butterknife.OnClick;

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


/**
 * ================================================
 * Description:
 * <p>
 * Created by MVPArmsTemplate on 10/20/2020 09:34
 * <a href="mailto:jess.yan.effort@gmail.com">Contact me</a>
 * <a href="https://github.com/JessYanCoding">Follow me</a>
 * <a href="https://github.com/JessYanCoding/MVPArms">Star me</a>
 * <a href="https://github.com/JessYanCoding/MVPArms/wiki">See me</a>
 * <a href="https://github.com/JessYanCoding/MVPArmsTemplate">模版请保持更新</a>
 * ================================================
 */
public class PrjQueryActivity extends BaseActivity<PrjQueryPresenter> implements PrjQueryContract.View, View.OnClickListener {

    @BindView(R2.id.top_bar_prj_print)
    QMUITopBar topBarPrjPrint;
    @BindView(R2.id.tv_prj_record_order_id)
    TextView tvPrjRecordOrderId;
    @BindView(R2.id.rv_prj_record_list)
    RecyclerView rvPrjRecordList;
    private PrjStateAdapter prjStateAdapter;

    @BindView(R2.id.layout_edit_prj_order_number)
    ConstraintLayout editLayout;

    @BindView(R2.id.iv_search_order_prj)
    ImageView ivSearchOrderPrj;
    @BindView(R2.id.layout_prj_order_number)
    LinearLayout layoutPrjOrderNumber;
    @BindView(R2.id.ed_input_order_number)
    EditText edOrderNumber;

    private static final String ORDERID_EXTRA_NAME = "orderId";

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

    @Override
    public int initView(@Nullable Bundle savedInstanceState) {
        return R.layout.activity_prj_query;
    }


    @Override
    public void initData(@Nullable Bundle savedInstanceState) {
        String orderId = getIntent().getStringExtra(ORDERID_EXTRA_NAME);
        if (TextUtil.isNotEmptyOrNullOrUndefined(orderId)) {
//            layoutPrjOrderNumber.setVisibility(View.VISIBLE);
//            tvPrjRecordOrderId.setText(orderId);
            edOrderNumber.setText(orderId);
            getKitchenPrintRecord();
        } else {
            editLayout.setVisibility(View.VISIBLE);
        }
    }

    public static void startPrjQueryActivity(Context context, String orderId) {
        Intent intent = new Intent(context, PrjQueryActivity.class);
        intent.putExtra(ORDERID_EXTRA_NAME, orderId);
        context.startActivity(intent);
    }

    @Override
    public void initIntent() {

    }

    @Override
    public void initTopBar() {
        topBarPrjPrint.setTitle("廚房打印查詢");
        topBarPrjPrint.setBackgroundColor(ContextCompat.getColor(this, R.color.theme_color));
        topBarPrjPrint.addLeftImageButton(R.drawable.icon_return, R.id.iv_left_back).setOnClickListener(v -> killMyself());
        topBarPrjPrint.addRightImageButton(R.drawable.icon_refresh, R.id.topbar_refresh).setOnClickListener(v -> {
            getKitchenPrintRecord();
        });
    }

    @Override
    public void initLanguage() {

    }

    @Override
    public void initLayoutParams() {

    }

    @Override
    public void initLayoutVisible() {

    }

    @Override
    public void showLoading(String message) {
        if (message != null) {
            LoadingDialog.showDialogForLoading(this, message, true);
        } else {
            LoadingDialog.showDialogForLoading(this);
        }
    }

    @Override
    public void hideLoading() {
        LoadingDialog.cancelDialogForLoading();
    }

    @Override
    public void showMessage(@NonNull String message) {
        ArmsUtils.makeText(this, message);
    }

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

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

    @OnClick({R2.id.iv_search_order_prj})
    @Override
    public void onClick(View v) {
        int viewId = v.getId();
        if (viewId == R.id.iv_search_order_prj) {
            getKitchenPrintRecord();
        }
    }

    private void getKitchenPrintRecord() {
        if (TextUtil.isNotEmptyOrNullOrUndefined(edOrderNumber)) {
            mPresenter.getKitchenPrint(edOrderNumber.getText().toString());
        } else {
            showMessage("請輸入訂單號");
            edOrderNumber.requestFocus();
        }
    }


    @Override
    public void loadPrjInfo(PrjQueryBean prjQueryBean) {
        if (prjStateAdapter == null) {
            prjStateAdapter = new PrjStateAdapter(mContext, prjQueryBean.getData());
            rvPrjRecordList.setAdapter(prjStateAdapter);
            rvPrjRecordList.addItemDecoration(new DividerItemDecoration(mContext, DividerItemDecoration.VERTICAL_LIST));
            prjStateAdapter.setOnItemChildClickListener((adapter, view, position) -> {
                if (view.getId() == R.id.tv_prj_record_print_operation) {
                    //重印
                    List<PrjBean> prjData = prjQueryBean.getData();
                    if (prjData.get(position).getPrinterType() == 3) {
                        //已打印的，提示是否重新打印
                        new AppDialog().showWaringDialog(mContext, "食品已打印，確認重印？", (view1, dialog) -> {
                            organizeData(position, prjData);
                        });
                    } else {
                        organizeData(position, prjData);
                    }
                }
            });
            rvPrjRecordList.setLayoutManager(new LinearLayoutManager(mContext));
        } else {
            prjStateAdapter.setNewInstance(prjQueryBean.getData());
        }
    }

    private void organizeData(int position, List<PrjBean> prjData) {
        if (prjData.get(position).getParentId() == 0) {
            //是主食品，判斷有沒有子食品，如果沒有子食品，直接打印主食品
            if (position + 1 >= prjData.size()) {
                //沒有子食品
                //直接打印
                List<PrjBean> printDatas = new ArrayList<>();
                printDatas.add(prjData.get(position));
                printPrj(printDatas);
            } else if (prjData.get(position).getProductId().equals(prjData.get(position + 1).getParentId() + "")) {
                //有子食品
                List<PrjBean> printDatas = new ArrayList<>();
                printDatas.add(prjData.get(position));
                for (int i = position; i < prjData.size(); i++) {
                    if (prjData.get(position).getProductId().equals(prjData.get(i).getParentId() + "")) {
                        printDatas.add(prjData.get(i));
                    } else {
                        break;
                    }
                }
                printPrj(printDatas);
            } else {
                //沒有子食品
                //直接打印
                List<PrjBean> printDatas = new ArrayList<>();
                printDatas.add(prjData.get(position));
                printPrj(printDatas);
            }
        } else {
            //是主食品，直接打印子食品
            List<PrjBean> printDatas = new ArrayList<>();
            printDatas.add(prjData.get(position));
            printPrj(printDatas);
        }
    }

    private void printPrj(List<PrjBean> printDatas) {
        String orderNo = "";
        StringBuilder ids = new StringBuilder();
        for (int i = 0; i < printDatas.size(); i++) {
            PrjBean prjBean = printDatas.get(i);
            orderNo = prjBean.getOrderNo();
            prjBean.setTotalPrj(printDatas.size());
            prjBean.setCurrentIndex(i + 1);
            ids.append(prjBean.getId());
        }
        //添加重印的報警推送
        OkHttp3Utils.noticePersonnel(AppConstans.RP_REPRINT_CODE, "重印，訂單號：" + printDatas.get(0).getOrderNo());
        String finalIds = ids.toString();
        CC.obtainBuilder(ComponentName.COMPONENT_PRINT)
                .addParam(PrintConstans.PRINT_TYPE, PrintConstans.PRINT_KITCHEN)
                .addParam(PrintConstans.PRINT_ORDER_NO, orderNo)
                .addParam("prjBeans", GsonUtils.GsonString(printDatas))
                .setActionName("printActivity")
                .build()
                .callAsyncCallbackOnMainThread((cc, result) -> {
                    if (result.isSuccess()) {
                        mPresenter.updatePrjState(UpdateBean.ALREADY_PRINT, finalIds, printDatas.get(0).getOrderNo());
                    }
                });
    }
}
