package com.wd.workoffice.ui.activity.bat.order;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.qmuiteam.qmui.widget.dialog.QMUIBottomSheet;
import com.qmuiteam.qmui.widget.dialog.QMUIDialog;
import com.qmuiteam.qmui.widget.dialog.QMUIDialogAction;
import com.wd.workoffice.R;
import com.wd.workoffice.app.BaseBean;
import com.wd.workoffice.app.WorkToolBarActivity;
import com.wd.workoffice.bean.OrderCheckStatusBean;
import com.wd.workoffice.bean.OrderDetail;
import com.wd.workoffice.bean.event.CheckOrderEvent;
import com.wd.workoffice.bean.event.CheckSendEvent;
import com.wd.workoffice.retrofit.RtfUtils;
import com.wd.workoffice.retrofit.WorkObserver;
import com.wd.workoffice.ui.adapter.OrderDetailProductAdapter;
import com.wd.workoffice.ui.adapter.OrderProcessAdapter;
import com.wd.workoffice.util.DialogUtils;
import com.wd.workoffice.util.MathUtils;
import com.wd.workoffice.util.WorkUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

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

import androidx.appcompat.app.AlertDialog;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import flexible.xd.android_base.network.rtfhttp.Transformer;
import io.reactivex.disposables.Disposable;

/**
 * 销售订单详情
 * author : flexible
 * email : lgd19940421@163.com
 * github: https://github.com/FlexibleXd
 **/
public class SaleOrderDetailActivity extends WorkToolBarActivity {
    @BindView(R.id.tv_status)
    TextView tvStatus;
    @BindView(R.id.tv_desc)
    TextView tvDesc;
    @BindView(R.id.ll_top)
    RelativeLayout llTop;
    @BindView(R.id.tv_refuse)
    TextView tvRefuse;
    @BindView(R.id.tv_agree)
    TextView tvAgree;
    @BindView(R.id.ll_bottom)
    LinearLayout llBottom;
    @BindView(R.id.rv_process)
    RecyclerView rvProcess;
    @BindView(R.id.tv_name)
    TextView tvName;
    @BindView(R.id.tv_dep)
    TextView tvDep;
    @BindView(R.id.tv_place_name)
    TextView tvPlaceName;
    @BindView(R.id.tv_company)
    TextView tvCompany;
    @BindView(R.id.tv_order_no)
    TextView tvOrderNo;
    @BindView(R.id.tv_time)
    TextView tvTime;
    @BindView(R.id.tv_send_time)
    TextView tvSendTime;
    @BindView(R.id.tv_order_price)
    TextView tvOrderPrice;
    @BindView(R.id.rv_pro)
    RecyclerView rvPro;
    @BindView(R.id.tv_claim1)
    TextView tvClaim1;
    @BindView(R.id.tv_claim2)
    TextView tvClaim2;
    @BindView(R.id.tv_claim3)
    TextView tvClaim3;
    @BindView(R.id.tv_claim4)
    TextView tvClaim4;
    @BindView(R.id.tv_claim5)
    TextView tvClaim5;
    @BindView(R.id.tv_claim6)
    TextView tvClaim6;
    @BindView(R.id.tv_finish_apply)
    TextView tvFinishApply;
    @BindView(R.id.tv_send_apply)
    TextView tvSendApply;
    @BindView(R.id.ll_sale)
    LinearLayout llSale;
    @BindView(R.id.ll_check)
    LinearLayout llCheck;
    @BindView(R.id.ll_apply)
    LinearLayout llApply;
    @BindView(R.id.rl_dep)
    RelativeLayout rlDep;
    @BindView(R.id.ll_see_more)
    LinearLayout llSeeMore;
    @BindView(R.id.view_finish_apply)
    View viewFinishApply;
    @BindView(R.id.fl_finish_apply)
    FrameLayout flFinishApply;
    @BindView(R.id.view_send_apply)
    View viewSendApply;
    @BindView(R.id.fl_send_apply)
    FrameLayout flSendApply;
    private OrderDetail dataBean;
    private List<OrderDetail.OrderFlowsBean> flowList;
    private OrderProcessAdapter flowAdapter;
    private OrderDetailProductAdapter proAdapter;
    private List<OrderDetail.OrderItemsBean> proList;
    private Integer status;
    private String identity;
    private QMUIBottomSheet flowSheet;
    private RecyclerView rvFlowSheet;
    private List<OrderDetail.OrderFlowsBean> flowSheetList;
    private OrderProcessAdapter flowSheetAdapter;

