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

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.text.InputFilter;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
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.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.request.target.Target;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemChildClickListener;
import com.gingersoft.gsa.cloud.common.utils.FileUtils;
import com.gingersoft.gsa.cloud.common.utils.MoneyUtil;
import com.gingersoft.gsa.cloud.common.utils.glide.GlideUtils;
import com.gingersoft.gsa.cloud.common.utils.inputFilter.InputFilterUtils;
import com.gingersoft.gsa.cloud.common.utils.other.TextUtil;
import com.gingersoft.gsa.cloud.common.utils.time.TimeUtils;
import com.gingersoft.gsa.cloud.common.utils.toast.ToastUtils;
import com.gingersoft.gsa.cloud.ui.adapter.multi.RemarkProvider;
import com.gingersoft.gsa.cloud.ui.utils.AppDialog;
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.bean.WareHousingUnitBean;
import com.gingersoft.supply_chain.mvp.contract.OrderDetailsContract;
import com.gingersoft.supply_chain.mvp.presenter.OrderDetailsPresenter;
import com.gingersoft.supply_chain.mvp.ui.adapter.ImageAdapter;
import com.gingersoft.supply_chain.mvp.ui.adapter.OrderDetailsFoodAdapter;
import com.gingersoft.supply_chain.mvp.ui.fragment.BaseSupplyChainFragment;
import com.gingersoft.supply_chain.mvp.ui.widget.ChooseUnitPopup;
import com.gingersoft.supply_chain.mvp.ui.widget.PurchaseListMorePopup;
import com.gingersoft.supply_chain.mvp.utils.SelectPicture;
import com.google.android.material.checkbox.MaterialCheckBox;
import com.jess.arms.di.component.AppComponent;
import com.jess.arms.http.imageloader.ImageLoader;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.core.ImageViewerPopupView;
import com.lxj.xpopup.enums.PopupPosition;
import com.lxj.xpopup.interfaces.OnSelectListener;
import com.lxj.xpopup.interfaces.XPopupImageLoader;
import com.qmuiteam.qmui.alpha.QMUIAlphaTextView;
import com.qmuiteam.qmui.util.QMUIDisplayHelper;
import com.qmuiteam.qmui.widget.QMUITopBar;
import com.yalantis.ucrop.UCrop;

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

import butterknife.BindView;
import butterknife.OnClick;

import static com.yalantis.ucrop.UCrop.REQUEST_CROP;


/**
 * ================================================
 * Description: 訂單詳情，收貨操作頁面
 */
public class OrderDetailsFragment extends BaseSupplyChainFragment<OrderDetailsPresenter> implements OrderDetailsContract.View, View.OnClickListener {

