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

import android.content.Intent;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bigkoo.pickerview.listener.OnTimeSelectListener;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.JsonObject;
import com.wd.workoffice.R;
import com.wd.workoffice.app.BaseBean;
import com.wd.workoffice.app.WorkToolBarActivity;
import com.wd.workoffice.bean.AddStockChooseBean;
import com.wd.workoffice.bean.OrderDetail;
import com.wd.workoffice.bean.event.CheckSendEvent;
import com.wd.workoffice.bean.event.SendWeightEvent;
import com.wd.workoffice.bean.workEnum.OrderType;
import com.wd.workoffice.retrofit.RtfUtils;
import com.wd.workoffice.retrofit.WorkObserver;
import com.wd.workoffice.ui.activity.bat.store.StoreSaleClientActivity;
import com.wd.workoffice.ui.adapter.SendApplyAddCrucibleAdapter;
import com.wd.workoffice.util.MathUtils;
import com.wd.workoffice.util.PickTimeUtils;
import com.wd.workoffice.util.WorkUtils;

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

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import androidx.annotation.Nullable;
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 flexible.xd.android_base.utils.TimeUtils;
import io.reactivex.Observable;
import io.reactivex.disposables.Disposable;

/**
 * 添加发货-坩埚
 * author : flexible
 * email : lgd19940421@163.com
 * github: https://github.com/FlexibleXd
 **/
public class SendApplyAddCrucibleActivity extends WorkToolBarActivity {
    @BindView(R.id.tv_bottom)
    TextView tvBottom;
    @BindView(R.id.rv_data)
    RecyclerView rvData;
    @BindView(R.id.tv_time)
    TextView tvTime;
    @BindView(R.id.rl_time)
    RelativeLayout rlTime;
    @BindView(R.id.tv_weight)
    TextView tvWeight;
    @BindView(R.id.et_logistics_price)
    EditText etLogisticsPrice;
    @BindView(R.id.et_logistics_code)
    EditText etLogisticsCode;
    @BindView(R.id.tv_logistics_company)
    TextView tvLogisticsCompany;
    @BindView(R.id.rl_set)
    RelativeLayout rlSet;
    @BindView(R.id.et_remark)
    EditText etRemark;
    @BindView(R.id.tv_input1)
    TextView tvInput1;
    private List<OrderDetail.OrderItemsBean> dataList;
    private SendApplyAddCrucibleAdapter dataAdapter;
    private Map<String, Object> param;
    private OrderDetail dataBean;
    private int clientId;
    private String orderType;

    @Override
    protected void initView() {
        ButterKnife.bind(this);
        rvData.setLayoutManager(new LinearLayoutManager(this, RecyclerView.VERTICAL, false));
        WorkUtils.addNumListener(etRemark, tvInput1);
    }

    @Override
    protected void initData() {
        orderType = getIntent().getStringExtra("orderType");
        dataList = new ArrayList<>();
        dataAdapter = new SendApplyAddCrucibleAdapter(R.layout.item_send_apply_add_crucible, dataList);
        dataAdapter.bindToRecyclerView(rvData);
        param = new HashMap<>();
        param.put("orderId", getIntent().getStringExtra("id"));
        param.put("payer", 2);
        getData();
    }

