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

import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.widget.EditText;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.wd.workoffice.R;
import com.wd.workoffice.app.BaseBean;
import com.wd.workoffice.app.WorkToolBarActivity;
import com.wd.workoffice.bean.TicketAddBean;
import com.wd.workoffice.bean.event.CheckTicketEvent;
import com.wd.workoffice.retrofit.RtfUtils;
import com.wd.workoffice.retrofit.WorkObserver;
import com.wd.workoffice.ui.adapter.WorkAddTicketOrderAdapter;
import com.wd.workoffice.util.MathUtils;
import com.wd.workoffice.util.WorkUtils;

import org.greenrobot.eventbus.EventBus;

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.Observable;
import io.reactivex.disposables.Disposable;

/**
 * 工作台 - 收票 票申请 提交
 * author : flexible
 * email : lgd19940421@163.com
 * github: https://github.com/FlexibleXd
 **/
public class WorkFinancialReceiveTicketSubmitActivity extends WorkToolBarActivity {
    @BindView(R.id.tv_bottom)
    TextView tvBottom;
    @BindView(R.id.tv_desc)
    TextView tvDesc;
    @BindView(R.id.tv_client)
    TextView tvClient;
    @BindView(R.id.tv_price)
    TextView tvPrice;
    @BindView(R.id.rv_data)
    RecyclerView rvData;
    @BindView(R.id.et_tax)
    EditText etTax;
    @BindView(R.id.et_remark)
    EditText etRemark;
    @BindView(R.id.tv_remark_num)
    TextView tvRemarkNum;
    private List<TicketAddBean.RecordsBean> dataList;
    private WorkAddTicketOrderAdapter dataAdapter;
    private Map<String, Object> param;
    private String orderType;

    @Override
    protected void initView() {
        ButterKnife.bind(this);
        tvDesc.setText("所属供应商");
        rvData.setLayoutManager(new LinearLayoutManager(this, RecyclerView.VERTICAL, false));
    }

    @Override
    protected void initData() {
        tvClient.setText(getIntent().getStringExtra("customerName"));
        dataList = JSON.parseArray(getIntent().getStringExtra("info"), TicketAddBean.RecordsBean.class);
        dataAdapter = new WorkAddTicketOrderAdapter(R.layout.item_ticket_add_detail, dataList,1);
        dataAdapter.bindToRecyclerView(rvData);
        param = new HashMap<>();
        param.put("supplierId", getIntent().getStringExtra("customerId"));
        param.put("deptId", getIntent().getStringExtra("depId"));
        orderType = getIntent().getStringExtra("orderType");
        changeNumAndPrice();
        coverProInfo(dataList);
    }

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

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

    /**
     * 转换pro，生成上传参数
     *
     * @param proList
     * @return
     */
    private void coverProInfo(List<TicketAddBean.RecordsBean> proList) {
        List<JSONObject> orderItems = new ArrayList<>();
        for (TicketAddBean.RecordsBean recordsBean : proList) {
            JSONObject data = new JSONObject();
            data.put("productId", recordsBean.getProductId());
            data.put("orderId", recordsBean.getOrderId());
            data.put("quantity", recordsBean.getCarNum());
            data.put("invoiceUnitPrice", recordsBean.getCarPrice());
//            data.put("outProductName", recordsBean.getoutpr());
            orderItems.add(data);
        }
        param.put("invoiceApplyItems", orderItems);
    }

    private void changeNumAndPrice() {
        String allPrice = "";
        for (TicketAddBean.RecordsBean recordsBean : dataList) {
            allPrice = MathUtils.add(allPrice, MathUtils.multiply(recordsBean.getCarNum(),
                    recordsBean.getCarPrice(), 3), 3);
        }
        tvPrice.setText(" ¥ ".concat(allPrice));
    }

    private void submit() {
        param.put("tax", etTax.getText().toString());
        param.put("applyRemark", etRemark.getText().toString());
        Observable<BaseBean> baseBeanObservable;
        if (TextUtils.equals(orderType, "外采购订单")) {
            baseBeanObservable = RtfUtils.getRtf().poReceiptApply(WorkUtils.convertMapToBody(param));
        } else if (TextUtils.equals(orderType, "销售订单")) {
            baseBeanObservable = RtfUtils.getRtf().foReceipApply(WorkUtils.convertMapToBody(param));
        } else {
            baseBeanObservable = RtfUtils.getRtf().poReceiptApply(WorkUtils.convertMapToBody(param));
        }
        baseBeanObservable.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 CheckTicketEvent());
                finish();
            }
        });
    }


    @OnClick(R.id.tv_bottom)
    public void onViewClicked() {
        if (TextUtils.isEmpty(etTax.getText().toString())) {
            toast("请输入税费");
            return;
        }
        submit();
    }
}
