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.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.retrofit.RtfUtils;
import com.wd.workoffice.retrofit.WorkObserver;
import com.wd.workoffice.ui.activity.mes.ImageActivity;
import com.wd.workoffice.ui.adapter.InsideOrderDetailProductAdapter;
import com.wd.workoffice.ui.adapter.OrderProcessAdapter;
import com.wd.workoffice.util.HwObsUtil;
import com.wd.workoffice.util.MathUtils;
import com.wd.workoffice.util.WorkUtils;

import org.greenrobot.eventbus.EventBus;

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 InsideOrderDetailActivity 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_check)
    LinearLayout llCheck;
    @BindView(R.id.tv_finish_apply)
    TextView tvFinishApply;
    @BindView(R.id.tv_send_apply)
    TextView tvSendApply;
    @BindView(R.id.ll_apply)
    LinearLayout llApply;
    @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_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_desc)
    TextView tvOrderDesc;
    @BindView(R.id.tv_price)
    TextView tvPrice;
    @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.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;
    @BindView(R.id.tv_pick_apply)
    TextView tvPickApply;
    @BindView(R.id.view_pick_apply)
    View viewPickApply;
    @BindView(R.id.fl_pick_apply)
    FrameLayout flPickApply;
    @BindView(R.id.tv_order_type)
    TextView tvOrderType;
    private OrderDetail dataBean;
    private List<OrderDetail.OrderFlowsBean> flowList;
    private OrderProcessAdapter flowAdapter;
    private InsideOrderDetailProductAdapter 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));
        if (!TextUtils.isEmpty(getIntent().getStringExtra("status"))) {
            status = Integer.valueOf(getIntent().getStringExtra("status"));
        }
        identity = getIntent().getStringExtra("identity");
        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 changeView() {
        switch (status) {
//          {"待审核", "待接单", "待生产", "已入库","已交付"};
//          { "100", "200", "710", "500","600"};
            case 100:
                if (WorkUtils.orderCheckPermission(4, dataBean.getLaunchDeptId())) {
                    llBottom.setVisibility(View.VISIBLE);
                    llCheck.setVisibility(View.VISIBLE);
                }
                break;
            case 200:
                if (WorkUtils.orderReceivePermission(4, 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);
                break;
            case 300:
//                llBottom.setVisibility(View.GONE);
//                llCheck.setVisibility(View.GONE);
                llBottom.setVisibility(View.VISIBLE);
                llCheck.setVisibility(View.GONE);
                llApply.setVisibility(View.GONE);
                break;
            case 320:
//                llBottom.setVisibility(View.GONE);
                llBottom.setVisibility(View.VISIBLE);
                llCheck.setVisibility(View.GONE);
                llApply.setVisibility(View.GONE);
                break;
            case 410:
                llBottom.setVisibility(View.VISIBLE);
                llCheck.setVisibility(View.GONE);
                llApply.setVisibility(View.GONE);
                break;
            case 420:
                llBottom.setVisibility(View.VISIBLE);
                llCheck.setVisibility(View.GONE);
                llApply.setVisibility(View.GONE);
                break;
            case 500:
                llBottom.setVisibility(View.VISIBLE);
                llCheck.setVisibility(View.GONE);
                llApply.setVisibility(View.GONE);
                break;
            case 600:
                llBottom.setVisibility(View.VISIBLE);
                llCheck.setVisibility(View.GONE);
                llApply.setVisibility(View.GONE);
                break;
            default:
                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 InsideOrderDetailProductAdapter(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().insideOrderDetail(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);
                status = dataBean.getStatus();
                flowSheetList.clear();
                flowList.clear();
                proList.clear();
                changeView();
                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.addAll(dataBean.getOrderItems());
                proAdapter.setStatus(dataBean.getStatus());
                proAdapter.notifyDataSetChanged();

                tvName.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());
                tvOrderDesc.setText(dataBean.getAttrName());
                tvPrice.setText(MathUtils.converData(dataBean.getLaunchOrderAmount(), 3));

                tvOrderType.setText(WorkUtils.getInsideOrderType(dataBean.getType(),dataBean.getBusinessFormat()));

                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());
                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.ll_annex:
                        if (!TextUtils.isEmpty(proList.get(position).getAnnex()))
                            startActivity(ImageActivity.class, "url", HwObsUtil.IMG_DOMAIN + proList.get(position).getAnnex());
                        break;
                    case R.id.tv_get:
                        startActivity(UseApplyActivity.class,
                                "status", dataBean.getStatus() + "",
                                "orderType", dataBean.getExpandInfo().getOrderType(),
                                "customerId", dataBean.getCustomerId() + "",
                                "num", proList.get(position).getCanUseProductSum() + "",
                                "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() + "",
                                "enterStockType", dataBean.getEnterStockType(),
                                "deptId", dataBean.getLaunchDeptId() + "",
                                "returnNum", TextUtils.equals(dataBean.getEnterStockType(), "1") ?
                                        proList.get(position).getCanOutReturnSum() : proList.get(position).getCanUsedReturnSum(),
                                "orderType", dataBean.getExpandInfo().getOrderType(),
                                "num", proList.get(position).getCanUseProductSum() + "",
                                "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;
                    case R.id.tv_quality:
                        startActivity(QualityApplyActivity.class,
                                "status", dataBean.getStatus() + "",
                                "orderType", dataBean.getExpandInfo().getOrderType(),
                                "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_inside_order;
    }


    @OnClick({R.id.tv_pick_apply, 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 {
                    checkDialog(1);
                }
                break;
            case R.id.tv_finish_apply:
                if (dataBean == null) {
                    toast("正在加载中，请稍后");
                    return;
                }
                startActivity(EndApplyActivity.class,
                        "status", dataBean.getStatus() + "",
                        "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;
            case R.id.tv_pick_apply:
                if (dataBean == null) {
                    toast("正在加载中，请稍后");
                    return;
                }
                startActivity(PickApplyActivity.class,
                        "status", getIntent().getStringExtra("status"),
                        "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(String.valueOf(dataBean.getLaunchOrderAmount()));
        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().insideOrderCheck(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("操作成功");
                getData();
                EventBus.getDefault().post(new CheckOrderEvent());
            }
        });
    }

    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 (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().insideOrderApplyCheck(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
    protected void onResume() {
        super.onResume();
        if (null != dataBean) {//刷新红点
            getProCheckStatus(dataBean.getId());
        }
    }

}
