package com.rv.rvmine.personal;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.base.utils.ui.datetime.selector.util.TextUtil;
import com.frame.base.bus.RxBus;
import com.frame.base.url.Constance;
import com.frame.rv.config.RvFrameConfig;
import com.ruiwenliu.wrapper.util.ViewHolder;
import com.ruiwenliu.wrapper.util.glide.GlideManager;
import com.ruiwenliu.wrapper.util.permission.RxPermission;
import com.rv.home.rv.module.ApiConfig;
import com.rv.home.rv.module.basic.dialog.PickerDialog;
import com.rv.home.rv.module.ui.main.home.bean.ImageUploadBean;
import com.rv.rvmine.R2;
import com.ruiwenliu.wrapper.base.BaseBean;
import com.ruiwenliu.wrapper.base.BaseStatusActivity;
import com.ruiwenliu.wrapper.weight.TitleView;
import com.rv.home.rv.module.basic.presenter.PickerPresenter;
import com.rv.rvmine.R;
import com.rv.rvmine.rxbusevent.UserInfoEvent;
import com.yuyife.okgo.OkGoUtil;

import java.io.File;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.functions.Consumer;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import pub.devrel.easypermissions.AppSettingsDialog;
import pub.devrel.easypermissions.EasyPermissions;
import top.zibin.luban.Luban;
import top.zibin.luban.OnCompressListener;

/**
 * 实名认证
 */
@Route(path = Constance.ACTIVITY_URL_IDCARDCERTIFICATION)
public class IDCardCertificationActivity extends BaseStatusActivity<PickerPresenter> implements EasyPermissions.PermissionCallbacks {

    @BindView(R2.id.et_name)
    EditText etName;
    @BindView(R2.id.et_phone)
    EditText etPhone;
    @BindView(R2.id.et_id_card)
    EditText etIdCard;
    @BindView(R2.id.iv_card)
    ImageView ivCard;
    @BindView(R2.id.ll_card)
    LinearLayout llCard;
    @BindView(R2.id.rl_card)
    RelativeLayout rlCard;
    @BindView(R2.id.iv_card_copy)
    ImageView ivCardCopy;
    @BindView(R2.id.ll_card_copy)
    LinearLayout llCardCopy;
    @BindView(R2.id.rl_card_copy)
    RelativeLayout rlCardCopy;
    @BindView(R2.id.tv_ok)
    TextView tvOk;

    private int cardType;
    private String strCard;
    private String strCardCopy;
    private String[] photoPermissions = {};


    public static Intent getIntent(Context context) {
        return new Intent(context, IDCardCertificationActivity.class);
    }

    @Override
    protected int setLayout() {
        return R.layout.activity_idcard_certification;
    }

    @Override
    protected void initView(Bundle savedInstanceState, TitleView titleView, Intent intent) {
        titleView.setTitle(mActivity.getString(R.string.tv_id_card_certrfication_title));
    }

