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.AddStockBean;
import com.wd.workoffice.bean.event.CheckAddStockEvent;
import com.wd.workoffice.bean.event.CheckOrderEvent;
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.activity.bat.order.AddStockApplyDetailActivity;
import com.wd.workoffice.ui.adapter.AddStockSendApplyAdapter;
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 AddStockApplyFragment 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 AddStockSendApplyAdapter dataAdapter;
    private List<AddStockBean.RecordsBean> dataList;
    private String orderId;
    private String productId;
    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);
        param.put("productId", productId);
        page = 1;
        param.put("current", page);
        dataList = new ArrayList<>();
        dataAdapter = new AddStockSendApplyAdapter(R.layout.item_add_stock_apply, dataList, Integer.valueOf(state));
        dataAdapter.bindToRecyclerView(rvData);
        dataAdapter.setEmptyView(R.layout.view_empty_content, rvData);
        changePermission();
        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");
            productId = arguments.getString("productId");
            orderType = arguments.getString("orderType");
        }
    }

    private void getData() {
        Observable<BaseBean> observable;
        if (TextUtils.equals(orderType, OrderType.SALE.getCode())) {
            observable = RtfUtils.getRtf().addStockApplyList(param);
        } else if (TextUtils.equals(orderType, OrderType.OUT_BUY.getCode())) {
            observable = RtfUtils.getRtf().addPoStockApplyList(param);
        } else if (TextUtils.equals(orderType, OrderType.SUPPLIER.getCode())) {
            observable = RtfUtils.getRtf().addFoStockApplyList(param);
        } else if (TextUtils.equals(orderType, OrderType.CRUCIBLE.getCode())) {
            observable = RtfUtils.getRtf().addCoStockApplyList(param);
        } else if (TextUtils.equals(orderType, OrderType.IN.getCode())) {
            observable = RtfUtils.getRtf().addIoStockApplyList(param);
        } else {
            observable = RtfUtils.getRtf().addStockApplyList(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<AddStockBean.RecordsBean> getList = JSON.parseObject(data.getData().toString(), AddStockBean.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(AddStockApplyDetailActivity.class,
                        "orderType", orderType,
                        "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;

                }
            }
        });
    }

    private void changePermission() {
        boolean hasPermission = true;
        if (TextUtils.equals(orderType, OrderType.SALE.getCode())) {
            hasPermission = WorkUtils.hasPermission(PagePermissionType.SO_ENTER_AUDIT.getPermission());
        } else if (TextUtils.equals(orderType, OrderType.OUT_BUY.getCode())) {
            hasPermission = WorkUtils.hasPermission(PagePermissionType.PO_ENTER_AUDIT.getPermission());
        } else if (TextUtils.equals(orderType, OrderType.SUPPLIER.getCode())) {
            hasPermission = WorkUtils.hasPermission(PagePermissionType.FO_ENTER_AUDIT.getPermission());
        } else if (TextUtils.equals(orderType, OrderType.CRUCIBLE.getCode())) {
            hasPermission = WorkUtils.hasPermission(PagePermissionType.CO_ENTER_AUDIT.getPermission());
        } else if (TextUtils.equals(orderType, OrderType.IN.getCode())) {
            hasPermission = WorkUtils.hasPermission(PagePermissionType.IO_ENTER_AUDIT.getPermission());
        }
        dataAdapter.setHasPermission(hasPermission);
        dataAdapter.notifyDataSetChanged();
    }

    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 (status!=1&&TextUtils.isEmpty(etRemark.getText().toString()) && status == 2) {
                    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("result", status);
        param.put("comment", remark);
        param.put("id", id);
        Observable<BaseBean> observable;
        if (TextUtils.equals(orderType, OrderType.SALE.getCode())) {
            observable = RtfUtils.getRtf().addStockApplyCheck(id + "", WorkUtils.convertMapToBody(param));
        } else if (TextUtils.equals(orderType, OrderType.OUT_BUY.getCode())) {
            observable = RtfUtils.getRtf().addPoStockApplyCheck(id + "", WorkUtils.convertMapToBody(param));
        } else if (TextUtils.equals(orderType, OrderType.SUPPLIER.getCode())) {
            observable = RtfUtils.getRtf().addFoStockApplyCheck(id + "", WorkUtils.convertMapToBody(param));
        } else if (TextUtils.equals(orderType, OrderType.CRUCIBLE.getCode())) {
            observable = RtfUtils.getRtf().addCoStockApplyCheck(id + "", WorkUtils.convertMapToBody(param));
        } else if (TextUtils.equals(orderType, OrderType.IN.getCode())) {
            observable = RtfUtils.getRtf().addIoStockApplyCheck(id + "", WorkUtils.convertMapToBody(param));
        } else {
            observable = RtfUtils.getRtf().addStockApplyCheck(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 CheckAddStockEvent());
                EventBus.getDefault().post(new CheckOrderEvent());
            }
        });
    }

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

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

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

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