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

import android.text.Editable;
import android.text.TextWatcher;
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.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.ProAddBean;
import com.wd.workoffice.bean.ProductBean;
import com.wd.workoffice.retrofit.RtfUtils;
import com.wd.workoffice.retrofit.WorkObserver;
import com.wd.workoffice.ui.activity.bat.store.StoreOrderSuccessActivity;
import com.wd.workoffice.ui.adapter.ProAddAdapter;
import com.wd.workoffice.ui.adapter.ProTargetAddAdapter;
import com.wd.workoffice.util.MathUtils;
import com.wd.workoffice.util.UserKeeper;
import com.wd.workoffice.util.WorkUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

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 ProductConfirmActivity extends WorkToolBarActivity {

    @BindView(R.id.tv_price)
    TextView tvPrice;
    @BindView(R.id.tv_ok)
    TextView tvOk;
    @BindView(R.id.ll_bottom)
    RelativeLayout llBottom;
    @BindView(R.id.tv_base1)
    TextView tvBase1;
    @BindView(R.id.tv_base2)
    TextView tvBase2;
    @BindView(R.id.tv_base3)
    TextView tvBase3;
    @BindView(R.id.tv_base4)
    TextView tvBase4;
    @BindView(R.id.tv_base5)
    TextView tvBase5;
    @BindView(R.id.rv_from)
    RecyclerView rvFrom;
    @BindView(R.id.rv_to)
    RecyclerView rvTo;
    @BindView(R.id.et_remark)
    EditText etRemark;
    @BindView(R.id.tv_remark_num)
    TextView tvRemarkNum;
    private ProTargetAddAdapter toAdapter;
    private Map<String, Object> param;
    private List<JSONObject> packageTargetList;
    private List<ProductBean.RecordsBean> toList;
    private List<ProAddBean.RecordsBean> fromList;
    private List<JSONObject> packageSourceList;

    @Override
    protected void initView() {
        ButterKnife.bind(this);
        rvFrom.setLayoutManager(new LinearLayoutManager(this, RecyclerView.VERTICAL, false));
        rvTo.setLayoutManager(new LinearLayoutManager(this, RecyclerView.VERTICAL, false));

    }


    @Override
    protected void initData() {
        fromList = new ArrayList<>();
        ProAddAdapter fromAdapter = new ProAddAdapter(R.layout.item_product_add_pro, fromList, 1);
        fromAdapter.bindToRecyclerView(rvFrom);
        fromList.addAll(JSON.parseArray(getIntent().getStringExtra("from"), ProAddBean.RecordsBean.class));
        fromAdapter.notifyDataSetChanged();
        toList = new ArrayList<>();
        toAdapter = new ProTargetAddAdapter(R.layout.item_product_target_pro, toList, 1);
        toAdapter.bindToRecyclerView(rvTo);
        toList.addAll(JSON.parseArray(getIntent().getStringExtra("to"), ProductBean.RecordsBean.class));
        toAdapter.notifyDataSetChanged();
        changeNumAndPrice();
        param = new HashMap<>();
        param.put("usedStockId", getIntent().getStringExtra("usedStockId"));
        param.put("targetStockId", getIntent().getStringExtra("targetStockId"));
        param.put("enterStockId", getIntent().getStringExtra("usedStockId"));
        param.put("customerId", getIntent().getStringExtra("customerId"));
        JSONObject data = JSON.parseObject(getIntent().getStringExtra("base"));
        tvBase1.setText(data.getString("1"));
        tvBase2.setText(data.getString("2"));
        tvBase3.setText(data.getString("3"));
        tvBase4.setText(data.getString("4"));

    }

    /**
     * 转换pro，生成上传参数
     *
     * @param proList
     * @return
     */
    private List<JSONObject> coverToInfo(List<ProductBean.RecordsBean> proList) {
        List<JSONObject> orderItems = new ArrayList<>();
        for (ProductBean.RecordsBean recordsBean : proList) {
            JSONObject data = new JSONObject();
            data.put("quantity", recordsBean.getCarNum());
            data.put("productId", recordsBean.getId());
            data.put("outerPrice", recordsBean.getCarPrice());
            orderItems.add(data);
        }
        return orderItems;
    }


    @Override
    protected void initEvent() {
        addNumListener(etRemark, tvRemarkNum);
    }

    /**
     * 添加字数监听器
     *
     * @param et
     * @param tv
     */
    private void addNumListener(EditText et, TextView tv) {
        et.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) {
                tv.setText(s.length() + "/140");
            }
        });
    }

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


    @OnClick({R.id.tv_ok})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_ok:
                packageTargetList = coverToInfo(toList);
                packageSourceList = coverFromInfo(fromList);
                submitOrder();
                break;
        }
    }

    private List<JSONObject> coverFromInfo(List<ProAddBean.RecordsBean> fromList) {
        List<JSONObject> orderItems = new ArrayList<>();
        for (ProAddBean.RecordsBean recordsBean : fromList) {
            JSONObject data = new JSONObject();
            data.put("orderType", recordsBean.getOrderType());
            data.put("orderId", recordsBean.getOrderId());
            data.put("quantity", recordsBean.getCarNum());
            data.put("productId", recordsBean.getProductId());
            data.put("orderItemId", recordsBean.getSerialNumber());
            data.put("stockId", getIntent().getStringExtra("usedStockId"));
            orderItems.add(data);
        }
        return orderItems;
    }

    /**
     * 下单
     */
    private void submitOrder() {
        param.put("packageTargetList", packageTargetList);
        param.put("packageSourceList", packageSourceList);
        param.put("applyRemark", etRemark.getText().toString());
        showLoading();
        RtfUtils.getRtf().submitProcedureOrder(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("下单成功");
                startActivity(StoreOrderSuccessActivity.class);
            }

        });
    }

    private void changeNumAndPrice() {
        String allPrice = "";
        for (ProductBean.RecordsBean recordsBean : toList) {
            allPrice = MathUtils.add(allPrice, MathUtils.multiply(recordsBean.getCarNum() + "", recordsBean.getInternalPrice() + "", 3), 3);
        }
        tvPrice.setText("总计: ¥ ".concat(allPrice));
        tvBase5.setText(String.valueOf(allPrice));
    }

}
