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.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.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.adapter.CruibleOrderDetailProductAdapter;
import com.wd.workoffice.ui.adapter.OrderProcessAdapter;
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.Observable;
import io.reactivex.disposables.Disposable;

/**
 * 坩埚详情
 * author : flexible
 * email : lgd19940421@163.com
 * github: https://github.com/FlexibleXd
 **/
public class CrucibleOrderDetailActivity 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_dep)
    TextView tvDep;
    @BindView(R.id.rl_dep)
    RelativeLayout rlDep;
    @BindView(R.id.tv_place_name)
    TextView tvPlaceName;
    @BindView(R.id.tv_company)
    TextView tvCompany;
    @BindView(R.id.tv_stock)
    TextView tvStock;
    @BindView(R.id.rl_stock)
    RelativeLayout rlStock;
    @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;
    private OrderDetail dataBean;
    private List<OrderDetail.OrderFlowsBean> flowList;
    private OrderProcessAdapter flowAdapter;
    private CruibleOrderDetailProductAdapter proAdapter;
    private List<OrderDetail.OrderItemsBean> proList;
    private Integer status;
    private String identity;
    private String type;
    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));
        status = Integer.valueOf(getIntent().getStringExtra("status"));
        identity = getIntent().getStringExtra("identity");
        type = getIntent().getStringExtra("type");
        if (TextUtils.equals(type, "1")) {//1 坩埚生产  2 坩埚销售
            rlDep.setVisibility(View.GONE);
            rlStock.setVisibility(View.GONE);
        } else {

        }
        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(6, dataBean.getLaunchDeptId())) {
                    llBottom.setVisibility(View.VISIBLE);
                    llCheck.setVisibility(View.VISIBLE);
                }
                break;
            case 200:
                if (WorkUtils.orderReceivePermission(6, dataBean.getReceiveDeptId())) {
                    llBottom.setVisibility(View.VISIBLE);
                    llCheck.setVisibility(View.VISIBLE);
                    tvAgree.setText("接单");
                    tvRefuse.setText("拒单");
                }
                break;
            case 300:
                llBottom.setVisibility(View.VISIBLE);
                llApply.setVisibility(View.VISIBLE);
                tvSendApply.setVisibility(View.GONE);
                break;
            case 410:
                llBottom.setVisibility(View.VISIBLE);
                llApply.setVisibility(View.VISIBLE);
                tvSendApply.setVisibility(View.GONE);
                break;
            case 420:
                llBottom.setVisibility(View.VISIBLE);
                llApply.setVisibility(View.VISIBLE);
                tvSendApply.setVisibility(View.GONE);
                break;
            case 500:
                if (TextUtils.equals(type, "1")) {//1坩埚生产 2 坩埚销售
                    llBottom.setVisibility(View.VISIBLE);
                    llApply.setVisibility(View.VISIBLE);
                    tvSendApply.setVisibility(View.GONE);
                } else {
                    llBottom.setVisibility(View.VISIBLE);
                    llApply.setVisibility(View.VISIBLE);
                    tvFinishApply.setVisibility(View.GONE);
                }
                break;
            case 600:
                break;
            default:
                llBottom.setVisibility(View.VISIBLE);
                llApply.setVisibility(View.VISIBLE);
                tvSendApply.setVisibility(View.GONE);
                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 CruibleOrderDetailProductAdapter(R.layout.item_order_product, proList, status);
        proAdapter.bindToRecyclerView(rvPro);
        proAdapter.setEmptyView(R.layout.view_empty_order, rvPro);
    }

    private void getData() {
        Observable<BaseBean> observable;
        if (TextUtils.equals(type, "1")) {//1坩埚生产 2 坩埚销售
            observable = RtfUtils.getRtf().crucibleOrderDetail(getIntent().getStringExtra("id"), "3");
        } else {
            observable = RtfUtils.getRtf().crucibleSaleOrderDetail(getIntent().getStringExtra("id"), "3");
        }
        observable.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();
                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());
                tvDep.setText(dataBean.getReceiveDeptName());
                tvStatus.setText(dataBean.getStatusName());
                tvPlaceName.setText(dataBean.getLaunchUserName());
                tvCompany.setText(dataBean.getLaunchDeptName());
                tvStock.setText(dataBean.getInStockName());
                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));

                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());

            }
        });
    }

    @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(),
                                "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(),
                                "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_crucible_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 {
                    checkDialog(1);
                }
                break;
            case R.id.tv_finish_apply:
                if (dataBean == null) {
                    toast("正在加载中，请稍后");
                    return;
                }
                startActivity(AddCrucibleActivity.class,
                        "status", dataBean.getStatus() + "",
                        "pro", JSON.toJSONString(dataBean.getOrderItems()),
                        "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 (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().crucibleOrderCheck(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("操作成功");
                llBottom.setVisibility(View.GONE);
                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().crucibleApplyCheck(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());
                llBottom.setVisibility(View.GONE);
                finish();
            }
        });
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }
}
