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

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.LinearLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.wd.workoffice.R;
import com.wd.workoffice.app.BaseBean;
import com.wd.workoffice.app.WorkToolBarActivity;
import com.wd.workoffice.bean.OrderBean;
import com.wd.workoffice.bean.ProAddBean;
import com.wd.workoffice.bean.ProductBean;
import com.wd.workoffice.bean.event.CheckProApplyEvent;
import com.wd.workoffice.bean.workEnum.PagePermissionType;
import com.wd.workoffice.retrofit.RtfUtils;
import com.wd.workoffice.retrofit.WorkObserver;
import com.wd.workoffice.ui.adapter.ProApplyDetailAdapter;
import com.wd.workoffice.ui.adapter.ProApplyTargetAddAdapter;
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.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 ProductOrderApplyDetailActivity extends WorkToolBarActivity {
    @BindView(R.id.tv_refuse)
    TextView tvRefuse;
    @BindView(R.id.tv_agree)
    TextView tvAgree;
    @BindView(R.id.ll_bottom)
    LinearLayout 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.tv_remark)
    TextView tvRemark;
    private Map<String, Object> param;
    private ProApplyTargetAddAdapter toAdapter;
    private List<ProductBean.RecordsBean> toList;
    private List<ProAddBean.RecordsBean> fromList;
    private ProApplyDetailAdapter fromAdapter;
    private OrderBean info;

    @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() {
        info = JSON.parseObject(getIntent().getStringExtra("info"), OrderBean.class);
        tvBase1.setText(info.getCustomerName());
        tvBase2.setText(info.getEnterStockName());
        tvBase3.setText(info.getEnterStockName());
        tvBase4.setText(info.getUsedStockName());
        tvRemark.setText(info.getApplyRemark());
        fromList = new ArrayList<>();
        fromAdapter = new ProApplyDetailAdapter(R.layout.item_product_apply_pro, fromList);
        fromAdapter.bindToRecyclerView(rvFrom);
        toList = new ArrayList<>();
        toAdapter = new ProApplyTargetAddAdapter(R.layout.item_product_target_pro, toList);
        toAdapter.bindToRecyclerView(rvTo);
        changeNumAndPrice();
        if (TextUtils.equals(info.getStatus() + "", "0")) {
            llBottom.setVisibility(View.VISIBLE);
            changePermission();
        } else {
            llBottom.setVisibility(View.GONE);
        }
        param = new HashMap<>();
        param.put("id", info.getId());
        getData(Integer.valueOf(info.getId()));
    }

    private void getData(Integer id) {
        RtfUtils.getRtf().packageSourcePro(id).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;
                }
                List<ProAddBean.RecordsBean> dataList = JSON.parseArray(data.getData().toString(), ProAddBean.RecordsBean.class);
                fromList.clear();
                fromList.addAll(dataList);
                fromAdapter.notifyDataSetChanged();

            }
        });
        RtfUtils.getRtf().packageEndPro(id).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;
                }
                List<ProductBean.RecordsBean> dataList = JSON.parseArray(data.getData().toString(), ProductBean.RecordsBean.class);
                toList.addAll(dataList);
                toAdapter.notifyDataSetChanged();
            }
        });
    }

    private void changePermission() {
        boolean hasPermission = WorkUtils.hasPermission(PagePermissionType.AO_PACKAGE_APPLY_AUDIT.getPermission());
        if (!hasPermission){
            tvRefuse.setVisibility(View.GONE);
            tvAgree.setVisibility(View.GONE);
        }
    }

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


    @Override
    protected void initEvent() {
    }

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


    @OnClick({R.id.tv_refuse, R.id.tv_agree})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_refuse:
                checkDialog(2);
                break;
            case R.id.tv_agree:
                checkDialog(1);
                break;
        }
    }


    private void checkDialog(int status) {
        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);
        WorkUtils.addNumListener(etRemark,tvNum);
        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) {
        param.put("status", status);
        param.put("auditRemark", remark);
        RtfUtils.getRtf().packageApply(info.getId(), 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;
                }
                EventBus.getDefault().post(new CheckProApplyEvent());
                toast("操作成功");
                finish();

            }
        });
    }

}
