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

import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.wd.workoffice.R;
import com.wd.workoffice.app.BaseBean;
import com.wd.workoffice.app.WorkToolBarActivity;
import com.wd.workoffice.bean.EndApplyBean;
import com.wd.workoffice.bean.event.CheckOrderEvent;
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.EndApplyAdapter;
import com.wd.workoffice.util.WorkUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

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

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import butterknife.BindView;
import butterknife.ButterKnife;
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 EndApplyActivity extends WorkToolBarActivity {

    @BindView(R.id.rv_data)
    RecyclerView rvData;
    @BindView(R.id.srl_refresh)
    SmartRefreshLayout srlRefresh;
    private Map<String, Object> param;
    private List<EndApplyBean.RecordsBean> dataList;
    private EndApplyAdapter dataAdapter;
    private int page = 1;

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


    @Override
    protected void initData() {
        dataList = new ArrayList<>();
        dataAdapter = new EndApplyAdapter(R.layout.item_send_apply, dataList);
        dataAdapter.bindToRecyclerView(rvData);
        dataAdapter.setEmptyView(R.layout.view_empty_content, rvData);
        changePermission();
        param = WorkUtils.pageKey();
        page = 1;
        param.put("current", page);
        getData();
    }

    private void getData() {
        String orderType = getIntent().getStringExtra("orderType");
        Observable<BaseBean> observable;
        if (TextUtils.equals(orderType, OrderType.SALE.getCode())) {
            observable = RtfUtils.getRtf().endApplyList(getIntent().getStringExtra("orderId"), param);
        } else if (TextUtils.equals(orderType, OrderType.OUT_BUY.getCode())) {
            observable = RtfUtils.getRtf().endPoApplyList(getIntent().getStringExtra("orderId"), param);
        } else {
            observable = RtfUtils.getRtf().endApplyList(getIntent().getStringExtra("orderId"), 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;
                }
                List<EndApplyBean.RecordsBean> getList = JSON.parseObject(data.getData().toString(), EndApplyBean.class).getRecords();
                srlRefresh.finishRefresh();
                dataList.clear();
                dataList.addAll(getList);
                dataAdapter.notifyDataSetChanged();
            }
        });
    }

    private void changePermission() {
        String orderType = getIntent().getStringExtra("orderType");
        boolean hasPermission = true;
        if (TextUtils.equals(orderType, OrderType.SALE.getCode())) {
            hasPermission = WorkUtils.hasPermission(PagePermissionType.SO_ADVANCE_AUDIT.getPermission());
        } else if (TextUtils.equals(orderType, OrderType.OUT_BUY.getCode())) {
            hasPermission = WorkUtils.hasPermission(PagePermissionType.PO_ADVANCE_AUDIT.getPermission());
        }
        dataAdapter.setHasPermission(hasPermission);
        dataAdapter.notifyDataSetChanged();
    }

    @Override
    protected void initEvent() {
        srlRefresh.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                page = 1;
                param.put("current", page);
                getData();
            }
        });
        dataAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                startActivity(EndApplyDetailActivity.class,
                        "orderType", getIntent().getStringExtra("orderType"),
                        "hasPermission",dataAdapter.isHasPermission()?"1":"0",
                        "info", JSON.toJSONString(dataList.get(position)));
            }
        });
        dataAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                switch (view.getId()) {
                    case R.id.tv_refuse:
                        checkDialog(2, dataList.get(position).getId());
                        break;
                    case R.id.tv_agree:
                        checkDialog(1, dataList.get(position).getId());
                        break;

                }
            }
        });
    }

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

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        if (TextUtils.equals("300", getIntent().getStringExtra("status"))) {
            String orderType = getIntent().getStringExtra("orderType");
            if (TextUtils.equals(orderType, OrderType.SALE.getCode())) {
                if (WorkUtils.hasPermission(PagePermissionType.SO_ADVANCE_SAVE.getPermission())) {
                    getMenuInflater().inflate(R.menu.menu_add, menu);
                }
            } else if (TextUtils.equals(orderType, OrderType.OUT_BUY.getCode())) {
                if (WorkUtils.hasPermission(PagePermissionType.PO_ADVANCE_SAVE.getPermission())) {
                    getMenuInflater().inflate(R.menu.menu_add, menu);
                }
            }
        }
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.add:
                addDialog();
                break;
        }
        return super.onOptionsItemSelected(item);
    }


    private void addDialog() {
        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("提前申请结束");
        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;
                }
                add(etRemark.getText().toString());
                addCartDialog.dismiss();
            }
        });
        tvCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                addCartDialog.dismiss();
            }
        });
        addCartDialog.show();
    }


    private void add(String remark) {
        Map<String, Object> param = WorkUtils.simpleParam();
        param.put("orderType", getIntent().getStringExtra("orderType"));
        param.put("applyRemark", remark);
        param.put("orderId", getIntent().getStringExtra("orderId"));
        String orderType = getIntent().getStringExtra("orderType");
        Observable<BaseBean> observable;
        if (TextUtils.equals(orderType, OrderType.SALE.getCode())) {
            observable = RtfUtils.getRtf().endApply(getIntent().getStringExtra("orderId"), WorkUtils.convertMapToBody(param));
        } else if (TextUtils.equals(orderType, OrderType.OUT_BUY.getCode())) {
            observable = RtfUtils.getRtf().endPoApply(getIntent().getStringExtra("orderId"), WorkUtils.convertMapToBody(param));
        } else {
            observable = RtfUtils.getRtf().endApply(getIntent().getStringExtra("orderId"), 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 CheckOrderEvent());
                getData();
            }
        });
    }

    @Override
    public void onStart() {
        super.onStart();
        EventBus.getDefault().register(this);
    }

    @Override
    public void onStop() {
        super.onStop();
        EventBus.getDefault().unregister(this);
    }

    @Subscribe
    public void refresh(CheckSendEvent event) {
        getData();
    }

    private void checkDialog(int status, int id) {
        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(), id);
                addCartDialog.dismiss();
            }
        });
        tvCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                addCartDialog.dismiss();
            }
        });
        addCartDialog.show();
    }


    private void check(int status, String remark, int id) {
        param.put("status", status);
        param.put("auditRemark", remark);
        param.put("id", id);
        String orderType = getIntent().getStringExtra("orderType");
        Observable<BaseBean> observable;
        if (TextUtils.equals(orderType, OrderType.SALE.getCode())) {
            observable = RtfUtils.getRtf().endSoCheck(id + "", WorkUtils.convertMapToBody(param));
        } else if (TextUtils.equals(orderType, OrderType.OUT_BUY.getCode())) {
            observable = RtfUtils.getRtf().endPoCheck(id + "", WorkUtils.convertMapToBody(param));
        } else {
            observable = RtfUtils.getRtf().endSoCheck(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());
                EventBus.getDefault().post(new CheckOrderEvent());
                finish();
            }
        });
    }
}