    @Override
    protected void initView() {
        ButterKnife.bind(this);
        rvPro.setLayoutManager(new LinearLayoutManager(this, RecyclerView.VERTICAL, false));
        rvProcess.setLayoutManager(new LinearLayoutManager(this, RecyclerView.VERTICAL, false));
        identity = getIntent().getStringExtra("identity");
        if (TextUtils.equals(identity, "1")) {//销售1

        } else {
            rlDep.setVisibility(View.GONE);
        }
        if (!TextUtils.isEmpty(getIntent().getStringExtra("status"))) {
            status = Integer.valueOf(getIntent().getStringExtra("status"));
        }
        View viewData = LayoutInflater.from(this).inflate(R.layout.view_rv, null);
        rvFlowSheet = viewData.findViewById(R.id.rv_data);
        rvFlowSheet.setLayoutManager(new LinearLayoutManager(this, RecyclerView.VERTICAL, false));
        flowSheet = new QMUIBottomSheet(this);
        flowSheet.addContentView(viewData);
        flowSheetList = new ArrayList<>();
        flowSheetAdapter = new OrderProcessAdapter(R.layout.item_order_process, flowSheetList);
        flowSheetAdapter.bindToRecyclerView(rvFlowSheet);
        flowSheetAdapter.setEmptyView(R.layout.view_empty_order, rvFlowSheet);
    }

    private void changView(Integer status) {
        switch (status) {
//            private String tab[] = {
//            "全部", "待审核", "待接单", "待生产", "已入库",
//            "已交付"};
//    private String order[] = {
//            "", "100", "200", "710", "500",
//            "600"};
            case 100:
                if (WorkUtils.orderCheckPermission(1, dataBean.getLaunchDeptId())) {
                    llBottom.setVisibility(View.VISIBLE);
                    llCheck.setVisibility(View.VISIBLE);
                }
                break;
            case 200:
                if (WorkUtils.orderReceivePermission(1, dataBean.getReceiveDeptId())) {
                    llBottom.setVisibility(View.VISIBLE);
                    llCheck.setVisibility(View.VISIBLE);
                    tvAgree.setText("接单");
                    tvRefuse.setText("拒单");
                }else {
                    llBottom.setVisibility(View.GONE);
                    llCheck.setVisibility(View.GONE);
                }
                break;
            case 220:
                    llBottom.setVisibility(View.GONE);
                    llCheck.setVisibility(View.GONE);
                break;
            case 300:
                llBottom.setVisibility(View.VISIBLE);
                llApply.setVisibility(View.VISIBLE);
                llCheck.setVisibility(View.GONE);
                break;
            case 320:
                llBottom.setVisibility(View.GONE);
                break;
            case 410:
                llBottom.setVisibility(View.VISIBLE);
                llApply.setVisibility(View.VISIBLE);
                break;
            case 420:
                llBottom.setVisibility(View.VISIBLE);
                llApply.setVisibility(View.VISIBLE);
                if (dataBean != null && dataBean.getAttr() == 400) {
                    llBottom.setVisibility(View.GONE);
                    llApply.setVisibility(View.GONE);
                }
                break;
            case 500:
                llBottom.setVisibility(View.VISIBLE);
                llApply.setVisibility(View.VISIBLE);
                break;
            case 600:
                llBottom.setVisibility(View.VISIBLE);
                llApply.setVisibility(View.VISIBLE);
                break;
            default:
                llBottom.setVisibility(View.VISIBLE);
                llApply.setVisibility(View.VISIBLE);
                break;
        }
    }

    @Override
    protected void initData() {
        getData();
        flowList = new ArrayList<>();
        flowAdapter = new OrderProcessAdapter(R.layout.item_order_process, flowList);
        flowAdapter.bindToRecyclerView(rvProcess);
        flowAdapter.setEmptyView(R.layout.view_empty_order, rvProcess);
        proList = new ArrayList<>();
        proAdapter = new OrderDetailProductAdapter(R.layout.item_order_product, proList, status == null ? 0 : status);
        proAdapter.bindToRecyclerView(rvPro);
        proAdapter.setEmptyView(R.layout.view_empty_order, rvPro);
    }

