package com.hw.nativeapp.ui.activity;

import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.view.View;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.hjq.bar.OnTitleBarListener;
import com.hjq.bar.TitleBar;
import com.hw.nativeapp.MApplication;
import com.hw.nativeapp.R;
import com.hw.nativeapp.httpnet.ErrorConsumer;
import com.hw.nativeapp.httpnet.ResponseConsumer;
import com.hw.nativeapp.httpnet.entity.PageAsk;
import com.hw.nativeapp.httpnet.entity.handleBean;
import com.hw.nativeapp.ui.activity.adapters.TicketCollectionAdapter;
import com.hw.nativeapp.ui.activity.adapters.TicketPurchaseAdapter;
import com.hw.nativeapp.utils.ActivityUtils;
import com.hw.nativeapp.utils.RxUtil;
import com.hw.nativeapp.utils.StockUtils;
import com.hw.nativeapp.utils.ToastUtils;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.header.ClassicsHeader;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;


public class TicketPurchaseActivity extends BaseActivity {

    @BindView(R.id.list_stock)
    RecyclerView listStock;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    @BindView(R.id.tx_noDataShow)
    TextView tx_noDataShow;

    public static final Integer COUNTDOWN_TIME = 120000;
    private CountDownTimer timer;
    private TitleBar titleBar;

    private PageAsk pageAsk = new PageAsk();
    private handleBean operLocation;
    private TicketPurchaseAdapter adapter;
    private String getId;

    private JSONArray dataList = new JSONArray();

    private ProgressDialog progressDialog;

    @Override
    void initView() {
        titleBar = findViewById(R.id.tb_main_bar);
        titleBar.setOnTitleBarListener(new OnTitleBarListener() {

            @Override
            public void onLeftClick(View v) {
                ActivityUtils.activityFinish(TicketPurchaseActivity.this, true );
            }

            @Override
            public void onTitleClick(View v) {

            }

            @Override
            public void onRightClick(View v) {

            }

        });
        getPageTransmitParams();
        initListView();
        startCountDownTimer();
    }


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_ticket_purchase);
    }

    @Override
    protected void onStart() {
        super.onStart();
        initLoadData();
    }

    @Override
    protected void onDestroy() {
//        initLoadData();
        super.onDestroy();
    }


    //获取页面传递参数
    private void getPageTransmitParams(){
        Intent transmitIntent = getIntent();
        getId = transmitIntent.getStringExtra("id");
    }

    private void reflashFinish(){
        if (refreshLayout != null){
            refreshLayout.finishRefresh();
            refreshLayout.finishLoadMore();
        }
    }

    private void initListView(){
        //线性布局
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        listStock.setLayoutManager(linearLayoutManager);

        adapter = new TicketPurchaseAdapter(this);
        adapter.setOnOutBtnClickListerer((bean, position) -> {
            Bundle bundle = new Bundle();
            bundle.putString("performId", bean.id);
            ActivityUtils.launchActivity(this, SelectInfoActivity.class, bundle);
        });
        listStock.setAdapter(adapter);

        //下拉刷新
        refreshLayout.setRefreshHeader(new ClassicsHeader(this));
        //上拉加载
        refreshLayout.setRefreshFooter(new ClassicsFooter(this));
        //为下来刷新添加事件
        refreshLayout.setOnRefreshListener(refreshlayout -> initLoadData());
        //为上拉下载添加事件
        refreshLayout.setOnLoadMoreListener(refreshlayout -> {
            if (pageAsk.pageNum > pageAsk.pageCount){
                ToastUtils.showLongToast(TicketPurchaseActivity.this, "没有太多数据了");
                refreshlayout.finishLoadMore();
            }else{
                getDataList(false);
            }
        });
    }

    private void initLoadData(){
        pageAsk.pageNum = 1;
        pageAsk.pageSize = 20;
        getDataList(true);
    }

    private void getDataList(boolean cleaned){
        Map< String,String> options = new HashMap<>();
        MApplication.getApiService().selectAll( options, System.currentTimeMillis() / 1000)
                .compose(RxUtil.applyObservableAsync())
                .subscribe(new ResponseConsumer<JSONObject>() {
                    @Override
                    public void onSuccess(JSONObject data) {
//                        pageHandle(data.getInteger("total"), data.getInteger("page"),data.getInteger("pages"));
                        JSONArray rows = data.getJSONArray("list");
                        dataList = rows;
                        if (rows != null && !rows.isEmpty()){
                            List<handleBean> rowbeans = JSONArray.parseArray(JSON.toJSONString(rows), handleBean.class);
                            reflashLoadData(rowbeans, cleaned);
                            emptyShow(false);
                        }else {
                            emptyShow(true);
                        }
                        reflashFinish();
                    }

                    @Override
                    public void onFailed(int code, String msg) {
                        reflashFinish();
                    }
                }, new ErrorConsumer());
    }


    private void emptyShow(boolean empty){
        if (empty){
            tx_noDataShow.setVisibility(View.VISIBLE);
            refreshLayout.setVisibility(View.GONE);
        }else{
            refreshLayout.setVisibility(View.VISIBLE);
            tx_noDataShow.setVisibility(View.GONE);
        }

    }

    private void pageHandle(int total, int page, int pageCount){
        if (pageAsk.pageNum <= pageCount){
            pageAsk.pageNum++;
        }
        pageAsk.pageCount = pageCount;
        pageAsk.total = total;
    }
    private void reflashLoadData(List<handleBean> rows, boolean cleared){
        if (adapter == null){
            return;
        }
        if (cleared){
            adapter.clearDatas();
        }
        adapter.addDatas(rows);
    }

    private void jumpToLogin(){
        stopCountDownTimer();
        ActivityUtils.activityFinish(TicketPurchaseActivity.this, true);
    }
    private void stopCountDownTimer(){
        if (timer != null){
            timer.cancel();
        }
    }
    private void startCountDownTimer(){
        timer = new CountDownTimer(COUNTDOWN_TIME, 1000) {
            @SuppressLint("SetTextI18n")
            @Override
            public void onTick(long millisUntilFinished) {
                titleBar.setRightTitle(millisUntilFinished / 1000 + "s");
            }

            @Override
            public void onFinish() {
                jumpToLogin();
            }
        };
        timer.start();
    }
}
