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

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

    private void getData() {
        RtfUtils.getRtf().endApplyList(getIntent().getStringExtra("orderId"), 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<EndApplyBean.RecordsBean> getList = JSON.parseObject(data.getData().toString(), EndApplyBean.class).getRecords();
                dataList.clear();
                dataList.addAll(getList);
                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.setOnLoadMoreListener(new BaseQuickAdapter.RequestLoadMoreListener() {
//            @Override
//            public void onLoadMoreRequested() {
//                param.put("current", page);
//                getData();
//            }
//        }, rvData);
        dataAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                startActivity(EndApplyDetailActivity.class,
                       "orderType", getIntent().getStringExtra("orderType"),
                        "info", JSON.toJSONString(dataList.get(position)));
            }
        });
    }

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

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        if (TextUtils.equals("status", getIntent().getStringExtra("300"))) {
            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);
                }
            } else if (TextUtils.equals(orderType, OrderType.CRUCIBLE.getCode())) {
            } else {
            }
        }
        return super.onCreateOptionsMenu(menu);
    }

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


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


    private void check(String remark) {
        Map<String, Object> param = WorkUtils.simpleParam();
        param.put("orderType", getIntent().getStringExtra("orderType"));
        param.put("applyRemark", remark);
        param.put("orderId", getIntent().getStringExtra("orderId"));
        RtfUtils.getRtf().endApply(getIntent().getStringExtra("orderId"), 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("操作成功");
                getData();
            }
        });
    }

}