    private void getData() {
        RtfUtils.getRtf().saleOrderDetail(getIntent().getStringExtra("id"), "3").compose(Transformer.schedule()).subscribe(new WorkObserver<BaseBean>() {

            @Override
            public void doOnSubscribe(Disposable d) {
            }

            @Override
            public void onFail(String errorMsg) {
                hideLoading();
                toast(errorMsg);
            }

            @Override
            public void onSuccess(BaseBean data) {
                hideLoading();
                if (data.getCode() != 0) {
                    toast(data.getMessage());
                    return;
                }
                dataBean = JSON.parseObject(data.getData().toString(), OrderDetail.class);
                flowSheetList.clear();
                flowList.clear();
                flowSheetList.addAll(dataBean.getOrderFlows());
                flowSheetAdapter.notifyDataSetChanged();
                if (dataBean.getOrderFlows().size() <= 3) {
                    llSeeMore.setVisibility(View.GONE);
                    flowList.addAll(dataBean.getOrderFlows());
                } else {
                    flowList.addAll(dataBean.getOrderFlows().subList(0, 3));
                }
                flowAdapter.notifyDataSetChanged();
                proList.clear();
                proList.addAll(dataBean.getOrderItems());
                proAdapter.setStatus(dataBean.getStatus());
                proAdapter.setAttr(dataBean.getAttr());
                proAdapter.notifyDataSetChanged();
                tvName.setText(dataBean.getCustomerName());
                tvDep.setText(dataBean.getReceiveDeptName());
                tvStatus.setText(dataBean.getStatusName());
                tvPlaceName.setText(dataBean.getLaunchUserName());
                tvCompany.setText(dataBean.getLaunchDeptName());
                tvOrderNo.setText(dataBean.getId());
                tvTime.setText(dataBean.getCreatedTime());
                tvSendTime.setText(dataBean.getRequireTime());
                tvDesc.setText(dataBean.getAttrName());
                tvOrderPrice.setText(MathUtils.converData(dataBean.getLaunchOrderAmount(), 3));

                OrderDetail.ExpandInfoBean expandInfo = dataBean.getExpandInfo();
                tvClaim1.setText(expandInfo.getDemond4());
                tvClaim2.setText(expandInfo.getDemond5());
                tvClaim3.setText(expandInfo.getDemond1());
                tvClaim4.setText(expandInfo.getDemond2());
                tvClaim5.setText(expandInfo.getDemond3());
                tvClaim6.setText(expandInfo.getComments());

                tvDesc.setText(dataBean.getAttrName());
                tvStatus.setText(dataBean.getStatusName());
                status = dataBean.getStatus();
                changView(dataBean.getStatus());
                getProCheckStatus(dataBean.getId());
            }
        });
    }

