package com.gingersoft.supply_chain.mvp.ui.fragment.order;

import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;

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

import com.gingersoft.gsa.cloud.common.utils.MoneyUtil;
import com.gingersoft.gsa.cloud.common.utils.time.TimeUtils;
import com.gingersoft.supply_chain.R;
import com.gingersoft.supply_chain.R2;
import com.gingersoft.supply_chain.di.component.DaggerOrderDetailsComponent;
import com.gingersoft.supply_chain.mvp.bean.DeputyUnitBean;
import com.gingersoft.supply_chain.mvp.bean.PurchaseOrderDetailsBean;
import com.gingersoft.supply_chain.mvp.contract.OrderDetailsContract;
import com.gingersoft.supply_chain.mvp.presenter.OrderDetailsPresenter;
import com.gingersoft.supply_chain.mvp.ui.adapter.OrderDetailsFoodAdapter;
import com.gingersoft.supply_chain.mvp.ui.fragment.BaseSupplyChainFragment;
import com.jess.arms.di.component.AppComponent;
import com.qmuiteam.qmui.alpha.QMUIAlphaTextView;
import com.qmuiteam.qmui.widget.QMUITopBar;

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

import butterknife.BindView;
import butterknife.OnClick;


/**
 * ================================================
 * Description: 訂單詳情
 */
public class OrderDetailsFragment extends BaseSupplyChainFragment<OrderDetailsPresenter> implements OrderDetailsContract.View {

    @BindView(R2.id.supply_top_bar)
    QMUITopBar supplyTopBar;
    @BindView(R2.id.tv_order_details_supplier_name)
    TextView tvOrderDetailsSupplierName;
    @BindView(R2.id.tv_order_details_order_no)
    TextView tvOrderDetailsOrderNo;
    @BindView(R2.id.tv_order_details_create_time)
    TextView tvOrderDetailsCreateTime;
    @BindView(R2.id.tv_order_details_order_state)
    TextView tvOrderDetailsOrderState;
    @BindView(R2.id.rv_order_details_food_list)
    RecyclerView rvOrderDetailsFoodList;
    @BindView(R2.id.cb_order_details_all_selected)
    CheckBox cbOrderDetailsAllSelected;
    @BindView(R2.id.tv_order_details_food_type_total)
    TextView tvOrderDetailsFoodTypeTotal;
    @BindView(R2.id.tv_order_details_total_amount)
    TextView tvOrderDetailsTotalAmount;
    @BindView(R2.id.tv_order_details_click_upload)
    TextView tvOrderDetailsClickUpload;
    @BindView(R2.id.ed_order_details_remark)
    EditText edOrderDetailsRemark;
    @BindView(R2.id.tv_order_details_buy_again)
    QMUIAlphaTextView tvOrderDetailsBuyAgain;
    @BindView(R2.id.tv_order_details_partial_receipt)
    QMUIAlphaTextView tvOrderDetailsPartialReceipt;
    @BindView(R2.id.tv_order_details_receipt)
    QMUIAlphaTextView tvOrderDetailsReceipt;

    private OrderDetailsFoodAdapter orderDetailsFoodAdapter;
    private int typesOfFood = 0;
    private double totalAmount = 0;

    //    private int orderState = PurchaseOrderDetailsBean.WAIT_RECEIVED;
    private final static String ORDER_DETAILS_ORDER_ID = "orderId";
    private final static String ORDER_STATE = "orderState";

    public static OrderDetailsFragment newInstance(int orderId, int orderState) {
        OrderDetailsFragment fragment = new OrderDetailsFragment();
        Bundle bundle = new Bundle();
        bundle.putInt(ORDER_DETAILS_ORDER_ID, orderId);
        bundle.putInt(ORDER_STATE, orderState);
        fragment.setArguments(bundle);
        return fragment;
    }

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

