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

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
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.alibaba.fastjson.JSONObject;
import com.bigkoo.pickerview.listener.OnTimeSelectListener;
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.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.WorkSendApplyAddAdapter;
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 PickApplyAddActivity 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;
    @BindView(R.id.tv_desc)
    TextView tvDesc;
    @BindView(R.id.ll_logistics_price)
    LinearLayout llLogisticsPrice;
    @BindView(R.id.ll_logistics_code)
    LinearLayout llLogisticsCode;
    private List<OrderDetail.OrderItemsBean> dataList;
    private WorkSendApplyAddAdapter 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);
        rlSet.setVisibility(View.GONE);
        llLogisticsCode.setVisibility(View.GONE);
        llLogisticsPrice.setVisibility(View.GONE);
        rlTime.setVisibility(View.GONE);
        tvDesc.setText("领料信息");
        tvBottom.setText("领料");
    }

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

    @Override
    protected void initEvent() {
    }

    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 (TextUtils.isEmpty(recordsBean.getChooseNum()) || Double.valueOf(recordsBean.getChooseNum()) == 0d) {
                    toast("请选择领料数量");
                    return false;
                }
                totalWeight = MathUtils.add(totalWeight, MathUtils.multiply(recordsBean.getChooseNum(),
                        String.valueOf(recordsBean.getProductWeight()), 3), 3);
                returnData.put("productId", recordsBean.getProductId());
                returnData.put("productAmount", recordsBean.getChooseNum());
                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.SUPPLIER.getCode())) {
            observable = RtfUtils.getRtf().pickApply(getIntent().getStringExtra("id"), WorkUtils.convertMapToBody(param));
        } else {
            observable = RtfUtils.getRtf().pickApply(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(PickApplyAddActivity.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);
        }
    }

    @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.getChooseNum(),
                        String.valueOf(recordsBean.getProductWeight()), 3), 3);
                returnData.put("productId", recordsBean.getProductId());
                returnData.put("productAmount", recordsBean.getChooseNum());
                info.add(returnData);
            }
        }
        tvWeight.setText(totalWeight);
    }
}
