package com.dskj.daikuan.ui.activity;

import android.Manifest;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.FileUtils;
import android.os.Handler;
import android.provider.ContactsContract;
import android.provider.MediaStore;
import android.view.View;
import android.webkit.MimeTypeMap;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.lifecycle.ViewModelProviders;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.azhon.basic.base.BaseActivity;
import com.dskj.daikuan.R;
import com.dskj.daikuan.adapter.comm.CommonAdapter;
import com.dskj.daikuan.adapter.comm.ViewHolder;
import com.dskj.daikuan.api.Api;
import com.dskj.daikuan.api.BaseObserver;
import com.dskj.daikuan.api.Result;
import com.dskj.daikuan.bean.ListBean;
import com.dskj.daikuan.bean.LoanBean;
import com.dskj.daikuan.bean.TokenBean;
import com.dskj.daikuan.config.Config;
import com.dskj.daikuan.databinding.ActivityMain2Binding;
import com.dskj.daikuan.utils.GsonUtils;
import com.dskj.daikuan.utils.LogUtils;
import com.dskj.daikuan.utils.RxBus;
import com.dskj.daikuan.viewModel.home.MainViewModel;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnLoadMoreListener;
import com.tbruyelle.rxpermissions2.RxPermissions;

import java.io.File;
import java.util.ArrayList;
import java.util.Locale;
import java.util.Vector;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import rx.Subscription;


public class MainActivity extends BaseActivity<MainViewModel, ActivityMain2Binding> {
    private RxPermissions rxPermissions;
    int index = 0;
    boolean isNeeDate = true;
    private ArrayList<LoanBean> lists = new ArrayList<>();
    int pageSize = 1;
    CommonAdapter commonAdapter;

    @Override
    protected MainViewModel initViewModel() {
        return ViewModelProviders.of(this).get(MainViewModel.class);
    }

    @Override
    protected void showError(Object obj) {

    }

    @Override
    protected int initLayout() {
        return R.layout.activity_main2;
    }

    @RequiresApi(api = Build.VERSION_CODES.Q)
    @Override
    protected void initView() {
        rxPermissions = new RxPermissions(this);
        initRefreshLayout();
        dataBinding.refreshLayout.autoRefresh();
        changeDate(true);
        dataBinding.menuTv.setOnClickListener(view -> addLoan());
        dataBinding.tijiaoBt.setOnClickListener(view -> addLoan());

        dataBinding.backButton.setOnClickListener(view -> addLoan());
    }

    private void changeDate(boolean isFirst) {
        if (isNeeDate) {
            dataBinding.refreshLayout.setVisibility(View.VISIBLE);
            dataBinding.nodateRy.setVisibility(View.GONE);
            if (!isFirst) {
                dataBinding.menuTv.setVisibility(View.VISIBLE);
            }
            initList();

        } else {
            dataBinding.refreshLayout.setVisibility(View.GONE);
            dataBinding.nodateRy.setVisibility(View.VISIBLE);
            dataBinding.menuTv.setVisibility(View.GONE);

        }
    }

    @Override
    protected void initData() {
//        getList();

    }

    private void getList() {
        Api.getInstance().getList(pageSize)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseObserver<Result<ListBean>>() {

                    @Override
                    public void onSuccess(Result<ListBean> feedbackResp) {
                        dataBinding.refreshLayout.finishRefresh();
                        dataBinding.refreshLayout.finishLoadMore();
                        if (pageSize == 1) {
                            lists = (ArrayList<LoanBean>) feedbackResp.data.getData();
                            commonAdapter.setDates(lists);
                        } else {
                            lists.addAll(feedbackResp.data.getData());
                            commonAdapter.setDates(lists);
                        }
                        if (lists.size() == 0) {
                            isNeeDate = false;
                        } else {
                            isNeeDate = true;
                        }
                        changeDate(false);
                        if (lists.size() == feedbackResp.data.getTotal()) {
                            dataBinding.refreshLayout.finishLoadMoreWithNoMoreData();
                        }
                    }

                    @Override
                    public void onError(int code, String msg) {
                        dataBinding.refreshLayout.finishRefresh();
                        dataBinding.refreshLayout.finishLoadMore();
                        if (lists.size() == 0) {
                            isNeeDate = false;
                        } else {
                            isNeeDate = true;
                        }
                        changeDate(false);
                    }
                });
    }

    private void initList() {
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        dataBinding.recyclerview.setLayoutManager(linearLayoutManager);
        commonAdapter = new CommonAdapter<LoanBean>(this, R.layout.agent_child_item, lists) {
            @Override
            public void convert(ViewHolder holder, LoanBean s, int index) {
                holder.setText(R.id.number_tv, "RM" + s.getAmount());
                holder.setText(R.id.name_tv, "Time：" + s.getCreate_time());
                // 0审核中 1通过 2失败
                TextView textView = holder.getView(R.id.status_tv);
                textView.setTextColor(getResources().getColor(R.color.white));
                if (s.getStatus() == 0) {
                    holder.setText(R.id.status_tv, "processing");

                } else if (s.getStatus() == 1) {
                    holder.setText(R.id.status_tv, "success");

                } else if (s.getStatus() == 2) {
                    holder.setText(R.id.status_tv, "fail");
                    textView.setTextColor(getResources().getColor(R.color.color_search_2));

                }
                holder.getView(R.id.big_ly).setOnClickListener(view -> {
                    Intent intent = new Intent(MainActivity.this, XiangQingActivity.class);
                    intent.putExtra("id", s.getId());
                    startActivity(intent);
                });
            }
        };
        dataBinding.recyclerview.setAdapter(commonAdapter);
    }


    private void initRefreshLayout() {
        dataBinding.refreshLayout.setOnRefreshListener(refreshlayout -> {
            pageSize = 1;
            dataBinding.refreshLayout.setEnableLoadMore(true);
            getList();

        });
        dataBinding.refreshLayout.setOnLoadMoreListener(refreshLayout -> {
            pageSize += 1;
            getList();
        });
    }

    private void addLoan() {
        startActivity(new Intent(this, ShenQingActivity.class));
        finish();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (RESULT_OK == resultCode && requestCode == 777) {
            dataBinding.refreshLayout.autoRefresh();
        }
    }
}