package com.wd.workoffice.ui.fg;

import android.os.Bundle;
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.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.WorkBaseFg;
import com.wd.workoffice.bean.SendApplyBean;
import com.wd.workoffice.bean.event.CheckSendEvent;
import com.wd.workoffice.bean.workEnum.OrderType;
import com.wd.workoffice.retrofit.RtfUtils;
import com.wd.workoffice.retrofit.WorkObserver;
import com.wd.workoffice.ui.activity.mes.order.MesOrderDetailActivity;
import com.wd.workoffice.ui.adapter.MesOrderAdapter;
import com.wd.workoffice.ui.adapter.MesProcessAdapter;
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.Nullable;
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 MesProcessFragment extends WorkBaseFg {

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

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


    @Override
    protected void initData() {
        param = WorkUtils.pageKey();
        param.put("status", state);
        param.put("orderId", orderId);
        page = 1;
        param.put("current", page);
        dataList = new ArrayList<>();
        dataAdapter = new MesProcessAdapter(R.layout.item_mes_process, dataList);
        dataAdapter.bindToRecyclerView(rvData);
        dataAdapter.setEmptyView(R.layout.view_empty_content, rvData);
        dataList.add(null);
        dataList.add(null);
        dataList.add(null);
        dataAdapter.notifyDataSetChanged();
//        getData();
    }


    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Bundle arguments = getArguments();
        if (arguments != null) {
            state = arguments.getString("state");
            orderId = arguments.getString("orderId");
            orderType = arguments.getString("orderType");
        }
    }

    private void getData() {
        Observable<BaseBean> observable;
        if (TextUtils.equals(orderType, OrderType.SALE.getCode())) {
            observable = RtfUtils.getRtf().sendApplyList(param);
        } else if (TextUtils.equals(orderType, OrderType.OUT_BUY.getCode())) {
            observable = RtfUtils.getRtf().sendPoApplyList(param);
        } else if (TextUtils.equals(orderType, OrderType.CRUCIBLE.getCode())) {
            observable = RtfUtils.getRtf().sendCoApplyList(param);
        } else {
            observable = RtfUtils.getRtf().sendApplyList(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<SendApplyBean.RecordsBean> getList = JSON.parseObject(data.getData().toString(), SendApplyBean.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 -> {
            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(MesOrderDetailActivity.class);
            }
        });
    }


    private void checkDialog(int status, int id) {
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        View view = LayoutInflater.from(getActivity()).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(), 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) {
        Map<String, Object> param = WorkUtils.simpleParam();
        param.put("status", status);
        param.put("auditRemark", remark);
        param.put("id", id);
        Observable<BaseBean> observable;
        if (TextUtils.equals(orderType, OrderType.SALE.getCode())) {
            observable = RtfUtils.getRtf().sendApplyCheck(WorkUtils.convertMapToBody(param));
        } else if (TextUtils.equals(orderType, OrderType.OUT_BUY.getCode())) {
            observable = RtfUtils.getRtf().sendPoApplyCheck(WorkUtils.convertMapToBody(param));
        } else if (TextUtils.equals(orderType, OrderType.CRUCIBLE.getCode())) {
            observable = RtfUtils.getRtf().sendCoApplyCheck(WorkUtils.convertMapToBody(param));
        } else {
            observable = RtfUtils.getRtf().sendApplyCheck(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());
            }
        });
    }

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

    @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) {
        page = 1;
        param.put("current", page);
        getData();
    }
}
