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

import android.text.TextUtils;
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.SendApplyBean;
import com.wd.workoffice.bean.SendApplyDetailBean;
import com.wd.workoffice.bean.event.CheckSendEvent;
import com.wd.workoffice.bean.workEnum.OrderType;
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.SendApplyDetailAdapter;
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.Observable;
import io.reactivex.disposables.Disposable;

/**
 * 申请领料发货详情
 * author : flexible
 * email : lgd19940421@163.com
 * github: https://github.com/FlexibleXd
 **/
public class PickApplyDetailActivity 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.rv_data)
    RecyclerView rvData;
    @BindView(R.id.tv_time)
    TextView tvTime;
    @BindView(R.id.tv_weight)
    TextView tvWeight;
    @BindView(R.id.tv_logistics_price)
    TextView tvLogisticsPrice;
    @BindView(R.id.tv_logistics_code)
    TextView tvLogisticsCode;
    @BindView(R.id.tv_logistics_company)
    TextView tvLogisticsCompany;
    @BindView(R.id.tv_remark)
    TextView tvRemark;
    @BindView(R.id.tv_check_person)
    TextView tvCheckPerson;
    @BindView(R.id.tv_check_time)
    TextView tvCheckTime;
    @BindView(R.id.tv_check_remark)
    TextView tvCheckRemark;
    @BindView(R.id.ll_check)
    LinearLayout llCheck;
    private List<SendApplyDetailBean> dataList;
    private SendApplyDetailAdapter dataAdapter;
    private Map<String, Object> param;
    private SendApplyBean.RecordsBean info;
    private String orderType;

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

    }

    private void changePermission() {
        boolean hasPermission = true;
        if (TextUtils.equals(orderType, OrderType.SUPPLIER.getCode())) {
            hasPermission = WorkUtils.hasPermission(PagePermissionType.FO_PICK_APPLY_AUDIT.getPermission());
        }
//        else if (TextUtils.equals(orderType, OrderType.OUT_BUY.getCode())) {
//            hasPermission =WorkUtils.hasPermission(PagePermissionType.PO_OUT_AUDIT.getPermission());
//        } else if (TextUtils.equals(orderType, OrderType.CRUCIBLE.getCode())) {
//            hasPermission =WorkUtils.hasPermission(PagePermissionType.CO_OUT_AUDIT.getPermission());
//        }
        if (!hasPermission) {
            llBottom.setVisibility(View.GONE);
        }
    }

    @Override
    protected void initData() {
        orderType = getIntent().getStringExtra("orderType");
        info = JSON.parseObject(getIntent().getStringExtra("info"), SendApplyBean.RecordsBean.class);
        getData(info.getId() + "");
        tvTime.setText(info.getCreatedTime());
        tvWeight.setText(MathUtils.converData(info.getTotalWeight(),3));
        tvLogisticsPrice.setText(MathUtils.converData(info.getFareMoney(),3));
        tvLogisticsCode.setText(info.getTrackingNumber());
        tvLogisticsCompany.setText(info.getTransitPartName());
        tvRemark.setText(info.getApplyRemark());
        if (TextUtils.equals(info.getStatus(), "0")) {
            llBottom.setVisibility(View.VISIBLE);
            llCheck.setVisibility(View.GONE);
            changePermission();
        } else {
            llBottom.setVisibility(View.GONE);
            llCheck.setVisibility(View.VISIBLE);
            tvCheckPerson.setText(info.getUpdatedUser());
            tvCheckTime.setText(info.getUpdatedTime());
            tvCheckRemark.setText(info.getAuditRemark());
        }
        dataList = new ArrayList<>();
        dataAdapter = new SendApplyDetailAdapter(R.layout.item_send_apply_detail, dataList);
        dataAdapter.bindToRecyclerView(rvData);
        param = new HashMap<>();
        param.put("id", info.getId());
    }

    private void getData(String id) {
        RtfUtils.getRtf().pickApplyDetail(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<SendApplyDetailBean> dataBean = JSON.parseArray(data.getData().toString(), SendApplyDetailBean.class);
                dataList.addAll(dataBean);
                dataAdapter.notifyDataSetChanged();
            }
        });
    }

    @Override
    protected void initEvent() {
    }

    @Override
    protected int layoutId() {
        return R.layout.activity_send_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 (status!=1&&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);
        param.put("id", info.getId());
        Observable<BaseBean> observable;
        if (TextUtils.equals(orderType, OrderType.SUPPLIER.getCode())) {
            observable = RtfUtils.getRtf().pickApplyCheck(WorkUtils.convertMapToBody(param));
        }else {
            observable = RtfUtils.getRtf().pickApplyCheck(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();
            }
        });
    }
}
