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.UseApplyBean;
import com.wd.workoffice.bean.event.CheckUseEvent;
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.UseApplyDetailActivity;
import com.wd.workoffice.ui.adapter.UseApplyAdapter;
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 UseApplyFragment 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 UseApplyAdapter dataAdapter;
    private List<UseApplyBean.RecordsBean> dataList;
    private String orderItemId;
    private String product;
    private String orderType;
    private String productId;

    @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("orderItemId", orderItemId);
        param.put("productId", productId);
        page = 1;
        param.put("current", page);
        dataList = new ArrayList<>();
        dataAdapter = new UseApplyAdapter(R.layout.item_use_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");
            orderItemId = arguments.getString("orderItemId");
            product = arguments.getString("product");
            orderType = arguments.getString("orderType");
            productId = arguments.getString("productId");
        }
    }

    private void changePermission() {
        boolean hasPermission =true;
        if (TextUtils.equals(orderType, OrderType.SALE.getCode())) {
            hasPermission =WorkUtils.hasPermission(PagePermissionType.SO_USE_APPLY_AUDIT.getPermission());
        } else if (TextUtils.equals(orderType, OrderType.BUILD.getCode())) {
            hasPermission =WorkUtils.hasPermission(PagePermissionType.AO_USE_APPLY_AUDIT.getPermission());
        } else if (TextUtils.equals(orderType, OrderType.OUT_BUY.getCode())) {
            hasPermission =WorkUtils.hasPermission(PagePermissionType.PO_USE_APPLY_AUDIT.getPermission());
        }
        dataAdapter.setHasPermission(hasPermission);
        dataAdapter.notifyDataSetChanged();
    }

    private void getData() {
        Observable<BaseBean> observable;
        if (TextUtils.equals(orderType, OrderType.SALE.getCode())) {
            observable = RtfUtils.getRtf().useApply(param);
        } else if (TextUtils.equals(orderType, OrderType.BUILD.getCode())) {
            observable = RtfUtils.getRtf().useAoApply(param);
        } else if (TextUtils.equals(orderType, OrderType.OUT_BUY.getCode())) {
            observable = RtfUtils.getRtf().usePoApply(param);
        } else {
            observable = RtfUtils.getRtf().useApply(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<UseApplyBean.RecordsBean> getList = JSON.parseObject(data.getData().toString(), UseApplyBean.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(UseApplyDetailActivity.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(), dataList.get(position).getProductAmount());
                        break;
                    case R.id.tv_agree:
                        checkDialog(1, dataList.get(position).getId(), dataList.get(position).getProductAmount());
                        break;

                }
            }
        });
    }


    private void checkDialog(int status, int id, double productAmount) {
        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);
        etRemark.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                tvNum.setText(s.length() + "/140");
            }
        });
        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, productAmount);
                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, double productAmount) {
        Map<String, Object> checkParam = WorkUtils.simpleParam();
        checkParam.put("status", status);
        checkParam.put("auditRemark", remark);
        checkParam.put("productAmount", productAmount);
        checkParam.put("id", id);
        Observable<BaseBean> observable;
        if (TextUtils.equals(orderType, OrderType.SALE.getCode())) {
            observable = RtfUtils.getRtf().useApplyCheck(id + "", WorkUtils.convertMapToBody(checkParam));
        } else if (TextUtils.equals(orderType, OrderType.BUILD.getCode())) {
            observable = RtfUtils.getRtf().useAoApplyCheck(id + "", WorkUtils.convertMapToBody(checkParam));
        } else {
            observable = RtfUtils.getRtf().useApplyCheck(id + "", WorkUtils.convertMapToBody(checkParam));
        }
        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("操作成功");
                page = 1;
                param.put("current", page);
                getData();
            }
        });
    }

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