    @Override
    protected void initEvent() {
        proAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                switch (view.getId()) {
                    case R.id.tv_get:
                        startActivity(UseApplyActivity.class,
                                "status", dataBean.getStatus() + "",
                                "orderType", dataBean.getExpandInfo().getOrderType(),
                                "num", proList.get(position).getCanUseProductSum() + "",
                                "customerId", dataBean.getCustomerId() + "",
                                "product", proList.get(position).getProductName(),
                                "simpleCode", proList.get(position).getProductSimpleCode(),
                                "orderId", getIntent().getStringExtra("id"),
                                "orderItemId", proList.get(position).getId(),
                                "usedStore",dataBean.getUsedStore(),
                                "usedStoreName",dataBean.getUsedStore(),
                                "productId", proList.get(position).getProductId() + "");
                        break;
                    case R.id.tv_add:
                        startActivity(AddStockApplyActivity.class,
                                "status", dataBean.getStatus() + "",
                                "orderType", dataBean.getExpandInfo().getOrderType(),
                                "num", proList.get(position).getCanInStoreProductSum() + "",
                                "product", proList.get(position).getProductName(),
                                "simpleCode", proList.get(position).getProductSimpleCode(),
                                "orderId", getIntent().getStringExtra("id"),
                                "orderItemId", proList.get(position).getId(),
                                "productId", proList.get(position).getProductId() + "");
                        break;
                    case R.id.tv_return:
                        startActivity(ReturnApplyActivity.class,
                                "identity", identity,
                                "status", dataBean.getStatus() + "",
                                "num", proList.get(position).getCanUseProductSum() + "",
                                "enterStockType", dataBean.getEnterStockType(),
                                "deptId", dataBean.getLaunchDeptId() + "",
                                "returnNum", proList.get(position).getCanUseProductSum() + "",
                                "orderType", dataBean.getExpandInfo().getOrderType(),
                                "product", proList.get(position).getProductName(),
                                "simpleCode", proList.get(position).getProductSimpleCode(),
                                "orderId", getIntent().getStringExtra("id"),
                                "orderItemId", proList.get(position).getId(),
                                "productId", proList.get(position).getProductId() + "");
                        break;
                    case R.id.tv_flow:
                        startActivity(ProFlowActivity.class,
                                "status", dataBean.getStatus() + "",
                                "num", proList.get(position).getStoreSum() + "",
                                "product", proList.get(position).getProductName(),
                                "simpleCode", proList.get(position).getProductSimpleCode(),
                                "orderId", getIntent().getStringExtra("id"),
                                "productId", proList.get(position).getProductId() + "",
                                "orderItemId", proList.get(position).getId(),
                                "info", JSON.toJSONString(proList.get(position)));
                        break;
                }
            }
        });
    }

    @Override
    protected int layoutId() {
        return R.layout.activity_sale_order;
    }


    @OnClick({R.id.ll_see_more, R.id.tv_finish_apply, R.id.tv_send_apply, R.id.tv_refuse, R.id.tv_agree})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.ll_see_more:
                flowSheet.show();
                break;
            case R.id.tv_refuse:
                if (status == 200) {
                    checkReceiveDialog(2, dataBean.getId());
                } else {
                    checkDialog(2);
                }
                break;
            case R.id.tv_agree:
                if (status == 200) {
                    checkReceiveDialog(1, dataBean.getId());
                } else {
                    boolean hasBeyond = false;
                    for (OrderDetail.OrderItemsBean orderItemsBean : proList) {
                        if (orderItemsBean.getProductBeyondCount() > 0d) {
                            hasBeyond = true;
                        }
                    }
                    if (hasBeyond) {
                        QMUIDialog.MessageDialogBuilder dialog = DialogUtils.okAndCancelDialog(SaleOrderDetailActivity.this);
                        dialog.setTitle("产品超出安全库存").setMessage("是否继续").addAction("取消", new QMUIDialogAction.ActionListener() {
                            @Override
                            public void onClick(QMUIDialog dialog, int index) {
                                dialog.dismiss();
                            }
                        }).addAction("确定", new QMUIDialogAction.ActionListener() {
                            @Override
                            public void onClick(QMUIDialog dialog, int index) {
                                checkDialog(1);
                                dialog.dismiss();
                            }
                        }).show();
                    } else {
                        checkDialog(1);
                    }
                }
                break;
            case R.id.tv_finish_apply:
                if (dataBean == null) {
                    toast("正在加载中，请稍后");
                    return;
                }
                startActivity(EndApplyActivity.class,
                        "status", getIntent().getStringExtra("status"),
                        "orderType", dataBean.getExpandInfo().getOrderType(),
                        "orderId", getIntent().getStringExtra("id"));
                break;
            case R.id.tv_send_apply:
                if (dataBean == null) {
                    toast("正在加载中，请稍后");
                    return;
                }
                startActivity(SendApplyActivity.class,
                        "status", dataBean.getStatus() + "",
                        "orderType", dataBean.getExpandInfo().getOrderType(),
                        "orderId", getIntent().getStringExtra("id"));
                break;
        }
    }

    private void checkDialog(int status) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        View view = LayoutInflater.from(this).inflate(R.layout.view_check_order, null);
        TextView tvOk = view.findViewById(R.id.tv_ok);
        TextView tvPrice = view.findViewById(R.id.tv_price);
        tvPrice.setText(MathUtils.converData(dataBean.getLaunchOrderAmount(), 3));
        TextView tvNum = view.findViewById(R.id.tv_num);
        TextView tvCancel = view.findViewById(R.id.tv_cancel);
        EditText etRemark = view.findViewById(R.id.et_content);
        WorkUtils.addNumListener(etRemark, tvNum);
        builder.setView(view);
        AlertDialog addCartDialog = builder.create();
        tvOk.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (status != 1 && TextUtils.isEmpty(etRemark.getText().toString())) {
                    toast("请填写备注");
                    return;
                }
                check(status, etRemark.getText().toString());
                addCartDialog.dismiss();
            }
        });
        tvCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                addCartDialog.dismiss();
            }
        });
        addCartDialog.show();
    }


    private void check(int status, String remark) {
        Map<String, Object> dataParam = WorkUtils.simpleParam();
        dataParam.put("result", status);
        dataParam.put("comment", remark);
        RtfUtils.getRtf().saleOrderCheck(dataBean.getId(), WorkUtils.convertMapToBody(dataParam)).compose(Transformer.schedule()).subscribe(new WorkObserver<BaseBean>() {
            @Override
            public void doOnSubscribe(Disposable d) {
            }

            @Override
            public void onFail(String errorMsg) {
                hideLoading();
                toast(errorMsg);
            }

            @Override
            public void onSuccess(BaseBean data) {
                hideLoading();
                if (data.getCode() != 0) {
                    toast(data.getMessage());
                    return;
                }
                toast("操作成功");
                EventBus.getDefault().post(new CheckOrderEvent());
                getData();
            }
        });
    }

    private void checkReceiveDialog(int status, String id) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        View view = LayoutInflater.from(this).inflate(R.layout.view_check, null);
        TextView tvOk = view.findViewById(R.id.tv_ok);
        TextView tvDesc = view.findViewById(R.id.tv_desc);
        tvDesc.setText(status == 1 ? "统一接单" : "拒绝接单");
        TextView tvNum = view.findViewById(R.id.tv_num);
        TextView tvCancel = view.findViewById(R.id.tv_cancel);
        EditText etRemark = view.findViewById(R.id.et_content);
        WorkUtils.addNumListener(etRemark, tvNum);
        builder.setView(view);
        AlertDialog addCartDialog = builder.create();
        tvOk.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (status != 1 && TextUtils.isEmpty(etRemark.getText().toString()) && status == 2) {
                    toast("请填写备注");
                    return;
                }
                checkReceive(status, etRemark.getText().toString(), id);
                addCartDialog.dismiss();
            }
        });
        tvCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                addCartDialog.dismiss();
            }
        });
        addCartDialog.show();
    }


    private void checkReceive(int status, String remark, String id) {
        Map<String, Object> param = WorkUtils.simpleParam();
        param.put("result", status);
        param.put("comment", remark);
        param.put("id", id);
        RtfUtils.getRtf().saleOrderApplyCheck(id + "", WorkUtils.convertMapToBody(param)).compose(Transformer.schedule()).subscribe(new WorkObserver<BaseBean>() {
            @Override
            public void doOnSubscribe(Disposable d) {
            }

            @Override
            public void onFail(String errorMsg) {
                hideLoading();
                toast(errorMsg);
            }

            @Override
            public void onSuccess(BaseBean data) {
                hideLoading();
                if (data.getCode() != 0) {
                    toast(data.getMessage());
                    return;
                }
                toast("操作成功");
                EventBus.getDefault().post(new CheckOrderEvent());
                getData();
            }
        });
    }

    /**
     * 获取按钮红点显示
     * @param id
     */
    private void getProCheckStatus(String id) {
        RtfUtils.getRtf().orderProCheckStatus(id).compose(Transformer.schedule()).subscribe(new WorkObserver<BaseBean>() {
            @Override
            public void doOnSubscribe(Disposable d) {
            }

            @Override
            public void onFail(String errorMsg) {
                hideLoading();
                toast(errorMsg);
            }

            @Override
            public void onSuccess(BaseBean data) {
                hideLoading();
                if (data.getCode() != 0) {
                    toast(data.getMessage());
                    return;
                }
                OrderCheckStatusBean orderCheckStatusBean = JSON.parseObject(data.getData().toString(), OrderCheckStatusBean.class);
                viewFinishApply.setVisibility(orderCheckStatusBean.getAdvance() ? View.VISIBLE : View.GONE);
                viewSendApply.setVisibility(orderCheckStatusBean.isOutStore() ? View.VISIBLE : View.GONE);
                proAdapter.setProStatusList(orderCheckStatusBean.getItems());
            }
        });
    }


    @Override
    public void onStart() {
        super.onStart();
        EventBus.getDefault().register(this);
    }

    @Override
    public void onStop() {
        super.onStop();
        EventBus.getDefault().unregister(this);
    }

    @Subscribe
    public void refresh(CheckSendEvent event) {
        getData();
    }

}