    @Override
    protected void initEvent() {
        dataAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter baseQuickAdapter, View view, int i) {
                startActivityForResult(SendApplyCrucibleChooseActivity.class,
                        10002, "position", i + ""
                        , "deptId", getIntent().getStringExtra("deptId"),
                        "num", MathUtils.converData(dataList.get(i).getCanOutStoreProductSum(),3) ,
                        "productId", dataList.get(i).getProductId() + "");
            }
        });
    }

    private void getData() {
        Observable<BaseBean> observable;
        if (TextUtils.equals(orderType, OrderType.SALE.getCode())) {
            observable = RtfUtils.getRtf().saleOrderDetail(getIntent().getStringExtra("id"), "1");
        } else if (TextUtils.equals(orderType, OrderType.OUT_BUY.getCode())) {
            observable = RtfUtils.getRtf().purchaseOrderDetail(getIntent().getStringExtra("id"), "1");
        } else if (TextUtils.equals(orderType, OrderType.SUPPLIER.getCode())) {
            observable = RtfUtils.getRtf().supplierOrderDetail(getIntent().getStringExtra("id"), "1");
        } else if (TextUtils.equals(orderType, OrderType.BUILD.getCode())) {
            observable = RtfUtils.getRtf().productOrderDetail(getIntent().getStringExtra("id"), "1");
        } else if (TextUtils.equals(orderType, OrderType.IN.getCode())) {
            observable = RtfUtils.getRtf().insideOrderDetail(getIntent().getStringExtra("id"), "1");
        } else if (TextUtils.equals(orderType, OrderType.CRUCIBLE.getCode())) {
            observable = RtfUtils.getRtf().crucibleSaleOrderDetail(getIntent().getStringExtra("id"), "1");
        } else {
            observable = RtfUtils.getRtf().saleOrderDetail(getIntent().getStringExtra("id"), "1");
        }
        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);
                param.put("orderType", dataBean.getExpandInfo().getOrderType());
                dataList.addAll(dataBean.getOrderItems());
                dataAdapter.notifyDataSetChanged();

            }
        });
    }

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


    @OnClick(R.id.tv_bottom)
    public void onViewClicked() {
        if (coverProInfo()) {
            submit();
        }
    }

    private boolean coverProInfo() {
        Map<Integer, Boolean> isChoose = dataAdapter.getIsChoose();
        List<JSONObject> info = new ArrayList<>();
        String totalWeight = "0";
        for (Map.Entry<Integer, Boolean> entry : isChoose.entrySet()) {
            if (entry.getValue()) {
                OrderDetail.OrderItemsBean recordsBean = dataList.get(entry.getKey());
                JSONObject returnData = new JSONObject();
                if (null == recordsBean.getBackList()) {
                    toast("请选择来源");
                    return false;
                }
                if (TextUtils.isEmpty(recordsBean.getCount()) || Double.valueOf(recordsBean.getCount()) == 0d) {
                    toast("请选择发货数量");
                    return false;
                }
                totalWeight = MathUtils.add(totalWeight, MathUtils.multiply(recordsBean.getCount(),
                        String.valueOf(recordsBean.getProductWeight()), 3), 3);
                returnData.put("productId", recordsBean.getProductId());
                returnData.put("productAmount", recordsBean.getCount());
                for (AddStockChooseBean.RecordsBean bean : recordsBean.getBackList()) {
                    bean.setActionQuantity(Double.valueOf(bean.getChooseNum()));
                    bean.setOrderId(getIntent().getStringExtra("id"));
                    bean.setOrderType(orderType);
                    bean.setFromStockId(bean.getStockId() + "");
                }

                returnData.put("stockFromDetails", recordsBean.getBackList());
                info.add(returnData);
            }
        }
        if (info.size() == 0) {
            toast("请选择货品");
            return false;
        }
        tvWeight.setText(totalWeight);
        param.put("sendOutStoreApplyItemList", info);
        param.put("totalWeight", totalWeight);
        return true;
    }

    private void submit() {
        String price = etLogisticsPrice.getText().toString();
        String code = etLogisticsCode.getText().toString();
        String remark = etRemark.getText().toString();
//        String time = tvTime.getText().toString();
//        if (TextUtils.isEmpty(time)) {
//            toast("请选择发货时间");
//            return;
//        }
        if (TextUtils.isEmpty(price)) {
            toast("请输入运费");
            return;
        }
        if (TextUtils.isEmpty(code)) {
            toast("请输入快递单号");
            return;
        }
        if (clientId == 0) {
            toast("请选择物流公司");
            return;
        }
        param.put("trackingNumber", code);
        param.put("fareMoney", price);
        param.put("applyRemark", remark);
        param.put("logisticsId", clientId);
        Observable<BaseBean> observable;
        if (TextUtils.equals(orderType, OrderType.SALE.getCode())) {
            observable = RtfUtils.getRtf().sendForwardApply(getIntent().getStringExtra("id"), WorkUtils.convertMapToBody(param));
        } else {
            observable = RtfUtils.getRtf().sendForwardApply(getIntent().getStringExtra("id"), WorkUtils.convertMapToBody(param));
        }
        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;
                }
                toast("提交申请成功");
                EventBus.getDefault().post(new CheckSendEvent());
                finish();
            }

        });
    }


    @OnClick({R.id.tv_bottom, R.id.rl_time, R.id.rl_set})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_bottom:
                break;
            case R.id.rl_time:
                PickTimeUtils.showPickThree(SendApplyAddCrucibleActivity.this, new OnTimeSelectListener() {
                    @Override
                    public void onTimeSelect(Date date, View v) {
                        String time = TimeUtils.date2String(date, new SimpleDateFormat("yyyy-MM-dd"));
//                        param.put("requireTime", time);
                        tvTime.setText(time);
                    }
                }).show();
                break;
            case R.id.rl_set:
                startActivityForResult(StoreSaleClientActivity.class, 10001,
                        "flag", "1", "supplier", "选择运输商", "code", "TRANSPORTERS");
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 10001 && resultCode == 10001) {
            String clientName = data.getStringExtra("clientName");
            clientId = data.getIntExtra("id", 0);
            tvLogisticsCompany.setText(clientName);
        } else if (requestCode == 10002 && resultCode == 10002) {
            List<AddStockChooseBean.RecordsBean> backList = JSON.parseArray(data.getStringExtra("stock"),
                    AddStockChooseBean.RecordsBean.class);
            Integer position = Integer.valueOf(data.getStringExtra("position"));
            String count = data.getStringExtra("count");
            dataList.get(position).setBackList(backList);
            dataList.get(position).setCount(count);
            dataAdapter.notifyItemChanged(position);
        }
    }

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

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

    @Subscribe
    public void refresh(SendWeightEvent event) {
        Map<Integer, Boolean> isChoose = dataAdapter.getIsChoose();
        List<JSONObject> info = new ArrayList<>();
        String totalWeight = "0";
        for (Map.Entry<Integer, Boolean> entry : isChoose.entrySet()) {
            if (entry.getValue()) {
                OrderDetail.OrderItemsBean recordsBean = dataList.get(entry.getKey());
                JSONObject returnData = new JSONObject();
                if (TextUtils.isEmpty(recordsBean.getChooseNum()) || Double.valueOf(recordsBean.getChooseNum()) == 0d) {
                }
                totalWeight = MathUtils.add(totalWeight, MathUtils.multiply(recordsBean.getCount(),
                        String.valueOf(recordsBean.getProductWeight()), 3), 3);
                returnData.put("productId", recordsBean.getProductId());
                returnData.put("productAmount", recordsBean.getCount());
                for (AddStockChooseBean.RecordsBean bean : recordsBean.getBackList()) {
                    bean.setActionQuantity(Double.valueOf(bean.getChooseNum()));
                }
                returnData.put("stockFromDetails", recordsBean.getBackList());
                info.add(returnData);
            }
        }
        tvWeight.setText(totalWeight);
    }

}
