package com.wd.workoffice.ui.activity.mes.ticket;

import android.content.Intent;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.wd.workoffice.R;
import com.wd.workoffice.app.BaseMesBean;
import com.wd.workoffice.app.WorkToolBarActivity;
import com.wd.workoffice.bean.event.AddTicketEvent;
import com.wd.workoffice.bean.mesBean.TicketBean;
import com.wd.workoffice.retrofit.RtfUtils;
import com.wd.workoffice.retrofit.WorkObserver;
import com.wd.workoffice.ui.adapter.MesTicketAdapter;
import com.wd.workoffice.util.UserKeeper;
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.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
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 MesTicketListActivity extends WorkToolBarActivity {

    @BindView(R.id.tv_go)
    TextView tvGo;
    @BindView(R.id.rv_data)
    RecyclerView rvData;
    @BindView(R.id.srl_refresh)
    SmartRefreshLayout srlRefresh;
    @BindView(R.id.btn_add)
    Button btnAdd;
    private int page = 1;
    private Map<String, Object> param;
    private List<TicketBean.ListBean> dataList;
    private MesTicketAdapter dataAdapter;
    private JSONArray permission;

    @Override
    protected void initView() {
        ButterKnife.bind(this);
        tvGo.setText("任务担当\n" +
                "页面");
        tvGo.setVisibility(View.GONE);
        rvData.setLayoutManager(new LinearLayoutManager(this, RecyclerView.VERTICAL, false));
    }

    private void getButtonPermission() {
        String mesMenuId = WorkUtils.getMesMenuId("市场服务", "服务工单");
        if (TextUtils.isEmpty(mesMenuId)){
            return;
        }
        RtfUtils.getMesRtf().buttonPermission(mesMenuId).compose(Transformer.schedule()).subscribe(new WorkObserver<BaseMesBean>() {
            @Override
            public void doOnSubscribe(Disposable d) {
            }

            @Override
            public void onFail(String errorMsg) {
                hideLoading();
                toast(errorMsg);
            }

            @Override
            public void onSuccess(BaseMesBean data) {
                hideLoading();
                if (!data.isSuccess()) {
                    toast(data.getMessage());
                    return;
                }
                permission = JSON.parseArray(data.getData().toString());
                if (WorkUtils.hasMesMenuPermission(permission, "新建")) {
                    btnAdd.setVisibility(View.VISIBLE);
                }
            }
        });
    }


    @Override
    protected void initData() {
        dataList = new ArrayList<>();
        dataAdapter = new MesTicketAdapter(R.layout.item_mes_ticket, dataList);
        dataAdapter.bindToRecyclerView(rvData);
        dataAdapter.setEmptyView(R.layout.view_empty_content, rvData);
        param = WorkUtils.pageMesKey();
        param.put("pageNum", page);
        getData();
    }

    private void getData() {
        getButtonPermission();
        RtfUtils.getMesRtf().ticketList("1", WorkUtils.convertMapToBody(param)).compose(Transformer.schedule()).subscribe(new WorkObserver<BaseMesBean>() {
            @Override
            public void doOnSubscribe(Disposable d) {
            }

            @Override
            public void onFail(String errorMsg) {
                hideLoading();
                toast(errorMsg);
            }

            @Override
            public void onSuccess(BaseMesBean data) {
                hideLoading();
                if (!data.isSuccess()) {
                    toast(data.getMessage());
                    return;
                }
                List<TicketBean.ListBean> getList = JSON.parseObject(data.getData().toString(), TicketBean.class).getList();
                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("pageNum", page);
            getData();
        });
        dataAdapter.setOnLoadMoreListener(() -> {
            param.put("pageNum", page);
            getData();
        }, rvData);
        dataAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                boolean isJob = TextUtils.equals(UserKeeper.getInstance().getMesUid(), dataList.get(position).getJobUserId());
                switch (dataList.get(position).getJobStatus()) {
                    case 0:
                        startActivity(MesTicketAddActivity.class, "from", isJob ? "1" : "0", "data", JSON.toJSONString(dataList.get(position)));
                        break;
                    case 1:
                        startActivity(MesTicketDetailActivity.class,
                                "from", isJob ? "1" : "0", "data", JSON.toJSONString(dataList.get(position)),"permission",permission == null ? "" :permission.toJSONString());
                        break;
                    case 2:
                        startActivity(MesTicketDetailActivity.class, "from", isJob ? "1" : "0", "data", JSON.toJSONString(dataList.get(position)),"permission",permission == null ? "" :permission.toJSONString());
                        break;
                    case 3:
                        startActivity(MesTicketDetailFinishActivity.class, "from", isJob ? "1" : "0", "data", JSON.toJSONString(dataList.get(position)),"permission",permission == null ? "" :permission.toJSONString());
                        break;
                    case 4:
                        startActivity(MesTicketDetailReviewActivity.class, "from", isJob ? "1" : "0", "data", JSON.toJSONString(dataList.get(position)),"permission",permission == null ? "" :permission.toJSONString());
                        break;
                    case 5:
                        startActivity(MesTicketDetailActivity.class,
                                "from", isJob ? "1" : "0", "data", JSON.toJSONString(dataList.get(position)),"permission",permission == null ? "" :permission.toJSONString());
                        break;
                    case 9:
                        startActivity(MesTicketDetailActivity.class,
                                "from", isJob ? "1" : "0", "data", JSON.toJSONString(dataList.get(position)),"permission",permission == null ? "" :permission.toJSONString());
                        break;
                }
            }
        });
    }


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

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_mes_search, menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.search:
                startActivityForResult(MesTicketConditionActivity.class, 10001);
                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(AddTicketEvent event) {
        page = 1;
        param.put("pageNum", page);
        getData();
    }

    @OnClick({R.id.tv_go, R.id.btn_add})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_go:
                startActivity(MesTicketListTakeOnActivity.class);
                finish();
                break;
            case R.id.btn_add:
                startActivity(MesTicketAddActivity.class);
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 10001 && resultCode == 10001) {
            String returnParam = data.getStringExtra("param");
            param.put("paramMap", JSON.parseObject(returnParam, Map.class));
            page = 1;
            param.put("pageNum", page);
            getData();
        }
    }

}