    @BindView(R2.id.supply_top_bar)
    QMUITopBar supplyTopBar;
    @BindView(R2.id.tv_order_details_supplier_name)
    TextView tvOrderDetailsSupplierName;
    @BindView(R2.id.tv_order_details_create_time)
    TextView tvOrderDetailsCreateTime;
    @BindView(R2.id.tv_order_details_order_no)
    TextView tvOrderDetailsOrderNo;
    @BindView(R2.id.tv_warehouse_order_no)
    TextView tvWarehouseOrderNo;
    @BindView(R2.id.layout_remarks)
    LinearLayout layoutRemarks;
    @BindView(R2.id.iv_order_state)
    ImageView ivOrderState;
    @BindView(R2.id.rv_order_details_pictures)
    RecyclerView rvOrderDetailsPictures;
    @BindView(R2.id.rv_order_details_food_name)
    RecyclerView rvOrderDetailsFoodName;
    @BindView(R2.id.rv_order_details_food_list)
    RecyclerView rvOrderDetailsFoodList;
    @BindView(R2.id.cb_order_details_all_selected)
    MaterialCheckBox 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_partial_receipt)
    QMUIAlphaTextView tvOrderDetailsPartialReceipt;
    @BindView(R2.id.tv_order_details_receipt)
    QMUIAlphaTextView tvOrderDetailsReceipt;
    @BindView(R2.id.ed_warehouse_order_remark)
    EditText edRemark;
    @BindView(R2.id.layout_ed_remark)
    LinearLayout layoutEdRemark;

    private OrderDetailsFoodAdapter orderDetailsFoodAdapter;

    ImageAdapter imageAdapter;
    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";
    private int 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_new, container, false);
    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {
        initTopBar(supplyTopBar, "入庫單");
        supplyTopBar.addRightImageButton(R.drawable.ic_white_more, R.id.id_more).setOnClickListener(this);
        supplyTopBar.addRightImageButton(R.drawable.ic_take_pictures, R.id.id_take_pictures).setOnClickListener(this);
        edRemark.setFilters(new InputFilter[]{InputFilterUtils.getLengthFilter(mContext, RemarkProvider.REMARK_TEXT_LENGTH), InputFilterUtils.getChAndEnAndNumAndPtInputFilter(mContext)});
        Bundle arguments = getArguments();
        if (arguments != null) {
            int orderId = arguments.getInt(ORDER_DETAILS_ORDER_ID, 0);
            orderState = arguments.getInt(ORDER_STATE, PurchaseOrderDetailsBean.WAIT_RECEIVED);
            int isShow = orderState == PurchaseOrderDetailsBean.COMPLETE_RECEIVED ? View.GONE : View.VISIBLE;
            tvOrderDetailsPartialReceipt.setVisibility(isShow);
            tvOrderDetailsReceipt.setVisibility(isShow);
            mPresenter.getOrderDetailsById(orderId);
        } else {
            showMessage("未獲取到訂單編號，請重試");
            killMyself();
        }
    }


    @OnClick({R2.id.tv_order_details_partial_receipt, R2.id.tv_order_details_receipt, R2.id.layout_remarks})
    @Override
    public void onClick(View v) {
        int viewId = v.getId();
        if (viewId == R.id.id_take_pictures) {
            //拍照
            if (mPresenter.getPicSize() < 4) {
                SelectPicture.getInstance().showSelectType(this);
            } else {
                ToastUtils.show(requireContext(), "最多只能上傳四張圖片");
            }
        } else if (viewId == R.id.id_more) {
            //更多：刪除。發送。再次購買
            String[] functions;
            if (orderState == PurchaseOrderDetailsBean.COMPLETE_RECEIVED) {
                functions = new String[]{"再來一單", "删除"};
            } else {
                functions = new String[]{"再來一單", "删除", "部分收貨", "收貨"};
            }
            new XPopup.Builder(mContext)
                    .atView(v)
                    .hasShadowBg(false)
                    .popupPosition(PopupPosition.Left)
                    .asCustom(new PurchaseListMorePopup(mContext)
                            .setStringData(functions, new int[]{R.drawable.ic_purchase_buy_again, R.drawable.ic_purchase_delete, R.drawable.ic_small_partial_receipt, R.drawable.ic_receipt})
                            .setOnSelectListener(mOnSelectListener))
                    .show();
        } else if (viewId == R.id.tv_order_details_partial_receipt) {
            //部分收貨
            addWarehouse(PurchaseOrderDetailsBean.PART_RECEIVED);
        } else if (viewId == R.id.tv_order_details_receipt) {
            //收貨
            addWarehouse(PurchaseOrderDetailsBean.COMPLETE_RECEIVED);
        } else if (viewId == R.id.layout_remarks) {
            //備註，顯示備註輸入框
            layoutEdRemark.setVisibility(layoutEdRemark.getVisibility() == View.VISIBLE ? View.GONE : View.VISIBLE);
        }
    }

    private void addWarehouse(int state) {
        AppDialog.getInstance().showWaringDialog(requireContext(), "是否確認收貨？", (view, dialog) -> {
            mPresenter.addWarehouse(state, edRemark.getText() + "", totalAmount, orderDetailsFoodAdapter.getData());
            setFragmentResult(RESULT_OK, null);
        });
    }

    private OnSelectListener mOnSelectListener = (position, text) -> {
        if (position == 0) {
            //再來一單
            mPresenter.buyAgainByFoodIds(orderDetailsFoodAdapter.getData());
        } else if (position == 1) {
            //刪除訂單
            AppDialog.getInstance().showWaringDialog(mContext, "是否刪除訂單", (view1, dialog) -> mPresenter.deleteOrder());
        } else if (position == 2) {
            //部分收貨
            addWarehouse(PurchaseOrderDetailsBean.PART_RECEIVED);
        } else if (position == 3) {
            //收貨
            addWarehouse(PurchaseOrderDetailsBean.COMPLETE_RECEIVED);
        }
    };

    @Override
    public void loadOrderDetails(PurchaseOrderDetailsBean orderDetailsBean) {
        if (TextUtil.isNotEmptyOrNullOrUndefined(orderDetailsBean.getWarehousingRemarks())) {
            edRemark.setText(orderDetailsBean.getWarehousingRemarks());
        }
        tvOrderDetailsSupplierName.setText(orderDetailsBean.getSupplierName());
        tvOrderDetailsOrderNo.setText(String.format(getString(R.string.str_format_purchase_no), orderDetailsBean.getOrderNo()));
        if (TextUtil.isNotEmptyOrNullOrUndefined(orderDetailsBean.getWarehousingOrderNo())) {
            tvWarehouseOrderNo.setText(String.format(getString(R.string.str_format_warehouse_no), orderDetailsBean.getWarehousingOrderNo()));
            tvWarehouseOrderNo.setVisibility(View.VISIBLE);
        } else {
            tvWarehouseOrderNo.setVisibility(View.GONE);
        }
        tvOrderDetailsCreateTime.setText(TimeUtils.getStringByFormat(orderDetailsBean.getCreateTime(), TimeUtils.DEFAULT_DATE_FORMAT_YMDHM));
        switch (orderDetailsBean.getStatus()) {
            case PurchaseOrderDetailsBean.WAIT_RECEIVED:
                ivOrderState.setVisibility(View.INVISIBLE);
//                tvOrderDetailsOrderState.setText("待收貨");
                break;
            case PurchaseOrderDetailsBean.PART_RECEIVED:
                ivOrderState.setVisibility(View.VISIBLE);
//                tvOrderDetailsOrderState.setText("部分收貨");
                ivOrderState.setImageResource(R.drawable.ic_partial_receipt);
                break;
            case PurchaseOrderDetailsBean.COMPLETE_RECEIVED:
//                tvOrderDetailsOrderState.setText("已完成");
                ivOrderState.setImageResource(R.drawable.ic_all_receipt);
                break;
            case PurchaseOrderDetailsBean.REFUSE_RECEIVED:
                //拒收
                ivOrderState.setImageResource(R.drawable.ic_refuse_accept);
//                ivOrderState.setImageResource();
                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) {
                        DeputyUnitBean unit = datum.getShowUnit();
                        totalAmount = MoneyUtil.sum(totalAmount, MoneyUtil.priceCalculation(unit.getDeputyValue(), unit.getUnitPrice()));
                    }
                }
                orderDetailsFoodAdapter.notifyDataSetChanged();
                setTotalAmount();
                setTypesOfFood();
            }
        });
    }

    @Override
    public void uploadPicSuccess(String imgUrl) {
        if (imageAdapter == null) {
            imageAdapter = new ImageAdapter(mPresenter.orderState == PurchaseOrderDetailsBean.ALL);
            rvOrderDetailsPictures.setAdapter(imageAdapter);
            rvOrderDetailsPictures.setLayoutManager(new GridLayoutManager(requireContext(), 4));
            imageAdapter.setOnItemChildClickListener((adapter, view, position) -> {
                if (view.getId() == R.id.iv_img_delete) {
                    imageAdapter.removeAt(position);
                    mPresenter.deletePic(position);
                } else if (view.getId() == R.id.iv_img) {
                    //預覽大圖
                    String pic = mPresenter.getPic(position);
                    if (TextUtil.isNotEmptyOrNullOrUndefined(pic)) {
                        new XPopup.Builder(requireContext())
                                .isDestroyOnDismiss(true)
                                .asImageViewer((ImageView) view, pic, true, Color.parseColor("#f1f1f1"), -1, -1, false, -1, new ImageLoader())
                                .show();
                    }
                }
            });
        }
        imageAdapter.addData(imgUrl);
    }

    @Override
    public void buyAgain() {
        startWithPop(ShoppingCatFragment.newInstance());
    }

    public static class ImageLoader implements XPopupImageLoader {
        @Override
        public void loadImage(int position, @NonNull Object url, @NonNull ImageView imageView) {
            //必须指定Target.SIZE_ORIGINAL，否则无法拿到原图，就无法享用天衣无缝的动画
            Glide.with(imageView).load(url).apply(new RequestOptions().override(Target.SIZE_ORIGINAL)).into(imageView);
        }

        @Override
        public File getImageFile(@NonNull Context context, @NonNull Object uri) {
            try {
                return Glide.with(context).downloadOnly().load(uri).submit().get();
            } catch (Exception e) {
                e.printStackTrace();
            }
            return null;
        }
    }

    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.setOnAmountChangeListener((position, value) -> {
            totalAmount = MoneyUtil.sum(totalAmount, value);
            setTotalAmount();
        });
        orderDetailsFoodAdapter.setOnItemClickListener((adapter, view, position) -> {
            PurchaseOrderDetailsBean.PurchaseOrderDetailsInfoVosBean infoVosBean = orderDetailsFoodAdapter.getData().get(position);
//            if(infoVosBean.getStatus() == PurchaseOrderDetailsBean.COMPLETE_RECEIVED){
//                //已經全部收貨的，不讓選中
//                return;
//            }
            infoVosBean.setChecked(!infoVosBean.isChecked());
            adapter.notifyItemChanged(position);
            //修改選中狀態後，重新計算入庫總價
            DeputyUnitBean showUnit = infoVosBean.getShowUnit();
            if (infoVosBean.isChecked()) {
                totalAmount = MoneyUtil.sum(totalAmount, MoneyUtil.priceCalculation(showUnit.getDeputyValue(), showUnit.getUnitPrice()));
                typesOfFood += 1;
            } else {
                totalAmount = MoneyUtil.sub(totalAmount, MoneyUtil.priceCalculation(showUnit.getDeputyValue(), showUnit.getUnitPrice()));
                typesOfFood -= 1;
            }
            //全選
            cbOrderDetailsAllSelected.setChecked(typesOfFood == orderDetailsFoodAdapter.getData().size());
            setTotalAmount();
            setTypesOfFood();
        });
        orderDetailsFoodAdapter.setOnItemChildClickListener((adapter, view, position) -> {
            int id = view.getId();
            if (id == R.id.layout_order_details_unit) {
                //切換單位
                PurchaseOrderDetailsBean.PurchaseOrderDetailsInfoVosBean purchaseOrderDetailsInfoVosBean = orderDetailsFoodAdapter.getData().get(position);
                List<DeputyUnitBean> foodUnits = purchaseOrderDetailsInfoVosBean.getFoodUnits();
//                String[] units = new String[0];
                List<String> units = new ArrayList<>();
                if (foodUnits != null) {
//                    units = new String[foodUnits.size()];
                    for (int i = 0; i < foodUnits.size(); i++) {
//                        units[i] = foodUnits.get(i).getDeputyUnit();
                        units.add(foodUnits.get(i).getDeputyUnit());
                    }
                }
                if (units.size() > 1) {
                    ChooseUnitPopup popup = new ChooseUnitPopup(requireContext()).setStringData(units).setOnSelectListener(new OnSelectListener() {
                        @Override
                        public void onSelect(int position, String text) {
                            //將用戶之前輸入的值，修改到新選擇的單位匯中
                            DeputyUnitBean showUnit = purchaseOrderDetailsInfoVosBean.getShowUnit();
                            DeputyUnitBean deputyUnitBean = foodUnits.get(position);
                            deputyUnitBean.setDeputyValue(showUnit.getDeputyValue());
                            deputyUnitBean.setUnitPrice(showUnit.getUnitPrice());
                            purchaseOrderDetailsInfoVosBean.setShowUnit(deputyUnitBean);
                            orderDetailsFoodAdapter.notifyItemChanged(position);
                        }
                    });
                    new XPopup.Builder(getContext())
                            .hasShadowBg(false)
                            .atView(view)  // 依附于所点击的View，内部会自动判断在上方或者下方显示
                            .asCustom(popup)
                            .show();
                }
            }
        });
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == SelectPicture.CHOOSE_PHOTO && resultCode == RESULT_OK) {
            //從相冊選取完圖片之後
            if (data != null) {
                Uri uri = data.getData();
                if (uri != null) {
                    File file = SelectPicture.getInstance().uriToFileApiQ(requireContext(), uri);
                    SelectPicture.getInstance().crop(Uri.fromFile(file), this);
                }
            }
        } else if (requestCode == SelectPicture.TAKE_PHOTO && resultCode == RESULT_OK) {
            //拍照
            //拍照完成後需要裁剪
            SelectPicture.getInstance().crop(SelectPicture.getInstance().getmCameraUri(), this);
        } else if (requestCode == REQUEST_CROP && resultCode == RESULT_OK && data != null) {
            final Uri resultUri = UCrop.getOutput(data);
            if (resultUri != null) {
                String filePath = FileUtils.getFilePathByUri(mContext, resultUri);
                if (!TextUtils.isEmpty(filePath)) {
                    mPresenter.uploadPic(filePath);
                }
            }
        }
    }
}