    @Override
    public void onShowResult(int requestType, BaseBean result) {
        switch (requestType) {
            case 0:
                ImageUploadBean bean = (ImageUploadBean) result;
                if (cardType == 0) {
                    strCard = bean.getData();
                } else {
                    strCardCopy = bean.getData();
                }
                break;
            case 1:
                startActivity(SuccessfulCertificationActivity.getIntent(mActivity));
                RxBus.post(new UserInfoEvent());
                finish();
                break;
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ButterKnife.bind(this);
    }

    @OnClick({R2.id.rl_card, R2.id.rl_card_copy, R2.id.tv_ok})
    public void onViewClicked(View view) {
        int id = view.getId();
        if (id == R.id.rl_card) {
            showPickerDialog(0);
        } else if (id == R.id.rl_card_copy) {
            showPickerDialog(1);
        } else if (id == R.id.tv_ok) {
            String name = etName.getText().toString().trim();
            if (TextUtils.isEmpty(name)) {
                showToast("姓名不能为空！");
                return;
            }

//            String phone = etPhone.getText().toString().trim();
//            if (TextUtils.isEmpty(phone)) {
//                showToast("手机号码不能为空！");
//                return;
//            }

            String idCard = etIdCard.getText().toString().trim();
            if (TextUtils.isEmpty(idCard)) {
                showToast("身份证号不能为空！");
                return;
            }

            if (TextUtils.isEmpty(strCard)) {
                showToast("身份证正面不能为空！");
                return;
            }
            if (TextUtils.isEmpty(strCardCopy)) {
                showToast("身份证反面不能为空！");
                return;
            }

            verified(name, idCard);
        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == mPresenter.TYPE_ALBUM_CODE) {
            if (data != null && data.getData() != null) {
                if (cardType == 0) {
                    llCard.setVisibility(View.GONE);
                } else {
                    llCardCopy.setVisibility(View.GONE);
                }
                GlideManager.getInstance(mActivity).loadImage(mPresenter.getUriUrl(data.getData()), cardType == 0 ? ivCard : ivCardCopy);
                uploadFile(new File(mPresenter.getRealFilePath(data.getData())), "album");
            }
            return;
        }
        if (requestCode == mPresenter.TYPE_CAMERA_CODE) {
            if (!TextUtil.isEmpty(mPresenter.gerCameraStoreUrl())) {
                if (cardType == 0) {
                    llCard.setVisibility(View.GONE);
                } else {
                    llCardCopy.setVisibility(View.GONE);
                }
                String url = String.format("%1$s%2$s", "file://", mPresenter.gerCameraStoreUrl());
                GlideManager.getInstance(mActivity).loadImage(url, cardType == 0 ? ivCard : ivCardCopy);
                uploadFile(new File(mPresenter.gerCameraStoreUrl()), "camera");
            }
        }
//        if (requestCode == AppSettingsDialog.DEFAULT_SETTINGS_REQ_CODE) {
//            processPicker();
//        }
    }


    private int typeCamera;

    /**
     * 显示相机弹窗
     */
    private void showPickerDialog(int type) {
        cardType = type;
        new PickerDialog(mActivity) {
            @Override
            public void helper(ViewHolder helper) {
                super.helper(helper);
                helper.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        int i = v.getId();
                        if (i == com.rv.home.R.id.btn_camera) {
                            typeCamera = mPresenter.TYPE_CAMERA_CODE;
                            processPicker();
                            dismiss();

                        } else if (i == com.rv.home.R.id.btn_album) {
                            typeCamera = mPresenter.TYPE_ALBUM_CODE;
                            processPicker();
                            dismiss();

                        } else if (i == com.rv.home.R.id.btn_cancel) {
                            dismiss();

                        }

                    }
                }, com.rv.home.R.id.btn_camera, com.rv.home.R.id.btn_album, com.rv.home.R.id.btn_cancel);
            }
        }.show();
    }

    /**
     * 打开相机和相册
     *
     * @param type 1、相机2、相册
     * <p>
     * 此处方法不奏效
     */
