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

import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
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.wd.workoffice.R;
import com.wd.workoffice.app.BaseBean;
import com.wd.workoffice.app.WorkToolBarActivity;
import com.wd.workoffice.bean.MoneyOutBean;
import com.wd.workoffice.bean.event.CheckMoneytEvent;
import com.wd.workoffice.bean.listener.ThreeMenuClickListener;
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.WorkFinancialOutAdapter;
import com.wd.workoffice.util.WorkUtils;
import com.wd.workoffice.util.ddmfilter.FinancialOutFilterData;
import com.wd.workoffice.widget.DropDownMenu;

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

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

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

    @BindView(R.id.ddm_choose)
    DropDownMenu ddmChoose;
    private RecyclerView rvData;
    private int page = 1;
    private Map<String, Object> param;
    private SmartRefreshLayout srlRefresh;
    private List<MoneyOutBean.RecordsBean> dataList;
    private WorkFinancialOutAdapter dataAdapter;

    @Override
    protected void initView() {
        ButterKnife.bind(this);
        FinancialOutFilterData filterData = new FinancialOutFilterData(this,ddmChoose, new ThreeMenuClickListener() {
            @Override
            public void clickOne(String value) {
                param.put("orderType", WorkUtils.getOrderCode(value));
                page = 1;
                param.put("current", page);
                getData();
            }

            @Override
            public void clickTwo(String value) {
                //0未审核      1已通过      2不通过
                if (TextUtils.equals(value, "全部状态")) {
                    param.put("status", "");
                } else if (TextUtils.equals(value, "待审核")) {
                    param.put("status", "0");
                } else if (TextUtils.equals(value, "已通过")) {
                    param.put("status", "1");
                } else {
                    param.put("status", "2");
                }
                page = 1;
                param.put("current", page);
                getData();
            }

            @Override
            public void clickThree(String value) {
            }
        });
        rvData = filterData.getRvData();
        srlRefresh = filterData.getSrlRefresh();
    }


    @Override
    protected void initData() {
        dataList = new ArrayList<>();
        dataAdapter = new WorkFinancialOutAdapter(R.layout.item_financial_out, dataList,1);
        dataAdapter.bindToRecyclerView(rvData);
        dataAdapter.setEmptyView(R.layout.view_empty_content, rvData);
        param = WorkUtils.pageKey();
        param.put("current", page);
        param.put("orderType", "SO");
        if (!WorkUtils.hasPermission(PagePermissionType.MONEY_BACK_LIST.getPermission())) {
            toast(R.string.permission);
        } else {
            getData();
        }
    }

    private void getData() {
        RtfUtils.getRtf().moneyBack(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;
                }
                List<MoneyOutBean.RecordsBean> getList = JSON.parseObject(data.getData().toString(), MoneyOutBean.class).getRecords();
                if (page == 1) {
                    srlRefresh.finishRefresh();
                    dataList.clear();
                    dataList.addAll(getList);
                    dataAdapter.notifyDataSetChanged();
                    dataAdapter.loadMoreComplete();
                } else {
                    dataAdapter.loadMoreComplete();
                    dataList.addAll(getList);
                    dataAdapter.notifyDataSetChanged();
                }
                if (getList.size() == 0) {
                    dataAdapter.loadMoreEnd();
                } else {
                    page++;
                }
            }
        });
    }

    @Override
    protected void initEvent() {
        srlRefresh.setOnRefreshListener(refreshLayout -> {
            if (!WorkUtils.hasPermission(PagePermissionType.MONEY_BACK_LIST.getPermission())) {
                toast(R.string.permission);
            } else {
                page = 1;
                param.put("current", page);
                getData();
            }
        });
        dataAdapter.setOnLoadMoreListener(() -> {
            param.put("current", page);
            getData();
        }, rvData);
        dataAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                startActivity(WorkFinancialDetailActivity.class,
                        "type","1","detail",JSON.toJSONString(dataList.get(position)));
            }
        });
        dataAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter baseQuickAdapter, View view, int i) {
                switch (view.getId()){
                    case R.id.btn_agree:
                        checkDialog(i,1);
                        break;
                    case R.id.btn_refuse:
                        checkDialog(i,2);
                        break;
                }
            }
        });
    }

    private void checkDialog(int position, 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(),position);
                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 position) {
        Map<String, Object> param = WorkUtils.simpleParam();
        param.put("status",status);
        param.put("auditRemark",remark);
        param.put("id", dataList.get(position).getId());
        param.put("applyAmount",  dataList.get(position).getApplyAmount());
        RtfUtils.getRtf().checkMoneyBack(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("操作成功");
                dataList.get(position).setStatus(status+"");
                dataAdapter.notifyItemChanged(position);
            }
        });
    }
    @Override
    protected int layoutId() {
        return R.layout.fg_work_pro;
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        if (!WorkUtils.hasPermission(PagePermissionType.MONEY_BACK_APPLY.getPermission())){
            return super.onCreateOptionsMenu(menu);
        }else {
            getMenuInflater().inflate(R.menu.menu_add, menu);
        }
        return super.onCreateOptionsMenu(menu);
    }

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

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

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

    @Subscribe
    public void refresh(CheckMoneytEvent event) {
        page = 1;
        param.put("current", page);
        getData();
    }
}
