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.os.Handler;
import android.util.Log;
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.blankj.utilcode.util.ToastUtils;
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.PurchaseInfoAdapter;
import com.hw.nativeapp.ui.activity.adapters.TicketCollectionAdapter;
import com.hw.nativeapp.utils.ActivityUtils;
import com.hw.nativeapp.utils.MaskUtil;
import com.hw.nativeapp.utils.RxUtil;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.header.ClassicsHeader;

import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;


public class PurchaseInfoActivity 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.tx_num)
    TextView tx_num;
    @BindView(R.id.tx_total)
    TextView tx_total;

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

    private PageAsk pageAsk = new PageAsk();
    private handleBean operLocation;
    private PurchaseInfoAdapter adapter;

    private ProgressDialog progressDialog;

    private String performId = "";
    private String auditoriumId = "";
    private String date = "";
    private String goodsId = "";
    private String salePeice = "";
    private String performTimeId = "";
    private String seatTypeId = "";
    private String type = "";  // 1 是购票人  2是观影人
    private String name = "";
    private String total = "";
    private String totalPeice = "";
    private String idcard = "";
    private JSONArray viewerList = new JSONArray();

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

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

            @Override
            public void onTitleClick(View v) {

            }

            @Override
            public void onRightClick(View v) {

            }

        });
        getPageTransmitParams();
        initListView();
        getDataList(true);;
        startCountDownTimer();
    }


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

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

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

    @OnClick({R.id.determine_btn, R.id.continue_btn})
    public void onClick(View v){
        switch (v.getId()){
            case R.id.determine_btn:
                orderSubmit();
                break;
            case R.id.continue_btn:
                jumpPage();
                break;
        }
    }
    // 订单提交
    private void orderSubmit(){
        JSONObject options = new  JSONObject();
        options.put("performId", performId);
        options.put("auditoriumId", auditoriumId);
        options.put("performTimeId", performTimeId);
        options.put("seatTypeId", seatTypeId);
        options.put("source", "8");
        options.put("totalPrice", Double.valueOf(salePeice) * viewerList.size());

        // 商品列表
        JSONArray goodsList = new  JSONArray();
        JSONObject goods = new  JSONObject();
        goods.put("goodsId", goodsId);
        goods.put("salePeice", salePeice);
        goods.put("saleNum", "1");
        goodsList.add(goods);
        options.put("goodsList", goodsList);

        // 购票人信息
        JSONObject purchaser = new  JSONObject();
        purchaser.put("name", name);
        purchaser.put("idcard", idcard);
        options.put("purchaser", purchaser);

        // 观影人列表
        JSONArray viewerList1 = new  JSONArray();
        if(viewerList != null && viewerList.size() > 0){
            for (int i = 0; i < viewerList.size(); i++) {
                JSONObject viewer = new  JSONObject();
                viewer.put("name", viewerList.getJSONObject(i).getString("name"));
                viewer.put("idcard", viewerList.getJSONObject(i).getString("idcard"));
                viewerList1.add(viewer);
            }
        }
        options.put("viewerList", viewerList1);
        progressDialog = MaskUtil.showProgressDialog( "正在提交...", PurchaseInfoActivity.this);
        new Handler().postDelayed(() -> {
            if(progressDialog != null){
                progressDialog.dismiss();
            }
        }, 30000);
        MApplication.getApiService().orderSubmit( options, System.currentTimeMillis() / 1000)
                .compose(RxUtil.applyObservableAsync())
                .subscribe(new ResponseConsumer<JSONObject>() {
                    @Override
                    public void onSuccess(JSONObject data) {
                        if(data.getString("orderId") != null && !data.getString("orderId").equals("")) {
                            if(progressDialog != null){
                                progressDialog.dismiss();
                            }
                            successFu(data.getString("orderId"));
                        } else {
                            if(progressDialog != null){
                                progressDialog.dismiss();
                            }
                        }
                    }

                    @Override
                    public void onFailed(int code, String msg) {
                        if(progressDialog != null){
                            progressDialog.dismiss();
                        }
                    }
                }, new ErrorConsumer());
    }
    private void successFu (String orderId) {
        Bundle bundle = new Bundle();
        bundle.putString("orderId", orderId);
        bundle.putString("idcard", idcard);
        bundle.putString("total", total);
        bundle.putString("totalPeice", totalPeice);
        bundle.putString("viewerList", JSONArray.toJSONString(viewerList));
        ActivityUtils.launchActivity(this,PaymentMethodActivity.class, bundle);
    }
    // 继续添加观影人
    private void jumpPage () {
        Bundle bundle = new Bundle();
        bundle.putString("performId", performId);
        bundle.putString("auditoriumId", auditoriumId);
        bundle.putString("performTimeId", performTimeId);
        bundle.putString("seatTypeId", seatTypeId);
        bundle.putString("goodsId", goodsId);
        bundle.putString("salePeice", salePeice);
        bundle.putString("type", "2");
        bundle.putString("name", name);
        bundle.putString("idcard", idcard);
        bundle.putString("viewerList", JSONArray.toJSONString(viewerList));
        ActivityUtils.launchActivity(this,InfoInputActivity.class, bundle);
    }
    //获取页面传递参数
    private void getPageTransmitParams(){
        Intent transmitIntent = getIntent();
        performId = transmitIntent.getStringExtra("performId");
        auditoriumId = transmitIntent.getStringExtra("auditoriumId");
        goodsId = transmitIntent.getStringExtra("goodsId");
        salePeice = transmitIntent.getStringExtra("salePeice");
        performTimeId = transmitIntent.getStringExtra("performTimeId");
        seatTypeId = transmitIntent.getStringExtra("seatTypeId");
        type = transmitIntent.getStringExtra("type");
        name = transmitIntent.getStringExtra("name");
        idcard = transmitIntent.getStringExtra("idcard");
        viewerList = JSONArray.parseArray(transmitIntent.getStringExtra("viewerList"));
    }

    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 PurchaseInfoAdapter(this);
        listStock.setAdapter(adapter);

        //下拉刷新
        refreshLayout.setRefreshHeader(new ClassicsHeader(this));
        //上拉加载
        refreshLayout.setRefreshFooter(new ClassicsFooter(this));
        //为下来刷新添加事件
        refreshLayout.setOnRefreshListener(refreshlayout -> reflashFinish());
        //为上拉下载添加事件
        refreshLayout.setOnLoadMoreListener(refreshlayout -> {
            reflashFinish();
        });
    }

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

    private void getDataList(boolean cleaned){
        JSONArray rows = new  JSONArray();
        if(viewerList != null && viewerList.size() > 0) {
            for (int i = 0; i < viewerList.size(); i++) {
                JSONObject obj1 =  new JSONObject();
                obj1.put("id", i+1);
                obj1.put("name", viewerList.getJSONObject(i).getString("name"));
                obj1.put("idcard", viewerList.getJSONObject(i).getString("idcard"));
                rows.add(obj1);
            }
        }
        dataList = rows;
        tx_num.setText("共" + rows.size() + "张, 合计");
        tx_total.setText("¥" + (rows.size() * Double.valueOf(salePeice)));
        total = String.valueOf(rows.size());
        totalPeice = String.valueOf(rows.size() * Double.valueOf(salePeice));
        if (rows != null && !rows.isEmpty()){
            List<handleBean> rowbeans = JSONArray.parseArray(JSON.toJSONString(rows), handleBean.class);
            reflashLoadData(rowbeans, cleaned);
            emptyShow(false);
        }else {
            emptyShow(false);
        }
        reflashFinish();
    }


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

}
