package com.tjzhxx.union.activity;

import android.Manifest;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.lifecycle.Lifecycle;

import com.bumptech.glide.Glide;
import com.huantansheng.easyphotos.EasyPhotos;
import com.huantansheng.easyphotos.callback.SelectCallback;
import com.huantansheng.easyphotos.models.album.entity.Photo;
import com.tjzhxx.union.R;
import com.tjzhxx.union.entity.AuthenticationInfo;
import com.tjzhxx.union.entity.BaseResponse;
import com.tjzhxx.union.entity.Faceid;
import com.tjzhxx.union.entity.UserInfo;
import com.tjzhxx.union.entity.request.FaceidRequest;
import com.tjzhxx.union.entity.request.IsRepeatRequest;
import com.tjzhxx.union.permission.PermissionHelper;
import com.tjzhxx.union.permission.PermissionInterface;
import com.tjzhxx.union.public_store.ConstDefine;
import com.tjzhxx.union.public_store.FileUtils;
import com.tjzhxx.union.public_store.GlideEngine;
import com.tjzhxx.union.public_store.ImageUtils;
import com.tjzhxx.union.public_store.SpUtils;
import com.tjzhxx.union.public_store.retrofit.RetrofitUtils;
import com.tjzhxx.union.public_store.retrofit.UnionServices;
import com.tjzhxx.union.public_store.rx.DefaultSubscriber;
import com.tjzhxx.union.public_store.rx.ProgressSubscriber;
import com.tjzhxx.union.system.BaseActivity;
import com.tjzhxx.union.system.WebviewActivity;
import com.uber.autodispose.AutoDispose;
import com.uber.autodispose.android.lifecycle.AndroidLifecycleScopeProvider;

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

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

/**
 * 描述:
 *
 * @author yhx
 * @create 2021/9/2  8:57 AM
 */
public class AuthenticationActivity extends BaseActivity implements PermissionInterface {


    @BindView(R.id.name)
    TextView name;
    @BindView(R.id.sex)
    TextView sex;
    @BindView(R.id.national)
    TextView national;
    @BindView(R.id.idcard)
    TextView idcard;
    @BindView(R.id.positive)
    ImageView positive;
    @BindView(R.id.reverse)
    ImageView reverse;
    private UnionServices services;
    private PermissionHelper mPermissionHelper;
    private Boolean isPositive = true;
    private AuthenticationInfo info;
    @Override
    public int getContentViewLayoutID() {
        return R.layout.activity_authentication;
    }

    @Override
    public void bindViewAndEvent(Bundle savedInstanceState) {
        initTitle("实名认证");
        info = new AuthenticationInfo();
        services = RetrofitUtils.createApi(UnionServices.class, ConstDefine.HttpAdress);
        mPermissionHelper = new PermissionHelper(this, this);
    }


    @OnClick({R.id.positive, R.id.positive_close, R.id.reverse, R.id.reverse_close, R.id.next})
    public void onClick(View view) {
        Intent intent = new Intent();
        switch (view.getId()) {
            case R.id.positive:
                isPositive = true;
                mPermissionHelper.requestPermissions();
                break;
            case R.id.positive_close:

                break;
            case R.id.reverse:
                isPositive = false;
                mPermissionHelper.requestPermissions();
                break;
            case R.id.reverse_close:
                break;
            case R.id.next:
                if (TextUtils.isEmpty(info.getFrontsfzurl())){
                    showSnackBar("请上传正确的身份证正面");
                    return;
                }else  if (TextUtils.isEmpty(info.getBacksfzurl())){
                    showSnackBar("请上传正确的身份证反面");
                    return;
                }
                querysfzrepeatfromapp(info.getSfzid());
                break;
        }
    }

    //上传图片
    private void uploadImage(String path) {
        File file = new File(path);
        RequestBody imageBody = RequestBody.create(MediaType.parse("multipart/form-data"), file);
        MultipartBody.Part imageBodyPart = MultipartBody.Part.createFormData("file", file.getName(), imageBody);
        services.uploadImage(imageBodyPart)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .as(AutoDispose.<BaseResponse<String>>autoDisposable(AndroidLifecycleScopeProvider.from(this, Lifecycle.Event.ON_DESTROY)))
                .subscribe(new DefaultSubscriber<BaseResponse<String>>(this) {
                    @Override
                    public void success(BaseResponse<String> value) {
                        faceid(value.getData());
                    }

                });
    }