    @Override
    public View initView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_order_details, container, false);
    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {
        initTopBar(supplyTopBar, "入庫單");
        supplyTopBar.addRightImageButton(R.drawable.ic_white_delete, R.id.qmui_delete_order).setOnClickListener(v -> {
            //刪除訂單

        });
        Bundle arguments = getArguments();
        if (arguments != null) {
            int orderId = arguments.getInt(ORDER_DETAILS_ORDER_ID, 0);
//            orderState = arguments.getInt(ORDER_STATE, 0);
//            if (orderState == PurchaseOrderDetailsBean.COMPLETE_RECEIVED) {
//            } else {
            mPresenter.getOrderDetailsById(orderId);
//            }
        } else {
            showMessage("未獲取到訂單編號，請重試");
            killMyself();
        }
    }


    @OnClick({R2.id.tv_order_details_click_upload, R2.id.tv_order_details_buy_again, R2.id.tv_order_details_partial_receipt, R2.id.tv_order_details_receipt})
    public void onClick(View v) {
        int viewId = v.getId();
        if (viewId == R.id.tv_order_details_click_upload) {
            //文件上傳

        } else if (viewId == R.id.tv_order_details_buy_again) {
            //再次購買

        } else if (viewId == R.id.tv_order_details_partial_receipt) {
            //部分收貨
            mPresenter.addWarehouse(PurchaseOrderDetailsBean.PART_RECEIVED, "", edOrderDetailsRemark.getText() + "", totalAmount, orderDetailsFoodAdapter.getData());
            setFragmentResult(RESULT_OK, null);
        } else if (viewId == R.id.tv_order_details_receipt) {
            //收貨
            mPresenter.addWarehouse(PurchaseOrderDetailsBean.COMPLETE_RECEIVED, "", edOrderDetailsRemark.getText() + "", totalAmount, orderDetailsFoodAdapter.getData());
            setFragmentResult(RESULT_OK, null);
        }
    }

    @Override
    public void loadOrderDetails(PurchaseOrderDetailsBean orderDetailsBean) {
        tvOrderDetailsSupplierName.setText(orderDetailsBean.getSupplierName());
        tvOrderDetailsOrderNo.setText(orderDetailsBean.getOrderNo());
        tvOrderDetailsCreateTime.setText(TimeUtils.getStringByFormat(orderDetailsBean.getCreateTime(), TimeUtils.DEFAULT_DATE_FORMAT_YMDHM));
        switch (orderDetailsBean.getStatus()) {
            case PurchaseOrderDetailsBean.WAIT_RECEIVED:
                tvOrderDetailsOrderState.setText("待收貨");
                break;
            case PurchaseOrderDetailsBean.PART_RECEIVED:
                tvOrderDetailsOrderState.setText("部分收貨");
                break;
            case PurchaseOrderDetailsBean.COMPLETE_RECEIVED:
                tvOrderDetailsOrderState.setText("已完成");
                break;
            case PurchaseOrderDetailsBean.REFUSE_RECEIVED:
                tvOrderDetailsOrderState.setText("拒收");
                break;
            default:
                break;
        }
        setTypesOfFood();
        initRecyclerView(orderDetailsBean);
        //全選按鈕狀態切換
        cbOrderDetailsAllSelected.setOnCheckedChangeListener((buttonView, isChecked) -> {
            if (buttonView.isPressed()) {
                //重新計算總價
                totalAmount = 0;
                typesOfFood = isChecked ? orderDetailsFoodAdapter.getData().size() : 0;
                //修改所有食品的選中狀態
                for (PurchaseOrderDetailsBean.PurchaseOrderDetailsInfoVosBean datum : orderDetailsFoodAdapter.getData()) {
                    datum.setChecked(isChecked);
                    if (isChecked) {
                        totalAmount = MoneyUtil.sum(totalAmount, datum.getWarehousingAmount());
                    }
                }
                orderDetailsFoodAdapter.notifyDataSetChanged();
                setTotalAmount();
                setTypesOfFood();
            }
        });
    }

    private void setTypesOfFood() {
        tvOrderDetailsFoodTypeTotal.setText(String.valueOf(typesOfFood));
    }

    private void setTotalAmount() {
        tvOrderDetailsTotalAmount.setText(String.valueOf(totalAmount));
    }

    private void initRecyclerView(PurchaseOrderDetailsBean orderDetailsBean) {
        orderDetailsFoodAdapter = new OrderDetailsFoodAdapter(mContext, orderDetailsBean.getPurchaseOrderDetailsInfoVOS());
        rvOrderDetailsFoodList.setAdapter(orderDetailsFoodAdapter);
        orderDetailsFoodAdapter.setOnValueChangeListener((position, value) -> {
            totalAmount = MoneyUtil.sum(totalAmount, value);
            setTotalAmount();
        });
        orderDetailsFoodAdapter.setOnItemClickListener((adapter, view, position) -> {
            PurchaseOrderDetailsBean.PurchaseOrderDetailsInfoVosBean infoVosBean = orderDetailsFoodAdapter.getData().get(position);
            infoVosBean.setChecked(!infoVosBean.isChecked());
            adapter.notifyItemChanged(position);
            //修改選中狀態後，重新計算入庫總價
            if (infoVosBean.isChecked()) {
                totalAmount = MoneyUtil.sum(totalAmount, infoVosBean.getWarehousingAmount());
                typesOfFood += 1;
            } else {
                totalAmount = MoneyUtil.sub(totalAmount, infoVosBean.getWarehousingAmount());
                typesOfFood -= 1;
            }
            //全選
            cbOrderDetailsAllSelected.setChecked(typesOfFood == orderDetailsFoodAdapter.getData().size());
            setTotalAmount();
            setTypesOfFood();
        });
    }
}
