package com.dskj.trustlend;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.ComponentName;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;

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

import com.azhon.basic.base.BaseActivity;
import com.bumptech.glide.Glide;
import com.dskj.trustlend.api.Api;
import com.dskj.trustlend.api.BaseObserver;
import com.dskj.trustlend.api.Result;
import com.dskj.trustlend.bean.UserBean;
import com.dskj.trustlend.databinding.ActivityEditUserBinding;
import com.dskj.trustlend.home.MainViewModel;
import com.dskj.trustlend.utils.GsonUtils;
import com.dskj.trustlend.utils.LogUtils;
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.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

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

public class EditUserActivity extends BaseActivity<MainViewModel, ActivityEditUserBinding> {
    int isRenXiang = 0;
    private RxPermissions rxPermissions;
    public static final int REQUEST_CODE_CHOOSE = 0x124;
    public static final int PHOTO_RESOULT = 0x125;

    private Uri imageUri;
    private String imageUriString = "";
    private String imageUriStringNet = "";
    UserBean userBean = null;


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

    @SuppressLint("WrongConstant")
    @Override
    protected void initView() {
        rxPermissions = new RxPermissions(this);
//        setStatusBarColorW(this, R.color.white, false);
        dataBinding.backIv.setOnClickListener(v -> onBackPressed());

        dataBinding.userIvRy.setOnClickListener(view -> {
            isRenXiang = 0;
            toOpenFile();
        });
        userBean = InitApp.getUserBean();
        changeUserInfo(userBean);


        dataBinding.loginBt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(TextUtils.isEmpty(imageUriString)){
                    toSumbit();
                }else{
//                    if(cropFile!=null){
//                        uploadSigin(cropFile);
//                    }else {
                        uploadSigin(new File(imageUriString));
//                    }
                }
            }
        });

        getUserInfo();

    }

    @Override
    public void onBackPressed() {
        setResult(RESULT_OK);
        super.onBackPressed();
    }

    private void changeUserInfo(UserBean userBean) {
        dataBinding.titleTv2.setText(userBean.getFull_name() + "");
        dataBinding.phoneTv.setText("" + userBean.getPhone());

        if(!TextUtils.isEmpty(userBean.getEmail())){
            dataBinding.emailEt.setText(userBean.getEmail());
        }
        Glide.with(EditUserActivity.this).load(userBean.getAvatar()+"").error(R.mipmap.default_head_img).error(R.mipmap.default_head_img).into(dataBinding.userHeadIv);

    }

    private void getUserInfo() {
        Api.getInstance().userProfile()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseObserver<Result<UserBean>>() {

                    @Override
                    public void onSuccess(Result<UserBean> feedbackResp) {
                        if(feedbackResp!=null&&feedbackResp.data!=null) {
//                            userBean = feedbackResp.data.get(0);
//                            InitApp.saveString("user_bean", GsonUtils.beanToJSONString(feedbackResp.data.get(0)));

                            userBean.setAvatar(feedbackResp.data.getAvatar());
                            userBean.setEmail(feedbackResp.data.getEmail());
                            InitApp.saveString("user_bean", GsonUtils.beanToJSONString(userBean));
//                            InitApp.setUserToken(feedbackResp.data.get(0).getAuth());
                            changeUserInfo(feedbackResp.data);
                        }
                    }

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

                    }
                });
    }


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


    /**
     * 上传单图片
     *
     * @param
     */
    public void uploadSigin(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.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) {
                            imageUriStringNet = feedbackResp.data.get(0);
                            toSumbit();

                        }
                    }

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

    private void toSumbit() {
        Map<String,Object> map = new HashMap<>();
        if(!TextUtils.isEmpty(imageUriStringNet)){
            map.put("avatar",imageUriStringNet);
        }
        map.put("email",dataBinding.emailEt.getText().toString());

        if(!TextUtils.isEmpty(dataBinding.passwordEt.getText().toString())&&!TextUtils.isEmpty(dataBinding.passwordEt1.getText().toString())){
            if(dataBinding.passwordEt.getText().toString().equals(dataBinding.passwordEt1.getText().toString())){
                map.put("password",dataBinding.passwordEt.getText().toString());
            }else{
                ToastUtils.showShort(dataBinding.emailEt,"Password inconsistency");
                return;
            }
        }

        Api.getInstance().userProfilePost(map)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseObserver<Result<UserBean>>() {

                    @Override
                    public void onSuccess(Result<UserBean> feedbackResp) {

                        if(feedbackResp!=null&&feedbackResp.data!=null) {
                            ToastUtils.showShort(dataBinding.loginBt,"Update UserInfo Success");
//                            userBean = feedbackResp.data.get(0);
                            userBean.setAvatar(feedbackResp.data.getAvatar());
                            userBean.setEmail(feedbackResp.data.getEmail());
                            InitApp.saveString("user_bean", GsonUtils.beanToJSONString(userBean));
//                            InitApp.setUserToken(feedbackResp.data.get(0).getAuth());
                            changeUserInfo(feedbackResp.data);
                        }

                    }

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

                    }
                });
    }


    private void toFile(boolean showCanme) {

        Matisse.from(EditUserActivity.this)
                .choose(MimeType.ofImage())
                .countable(true)
                .maxSelectable(1)
                .restrictOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED)
                .thumbnailScale(0.85f)
                .imageEngine(new 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(EditUserActivity.this).load(pathList1.get(i)).into(dataBinding.userHeadIv);
                        imageUri = pathList1.get(i);
                        imageUriString = pathList.get(i);
//                        crop(imageUri);
                    }
                    break;
                }
            }

        }
    }


    @Override
    protected void initData() {

    }

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

    @Override
    protected void showError(Object obj) {

    }
}