//    @SuppressLint("CheckResult")
//    private void processPicker(final int type) {
//        /**
//         * 6.0以上手机做权限处理
//         */
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
//            new RxPermission(mActivity).request(
//                    new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE,
//                            Manifest.permission.CAMERA}).subscribe(new Consumer<Boolean>() {
//                @Override
//                public void accept(Boolean aBoolean) throws Exception {
//                    if (aBoolean == true) {
//                        switch (type) {
//                            case 1001:
//                                mPresenter.openCamera(false);
//                                break;
//                            case 1002:
//                                mPresenter.openAlbum(false);
//                                break;
//                        }
//
//                    }
//                }
//            });
//        } else {
//            switch (type) {
//                case 1001:
//                    mPresenter.openCamera(false);
//                    break;
//                case 1002:
//                    mPresenter.openAlbum(false);
//                    break;
//            }
//        }
//    }
    private String[] cameraPermissions = {Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE};

    private void processPicker() {

        if (!EasyPermissions.hasPermissions(this, cameraPermissions)) {
            EasyPermissions.requestPermissions(this, "拍照需要此权限，否则无法正常使用", 1, cameraPermissions);
            return;
        }
        switch (typeCamera) {
            case 1001:
                mPresenter.openCamera(false);
                break;
            case 1002:
                mPresenter.openAlbum(false);
                break;
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        EasyPermissions.onRequestPermissionsResult(requestCode,permissions,grantResults, this);
    }

    /**
     * 上传文件
     *
     * @param files
     */
    private void uploadFile(File files, final String fileName) {


        Luban.with(this)
                .load(files)                                   // 传人要压缩的图片列表
                .ignoreBy(100)                                  // 忽略不压缩图片的大小
                .setCompressListener(new OnCompressListener() { //设置回调
                    @Override
                    public void onStart() {
                    }

                    @Override
                    public void onSuccess(File file) {
                        RequestBody requestFile =
                                RequestBody.create(MediaType.parse("application/otcet-stream"), file);
                        MultipartBody.Part body =
                                MultipartBody.Part.createFormData("file", file.getName(), requestFile);
                        RequestBody description =
                                RequestBody.create(
                                        MediaType.parse("multipart/form-data"), fileName);
                        mPresenter.getUploadFile(RvFrameConfig.VEHICLE_UPLOAD, 0, ApiConfig.HTTP_URL_FILE_UPLOAD, ImageUploadBean.class, description, body, true);
                    }

                    @Override
                    public void onError(Throwable e) {

                    }
                }).launch();    //启动压缩
    }


    private void verified(String name, String idCard) {
//        strCard ="https://xxtest.upyuns.com/image/app/20190605092021.jpg";
//        strCardCopy = "https://xxtest.upyuns.com/image/app/20190605092036.jpg";
        mPresenter.postBodyData(RvFrameConfig.VEHICLE_CAR_POST, 1, ApiConfig.HTTP_URL_CERTIFICATE, BaseBean.class, new Verified(name, idCard, 0, strCard, strCardCopy), getHeadMap(), true);
    }


    private Map<String, Object> getHeadMap() {
        Map<String, Object> headMap = new LinkedHashMap<>();
        if (OkGoUtil.getToken() != null)
            headMap.put("Authorization", OkGoUtil.getToken());
        return headMap;
    }

    @Override
    public void onPermissionsGranted(int requestCode, @NonNull List<String> perms) {
        processPicker();
    }

    @Override
    public void onPermissionsDenied(int requestCode, @NonNull List<String> perms) {
        Toast.makeText(this, "用户授权失败", Toast.LENGTH_SHORT).show();
        if (EasyPermissions.somePermissionPermanentlyDenied(this, perms)) {
            new AppSettingsDialog.Builder(this).
                    setTitle("需要权限")
                    .setRationale("如果没有这些权限，此应用程序可能无法正常工作,是否打开设置修改该应用权限")
                    .build().show();
        }
    }


    private class Verified {
        private String name;
        private String idNumber;
        private int certificateType;
        private String frontUrl;
        private String backUrl;

        public Verified(String name, String idNumber, int certificateType, String frontUrl, String backUrl) {
            this.name = name;
            this.idNumber = idNumber;
            this.certificateType = certificateType;
            this.frontUrl = frontUrl;
            this.backUrl = backUrl;
        }

        public String getIdNumber() {
            return idNumber;
        }

        public void setIdNumber(String idNumber) {
            this.idNumber = idNumber;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public int getCertificateType() {
            return certificateType;
        }

        public void setCertificateType(int certificateType) {
            this.certificateType = certificateType;
        }

        public String getFrontUrl() {
            return frontUrl;
        }

        public void setFrontUrl(String frontUrl) {
            this.frontUrl = frontUrl;
        }

        public String getBackUrl() {
            return backUrl;
        }

        public void setBackUrl(String backUrl) {
            this.backUrl = backUrl;
        }
    }

}
