package com.hw.nativeapp.ui.activity;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.widget.CheckBox;
import android.widget.TextView;
import android.widget.Toast;

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.PurchaseReceiptBean;
import com.hw.nativeapp.httpnet.entity.WarehousingDetailsBean;
import com.hw.nativeapp.httpnet.entity.handleBean;
import com.hw.nativeapp.ui.activity.adapters.TicketCollectionAdapter;
import com.hw.nativeapp.ui.dialogs.DialogCommon;
import com.hw.nativeapp.utils.ActivityUtils;
import com.hw.nativeapp.utils.MaskUtil;
import com.hw.nativeapp.utils.RxUtil;
import com.hw.nativeapp.utils.StockUtils;
import com.hw.nativeapp.utils.StringUtils;
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;
import butterknife.OnClick;


public class TicketCollectionActivity extends BaseActivity  {

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


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

    private PageAsk pageAsk = new PageAsk();
    private handleBean operLocation;
    private TicketCollectionAdapter adapter;
    private String qrcodeNo;
    private String idcard = "";

    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(TicketCollectionActivity.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_collection);
    }

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

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

    @OnClick({R.id.print_btn,R.id.all_btn})
    public void onClick(View v){
        switch (v.getId()){
            case R.id.print_btn:
                printTicket();
                break;
            case R.id.all_btn:
                for (int i = 0; i < dataList.size(); i++) {
                    dataList.getJSONObject(i).put("checkedStatus", all_btn.isChecked());
                }
                setDataList(true);
                break;
        }
    }


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

    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 TicketCollectionAdapter(this);
        adapter.setOnOutBtnClickListerer((bean, position) -> {
            for (int i = 0; i < dataList.size(); i++) {
                if(bean.id.equals(dataList.getJSONObject(i).getString("id"))){
                    dataList.getJSONObject(i).put("checkedStatus", bean.checkedStatus);
                }
            }
        });
        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(TicketCollectionActivity.this, "没有太多数据了");
                refreshlayout.finishLoadMore();
            }else{
                getDataList(false);
            }
        });
    }

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

    private void setDataList(boolean cleaned){
        if (dataList != null && !dataList.isEmpty()){
            List<handleBean> rowbeans = JSONArray.parseArray(JSON.toJSONString(dataList), handleBean.class);
            reflashLoadData(rowbeans, cleaned);
            emptyShow(false);
        }else {
            emptyShow(true);
        }
        reflashFinish();
    }


    private void getDataList(boolean cleaned){
        Map< String,String> options = new HashMap<>();
        if(qrcodeNo != null && !qrcodeNo.isEmpty()){
            options.put("qrcodeNo", qrcodeNo);
        }
        if(idcard != null && !idcard.isEmpty()){
            options.put("idcard", idcard);
        }
        MApplication.getApiService().getValidList( 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");
                        for (int i = 0; i < rows.size(); i++) {
                            rows.getJSONObject(i).put("checkedStatus", false);
                        }

                        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(TicketCollectionActivity.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();
    }

    // 打印
    private void printTicket() {
        JSONArray viewerList = new JSONArray();
        for (int i = 0; i < dataList.size(); i++) {
            if(dataList.getJSONObject(i).getBooleanValue("checkedStatus")){
                JSONObject obj = new JSONObject();
                obj.put("id",   dataList.getJSONObject(i).getString("id"));
                obj.put("orderId",  dataList.getJSONObject(i).getString("orderId"));
                obj.put("name",  dataList.getJSONObject(i).getString("name"));
                obj.put("idcard",   dataList.getJSONObject(i).getString("idcard"));
                viewerList.add(obj);
            }
        }
        if(viewerList == null || viewerList.size() == 0){
            Toast.makeText(TicketCollectionActivity.this, "请选择要打印的票", Toast.LENGTH_SHORT).show();
            return;
        }
        Bundle bundle = new Bundle();
        bundle.putString("viewerList", JSONArray.toJSONString(viewerList));
        ActivityUtils.launchActivity(this,IssueTicketsActivity.class, bundle);
    }

}