    //获取身份证信息
    private void faceid(String imgurl) {
        FaceidRequest request = new FaceidRequest();
        request.setImgurl(imgurl);
        if (isPositive) {
            request.setCardSide("FRONT");
        }else {
            request.setCardSide("BACK");
        }
        services.faceid(request)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .as(AutoDispose.<BaseResponse<Faceid>>autoDisposable(AndroidLifecycleScopeProvider.from(this, Lifecycle.Event.ON_DESTROY)))
                .subscribe(new ProgressSubscriber<BaseResponse<Faceid>>(this) {
                    @Override
                    public void success(BaseResponse<Faceid> value) {
                        if (value.getData() != null){
                            Faceid faceid = value.getData();
                            if (isPositive) {
                                name.setText(faceid.getName());
                                sex.setText(faceid.getSex());
                                national.setText(faceid.getNation());
                                idcard.setText(faceid.getIdNum());
                                info.setWname(faceid.getName());
                                info.setAddress(faceid.getAddress());
                                info.setFrontsfzurl(imgurl);
                                info.setGender(faceid.getSex());
                                info.setNation(faceid.getNation());
                                info.setSfzid(faceid.getIdNum());
                            }else {
                                info.setBacksfzurl(imgurl);
                                info.setSfzenddate(faceid.getValidDate());
                            }
                        }else {
                            showSnackBar(value.getMsg());
                        }
                    }
                });
    }

    //查询身份证是否重复
    private void querysfzrepeatfromapp(String idNum) {
        IsRepeatRequest request = new IsRepeatRequest();
        request.setSfzid(idNum);
        services.querysfzrepeatfromapp(request)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .as(AutoDispose.<BaseResponse<UserInfo>>autoDisposable(AndroidLifecycleScopeProvider.from(this, Lifecycle.Event.ON_DESTROY)))
                .subscribe(new ProgressSubscriber<BaseResponse<UserInfo>>(this) {
                    @Override
                    public void success(BaseResponse<UserInfo> value) {
                        if (value.getData() ==  null){
                            Intent intent = new Intent();
                            intent.setClass(AuthenticationActivity.this, WebviewActivity.class);
                            intent.putExtra("url", ConstDefine.HttpAdressH5+"/index.html#/memberFrom");
                            intent.putExtra("title", "填写资料");
                            intent.putExtra("AuthenticationInfo",info);
                            startActivity(intent);
                            finish();
                        }else {
                            ConstDefine.userInfo = value.getData();
                            SpUtils.putUserInfo(AuthenticationActivity.this, value.getData());
                            if (value.getData().getIsactive().equals("1")) {
                                showSnackBar("身份证重复，不能继续申请");
                            }else {
                                Intent intent = new Intent();
                                intent.setClass(AuthenticationActivity.this, PayActivity.class);
                                startActivity(intent);
                                finish();
                            }
                        }
                    }
                });
    }
    @Override
    public int getPermissionsRequestCode() {
        return 999;
    }

    @Override
    public String[] getPermissions() {
        return new String[]{
                Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.READ_EXTERNAL_STORAGE,
                Manifest.permission.CAMERA
        };
    }

    @Override
    public void requestPermissionsSuccess() {
        EasyPhotos.createAlbum(this, true, false, GlideEngine.getInstance())
                .setFileProviderAuthority("com.tjzhxx.union.FileProvider")
                .setCount(1)
                .setPuzzleMenu(false)
                .setCleanMenu(false)
                .start(new SelectCallback() {
                    @Override
                    public void onResult(ArrayList<Photo> photos, boolean isOriginal) {
                        if (isPositive) {
                            Glide.with(mContext)
                                    .load(photos.get(0).path)
                                    .error(R.mipmap.loading)
                                    .placeholder(R.mipmap.loading)
                                    .into(positive);
                        } else {
                            Glide.with(mContext)
                                    .load(photos.get(0).path)
                                    .error(R.mipmap.loading)
                                    .placeholder(R.mipmap.loading)
                                    .into(reverse);
                        }
                        String compressPath = FileUtils.getCompressFilePath(AuthenticationActivity.this) + "/" + photos.get(0).name;
                        new Thread(new Runnable() {
                            @Override
                            public void run() {
                                if (photos.get(0).size > 2*1024) {
                                    File file = new File(photos.get(0).path);
                                    ImageUtils.compressBmp(AuthenticationActivity.this, file, compressPath, 2 * 1024);
                                    runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                            uploadImage(compressPath);
                                        }
                                    });
                                }else {
                                    uploadImage(photos.get(0).path);
                                }

                            }
                        }).start();

                    }

                    @Override
                    public void onCancel() {
                    }
                });
    }

    @Override
    public void requestPermissionsFail() {
        showSnackBar("权限被拒绝");
    }
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
                                           @NonNull int[]
                                                   grantResults) {
        if (mPermissionHelper.requestPermissionsResult(requestCode, permissions, grantResults)) {
            //权限请求结果，并已经处理了该回调
            return;
        }
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }
}
