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

import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
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.QMUIDialog;
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.OrderProcessAdapter;
import com.wd.workoffice.ui.adapter.SupplierOrderDetailProductAdapter;
import com.wd.workoffice.util.DialogUtils;
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 SupplierOrderDetailActivity 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_place_dep)
    TextView tvPlaceDep;
    @BindView(R.id.tv_warehouse)
    TextView tvWarehouse;
    @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;
    private OrderDetail dataBean;
    private List<OrderDetail.OrderFlowsBean> flowList;
    private OrderProcessAdapter flowAdapter;
    private SupplierOrderDetailProductAdapter proAdapter;
    private List<OrderDetail.OrderItemsBean> proList;
    private Integer status;
    private String identity;
    private QMUIDialog.MenuDialogBuilder settingDialog;

    @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");
        if (TextUtils.equals(identity, "1")) {//1销售 2生产

        } else {
            rlDep.setVisibility(View.GONE);
        }
    }

    private void changeView() {
        switch (status) {
//          {"待审核", "待接单", "待生产", "已入库","已交付"};
//          { "100", "200", "710", "500","600"};
            case 100:
                if (WorkUtils.orderCheckPermission(3,dataBean.getLaunchDeptId())){
                    llBottom.setVisibility(View.VISIBLE);
                    llCheck.setVisibility(View.VISIBLE);
                }
                break;
            case 200:
                if (WorkUtils.orderReceivePermission(3, dataBean.getReceiveDeptId())) {
                    llBottom.setVisibility(View.VISIBLE);
                    llCheck.setVisibility(View.VISIBLE);
                    tvAgree.setText("接单");
                    tvRefuse.setText("拒单");
                }
                break;
            case 300:
                break;
            case 410:
                break;
            case 500:
                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 SupplierOrderDetailProductAdapter(R.layout.item_order_product, proList, status);
        proAdapter.bindToRecyclerView(rvPro);
        proAdapter.setEmptyView(R.layout.view_empty_order, rvPro);
    }

    private void getData() {
        RtfUtils.getRtf().supplierOrderDetail(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();
                changeView();
                flowList.addAll(dataBean.getOrderFlows());
                flowAdapter.notifyDataSetChanged();
                proList.addAll(dataBean.getOrderItems());
                proAdapter.notifyDataSetChanged();

                tvName.setText(dataBean.getSupplierName());
                tvDep.setText(dataBean.getReceiveDeptName());
                tvStatus.setText(dataBean.getStatusName());
                tvPlaceName.setText(dataBean.getLaunchUserName());
                tvPlaceDep.setText(dataBean.getLaunchDeptName());
                tvWarehouse.setText(dataBean.getInStockName());
                tvOrderNo.setText(dataBean.getId());
                tvTime.setText(dataBean.getCreatedTime());
                tvSendTime.setText(dataBean.getRequireTime());
                tvOrderDesc.setText(dataBean.getAttrName());
                tvPrice.setText(String.valueOf(dataBean.getLaunchOrderAmount()));

                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(),
                                "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(),
                                "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,
                                "orderType", dataBean.getExpandInfo().getOrderType(),
                                "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_supplier_order;
    }


    @OnClick({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.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", 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,
                        "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);
        etRemark.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                tvNum.setText(s.length() + "/140");
            }
        });
        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().supplierOrderCheck(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);
        etRemark.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                tvNum.setText(s.length() + "/140");
            }
        });
        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().supplierOrderApplyCheck(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);
            }
        });
    }
}
