package com.gingersoft.coldchain_module.mvp.ui.activity;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.print.PrintManager;
import android.util.Log;
import android.view.KeyEvent;
import android.widget.TextView;

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

import com.gingersoft.coldchain_module.R;
import com.gingersoft.coldchain_module.R2;
import com.gingersoft.coldchain_module.di.component.DaggerOrderDetailsComponent;
import com.gingersoft.coldchain_module.di.module.OrderDetailsModule;
import com.gingersoft.coldchain_module.mvp.contract.OrderDetailsContract;
import com.gingersoft.coldchain_module.mvp.presenter.OrderDetailsPresenter;
import com.gingersoft.coldchain_module.mvp.ui.adapter.MyPrintDocumentAdapter;
import com.gingersoft.coldchain_module.mvp.ui.adapter.OrderDetailsBtnAdapter;
import com.gingersoft.coldchain_module.mvp.ui.adapter.OrderDetailsFoodAdapter;
import com.gingersoft.gsa.cloud.base.application.GsaCloudApplication;
import com.gingersoft.gsa.cloud.base.utils.MoneyUtil;
import com.gingersoft.gsa.cloud.base.utils.other.TextUtil;
import com.gingersoft.gsa.cloud.base.utils.time.TimeUtils;
import com.gingersoft.gsa.cloud.constans.FunctionManagerConstants;
import com.gingersoft.gsa.cloud.database.bean.Function;
import com.gingersoft.gsa.cloud.function.FunctionManager;
import com.gingersoft.gsa.cloud.print.bean.OrderDetails;
import com.gingersoft.gsa.cloud.ui.utils.AppDialog;
import com.gingersoft.gsa.cloud.ui.utils.BtnBuilder;
import com.gingersoft.gsa.cloud.ui.widget.dialog.LoadingDialog;
import com.jess.arms.base.BaseActivity;
import com.jess.arms.di.component.AppComponent;
import com.jess.arms.utils.ArmsUtils;
import com.permissionx.guolindev.PermissionX;
import com.permissionx.guolindev.callback.RequestCallback;
import com.qmuiteam.qmui.widget.QMUITopBar;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;

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


public class OrderDetailsActivity extends BaseActivity<OrderDetailsPresenter> implements OrderDetailsContract.View {
    @BindView(R2.id.cold_chain_order_detail_top_bar)
    QMUITopBar topBar;
    @BindView(R2.id.tv_order_from)
    TextView mTvOrderFrom;
    @BindView(R2.id.tv_order_state)
    TextView mTvOrderStatus;
    @BindView(R2.id.tv_order_no)
    TextView mTvOrderNo;
    @BindView(R2.id.tv_create_time)
    TextView mTvCreateTime;
    @BindView(R2.id.tv_receiver)
    TextView mTvReceiver;
    @BindView(R2.id.tv_bill_num)
    TextView mTvOrderNum;
    @BindView(R2.id.tv_receive_phone)
    TextView mTvReceiverPhone;
    @BindView(R2.id.tv_receive_time)
    TextView mTvReceiverTime;
    @BindView(R2.id.tv_receive_address)
    TextView mTvReceiverAddress;
    @BindView(R2.id.tv_remark)
    TextView mTvRemark;
//    @BindView(R2.id.tv_delivery_man_name)
//    TextView mTvDeliveryManName;
//    @BindView(R2.id.tv_delivery_man_phone)
//    TextView mTvDeliveryManPhone;
//    @BindView(R2.id.tv_delivery_num)
//    TextView mTvDeliveryNumber;

    @BindView(R2.id.rv_food)
    RecyclerView mRvFood;
    OrderDetailsFoodAdapter mFoodAdapter;
    @BindView(R2.id.rv_order_details_btn)
    RecyclerView mRvBtn;

    @BindView(R2.id.tv_total)
    TextView mTvTotalAmount;
    @BindView(R2.id.tv_lunchbox_cost)
    TextView mTvLunchboxCost;
    @BindView(R2.id.tv_delivery_fee)
    TextView mTvDeliveryFee;
    @BindView(R2.id.tv_discount)
    TextView mTvDiscount;
    @BindView(R2.id.tv_total_amount2)
    TextView mTvTotalAmount2;
    @BindView(R2.id.tv_pay_amount)
    TextView mTvPayAmount;
    @BindView(R2.id.tv_pay_method)
    TextView mTvPayMethod;

    private int orderId;
    private int isRead = -1;

    private BtnBuilder btnBuilder;
    private String labUrl;

    private int position;
    private int orderStatus;

    private boolean printPdf = false;

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

    @Override
    public int initView(@Nullable Bundle savedInstanceState) {
        return R.layout.cold_chain_order_details; //如果你不需要框架帮你设置 setContentView(id) 需要自行设置,请返回 0
    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {
        requestPermissions(null);
        mPresenter.findOrderDetails(orderId, isRead);
//        mPresenter.download("https://labels.shipany.io/sbx2/325764d7-b2e2-4d8b-9a68-7f4473719f9c/2020-08-27/20200827171831451_SF5805023992121_144ac51b-5370-46db-9e8d-50904e33b1b7.pdf");
        List<Function> functionByResModule = FunctionManager.getDefault().getFunctionByResModule(GsaCloudApplication.getAppContext(), FunctionManagerConstants.takeaway.class, FunctionManagerConstants.takeaway.orderDetails, "orderDetails/btn");
        btnBuilder = BtnBuilder.getInstance(functionByResModule);
    }

    @Override
    public void initIntent() {
        orderId = getIntent().getIntExtra("orderId", 0);
        isRead = getIntent().getIntExtra("isRead", -1);//是否已讀訂單
        position = getIntent().getIntExtra("position", 0);//是否已讀訂單
    }

    @Override
    public void initTopBar() {
        topBar.setTitle("訂單詳情");
        topBar.addLeftImageButton(R.drawable.icon_return, R.id.iv_left_back).setOnClickListener(v -> killMyself());
        topBar.setBackgroundColor(ContextCompat.getColor(this, R.color.theme_color));
    }

    @Override
    public void initLanguage() {

    }

    @Override
    public void initLayoutParams() {

    }

    @Override
    public void initLayoutVisible() {

    }

    @Override
    public void showLoading(String message) {
        Observable.just(1)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(integer -> {
                    if (message != null) {
                        LoadingDialog.showDialogForLoading(mContext, message, true);
                    } else {
                        LoadingDialog.showDialogForLoading(mContext);
                    }
                });
    }

    @Override
    public void hideLoading() {
        Log.e("eee", "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() {
        Intent intent = new Intent();
        intent.putExtra("position", position);
        intent.putExtra("orderStatus", orderStatus);
        if (printPdf) {
            intent.putExtra("printPdf", true);
        }
        setResult(1001, intent);
        finish();
    }

    @Override
    public void loadOrderDetails(OrderDetails.DataBean bean) {
        labUrl = bean.getLabUrl();
        mTvOrderFrom.setText(getResources().getString(bean.getOrder_from() == 7 ? R.string.h5_order : R.string.ricepon_order));
        if (bean.getOrderStatus() == 2) {
            mTvOrderStatus.setText("已確認訂單");
            mTvOrderStatus.setTextColor(ContextCompat.getColor(mContext, R.color.order_state1_color));
        } else if (bean.getOrderStatus() == 3) {
            mTvOrderStatus.setText("訂單派送中");
            mTvOrderStatus.setTextColor(ContextCompat.getColor(mContext, R.color.order_state2_color));
        } else if (bean.getOrderStatus() == 0 || bean.getOrderStatus() == 1) {
            mTvOrderStatus.setText("待確認訂單");
            mTvOrderStatus.setTextColor(ContextCompat.getColor(mContext, R.color.order_state0_color));
        }
        mTvOrderNo.setText(getResources().getString(R.string.order_no) + bean.getORDER_NO());
        mTvCreateTime.setText(getResources().getString(R.string.create_order_time) + TimeUtils.parseTimeRepeat(bean.getCREATE_TIME(), TimeUtils.DEFAULT_DATE_FORMAT));
        mTvReceiver.setText(bean.getRECEIVER());
        mTvOrderNum.setText(bean.getBillNo());
        mTvReceiverPhone.setText(bean.getPHONE());
        mTvReceiverTime.setText(TextUtil.isNotEmptyOrNullOrUndefined(bean.getTakeTime()) ? bean.getTakeTime() : bean.getSEND_TIME());
        mTvReceiverAddress.setText(bean.getAddressDetail());
        mTvRemark.setText(bean.getRemark());
        if (mFoodAdapter == null) {
            mFoodAdapter = new OrderDetailsFoodAdapter(bean.getPRODUCT_NAME());
            mRvFood.setAdapter(mFoodAdapter);
            mRvFood.setLayoutManager(new LinearLayoutManager(mContext));
        } else {
            mFoodAdapter.setNewInstance(bean.getPRODUCT_NAME());
        }
        String amountUnit = getResources().getString(R.string.amount_unit);
        mTvTotalAmount.setText(amountUnit + MoneyUtil.sub(MoneyUtil.sub(Double.parseDouble(bean.getTOTAL_AMOUNT()), bean.getLunchbox()), bean.getDELIVERY_CHARGE()));
        mTvLunchboxCost.setText(amountUnit + bean.getLunchbox());
        mTvDeliveryFee.setText(amountUnit + bean.getDELIVERY_CHARGE());
        mTvDiscount.setText(amountUnit + bean.getDiscount_amount());
        mTvTotalAmount2.setText(amountUnit + MoneyUtil.sub(Double.parseDouble(bean.getTOTAL_AMOUNT()), bean.getDiscount_amount()));
        mTvPayAmount.setText(amountUnit + MoneyUtil.sub(Double.parseDouble(bean.getTOTAL_AMOUNT()), bean.getDiscount_amount()));

        if (bean.getOrderPayType() == 2 && bean.getPayMultiple() != null) {
            StringBuilder sb = new StringBuilder();
            for (OrderDetails.DataBean.PayMultiple payMultiple : bean.getPayMultiple()) {
                sb.append(payMultiple.getPayName());
                sb.append(",");
            }
            if (sb.length() > 0) {
                sb.deleteCharAt(sb.length() - 1);
            }
            mTvPayMethod.setText(sb.toString());
        }

        ArrayList<BtnBuilder.BtnBean> btnBeans = new ArrayList<>();
        if (bean.getOrderStatus() == 0 || bean.getOrderStatus() == 1) {
            //待確認
            btnBeans.add(btnBuilder.getSureBtn());
            btnBeans.add(btnBuilder.getCancelBtn());
        } else if (bean.getOrderStatus() == 2) {
            //待提交
            btnBeans.add(btnBuilder.getPrintBtn());
            if (bean.isDelete() == 0) {
                btnBeans.add(btnBuilder.getLogisticsBtn());
            }
            btnBeans.add(btnBuilder.getCancelBtn());
        } else {
            btnBeans.add(btnBuilder.getPrintBtn());
            btnBeans.add(btnBuilder.getCancelBtn());
        }

        if (btnBeans.size() > 1 && btnBeans.size() < 4) {
            mRvBtn.setLayoutManager(new GridLayoutManager(mContext, btnBeans.size()));
        } else {
            mRvBtn.setLayoutManager(new GridLayoutManager(mContext, 3));
        }
        OrderDetailsBtnAdapter orderDetailsBtnAdapter = new OrderDetailsBtnAdapter(btnBeans);
        orderDetailsBtnAdapter.setOnItemClickListener((adapter, view, position) -> {
            if (btnBeans.get(position).getType() == BtnBuilder.SureBtn) {
                requestPermissions((allGranted, grantedList, deniedList) -> {
                    //確認訂單
                    if (allGranted) {
                        mPresenter.thirdDelivery(bean);
                    }
                });
            } else if (btnBeans.get(position).getType() == BtnBuilder.CancelBtn) {
                //取消訂單
                new AppDialog().showWaringDialog(this, "確認取消訂單？", (v, dialog) -> {
                    dialog.dismiss();
                    if (bean.isDelete() == 0) {
                        mPresenter.cancelOrderAndLogistics(orderId);
                    } else {
                        mPresenter.cancelOrder(bean.getID());
                    }
                });
            } else if (btnBeans.get(position).getType() == BtnBuilder.LogisticsBtn) {
                //取消物流
                new AppDialog().showWaringDialog(this, "確認取消物流？", (v, dialog) -> {
                    dialog.dismiss();
                    mPresenter.cancelLogistics(bean.getID(), false);
                });
            } else if (btnBeans.get(position).getType() == BtnBuilder.PrintBtn) {
                //打印
                requestPermissions((allGranted, grantedList, deniedList) -> {
                    if (allGranted) {
                        if (TextUtil.isNotEmptyOrNullOrUndefined(labUrl)) {
                            mPresenter.download(bean.getID(), labUrl);
                        } else {
                            showMessage("獲取打印鏈接失敗");
                        }
                    }
                });
            }
        });
        mRvBtn.setAdapter(orderDetailsBtnAdapter);
    }

    @Override
    public void printLogisticsList(File file) {
        doPrint(file);
    }

    @Override
    public void updateOrderState(int state) {
        //當訂單狀態修改後，會調用此方法，返回列表頁面時，刷新對應的item
        orderStatus = state;
    }

    @Override
    public void setPrintPdfState() {
        printPdf = true;
    }

    /**
     * 自定义打印
     */
    private void doPrint(File file) {
        // Get a PrintManager instance 获取打印驱动对象
        PrintManager printManager = (PrintManager) getSystemService(Context.PRINT_SERVICE);
        // Set job name, which will be displayed in the print queue 设置作业名称，该名称将显示在打印队列中
        String jobName = getString(R.string.app_name) + "Document";
        // Start a print job, passing in a PrintDocumentAdapter implementation 启动打印作业，传入printdocumentadapter实现
        // to handle the generation of a print document处理打印文档的生成
        if (!isFinishing()) {
            printManager.print(jobName, new MyPrintDocumentAdapter(mContext, file, (code, msg) -> {
                hideLoading();
                if (code != 0) {
                    showMessage(msg);
                }
                killMyself();
            }), null);
        }
    }

    private void requestPermissions(RequestCallback requestCallback) {
        PermissionX.init(this)
                .permissions(Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                .onExplainRequestReason((scope, deniedList) -> scope.showRequestReasonDialog(deniedList, "打印物流單需要您同意文件讀取權限", "確定", "取消"))
                .onForwardToSettings((scope, deniedList) -> scope.showForwardToSettingsDialog(deniedList, "您需要去設置當中開啟文件讀取權限", "確定", "取消"))
                .request(requestCallback);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            killMyself();
            return true;
        } else {
            return super.onKeyDown(keyCode, event);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        hideLoading();
    }
}