package com.yidianling.user.ui;

import android.Manifest;
import android.app.Dialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.hardware.Camera;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.lzy.imagepicker.ImagePicker;
import com.lzy.imagepicker.bean.ImageItem;
import com.lzy.imagepicker.ui.ImageGridActivity;
import com.lzy.imagepicker.view.CropImageView;
import com.tbruyelle.rxpermissions2.RxPermissions;
import com.ydl.webview.RefreshWebEvent;
import com.ydl.ydl_image.module.GlideApp;
import com.ydl.ydlcommon.base.BaseActivity;
import com.ydl.ydlcommon.bean.StatusBarOptions;
import com.ydl.ydlcommon.data.http.RxUtils;
import com.ydl.ydlcommon.data.http.ThrowableConsumer;
import com.ydl.ydlcommon.utils.ActivityManager;
import com.ydl.ydlcommon.utils.log.LogHelper;
import com.ydl.ydlcommon.utils.remind.ToastHelper;
import com.ydl.ydlcommon.view.CircleImageView;
import com.ydl.ydlcommon.view.ListNoCancelDialog;
import com.ydl.ydlcommon.view.RoundCornerButton;
import com.ydl.ydlcommon.view.TitleBar;
import com.ydl.ydlcommon.view.dialog.CommonDialog;
import com.ydl.ydlcommon.view.dialog.ThreeLinesDialog;
import com.yidianling.common.tools.RxFileTool;
import com.yidianling.common.tools.RxImageTool;
import com.yidianling.user.GlideImageLoader;
import com.yidianling.user.LoginHelper;
import com.yidianling.user.R;
import com.yidianling.user.UserConstants;
import com.yidianling.user.UserHelper;
import com.yidianling.user.api.bean.UserResponseBean;
import com.yidianling.user.http.UserHttp;
import com.yidianling.user.http.UserHttpImpl;
import com.yidianling.user.http.request.HeadParam;
import com.yidianling.user.http.request.UserInfoParam;
import com.yidianling.user.route.UserIn;

import org.jetbrains.annotations.NotNull;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import de.greenrobot.event.EventBus;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

/**
 * 完善信息
 * Created by softrice on 15/12/9.
 */
public class FillInfoActivity extends BaseActivity implements View.OnClickListener {

    String icon;
    String name;
    String sex;
    int type = 0;//0 normal 1 第三方登录模式


    boolean isSelected;//是否上传了头像
    TitleBar tb_title;
    CircleImageView sdv_head;
    TextView tv_sex;
    EditText et_nick;
    RoundCornerButton rcb_submit;

    String head = "";

    private int finishNum = 0;

    private int gender = -1;
    String path;
    private Uri imgUri;

//    FileUtils fileUtils;
    private String head_dir;//目录
    private String head_path;//路径
    File head_filec;

    private RxPermissions rxPermissions;

    private boolean isFromSplash;
    private boolean isRegisterFromRedPacket;

    @Override
    protected int layoutResId() {
        return R.layout.user_activity_fill_info;
    }

    @NotNull
    @Override
    public StatusBarOptions getStatusViewOptions() {
        return new StatusBarOptions(true,true);
    }

    @Override
    protected void initDataAndEvent() {
        tb_title = findViewById(R.id.tb_title);
        sdv_head = findViewById(R.id.sdv_head);
        tv_sex = findViewById(R.id.tv_sex);
        et_nick = findViewById(R.id.et_nick);
        rcb_submit = findViewById(R.id.rcb_submit);
        sdv_head.setOnClickListener(this);
        tv_sex.setOnClickListener(this);
        rcb_submit.setOnClickListener(this);
        icon = getIntent().getStringExtra("icon");
        name = getIntent().getStringExtra("name");
        sex = getIntent().getStringExtra("sex");
        type = getIntent().getIntExtra("type", 0);
        isFromSplash = getIntent().getBooleanExtra("isFromSplash", false);
        isRegisterFromRedPacket = getIntent().getBooleanExtra(UserConstants.IS_REGISTER_FROM_PACKET, false);
        init();
    }


    void init() {
        rxPermissions = new RxPermissions(this);
        head_dir = Environment.getExternalStorageDirectory().getAbsolutePath() + "/yidianling/img/head_img/";
        ImagePicker imagePicker = ImagePicker.getInstance();
        imagePicker.setImageLoader(new GlideImageLoader());   //设置图片加载器
        imagePicker.setShowCamera(true);  //显示拍照按钮
        imagePicker.setCrop(true);        //允许裁剪（单选才有效）
        imagePicker.setMultiMode(false);
        imagePicker.setSaveRectangle(true); //是否按矩形区域保存
        imagePicker.setSelectLimit(1);    //选中数量限制
        imagePicker.setStyle(CropImageView.Style.RECTANGLE);  //裁剪框的形状
        imagePicker.setFocusWidth(800);   //裁剪框的宽度。单位像素（圆形自动取宽高最小值）
        imagePicker.setFocusHeight(800);  //裁剪框的高度。单位像素（圆形自动取宽高最小值）
        imagePicker.setOutPutX(300);//保存文件的宽度。单位像素
        imagePicker.setOutPutY(300);//保存文件的高度。单位像素
        if (!TextUtils.isEmpty(icon)) {
            GlideApp.with(FillInfoActivity.this)
                    .load(icon)
                    .fitCenter()
                    .error(R.drawable.user_regist_photo)
                    .into(sdv_head);
        }

        if (!TextUtils.isEmpty(name)) {
            et_nick.setText(name);
        }

        if (!TextUtils.isEmpty(sex)) {
            if (sex.equals("1")) {
                tv_sex.setText("男");
                gender = 1;
            } else {
                tv_sex.setText("女");
                gender = 2;
            }

        }
        tb_title.setOnLeftTextClick((view, isActive) -> {
            showExitDialog();
        });

    }

    @Override
    public void onBackPressed() {
        showExitDialog();
    }

    private void showExitDialog() {
        CommonDialog.create(this)
                .setTitle("提示")
                .setMessage("确定退出完善资料？")
                .setLeftOnclick("退出", (view1) -> {
                    if (isFromSplash) {
                        UserIn.INSTANCE.mainIntent(this);
                        ActivityManager.Companion.finishActivity(InputPhoneActivity.class);
                        ActivityManager.Companion.finishActivity(LoginActivity.class);
                        finish();
                    } else if (isRegisterFromRedPacket) {
                        EventBus.getDefault().post(new RefreshWebEvent());
                        UserIn.INSTANCE.mainIntent(this);
                        finish();
                    } else {
                        EventBus.getDefault().post(new RefreshWebEvent());
                        ActivityManager.Companion.finishActivity(InputPhoneActivity.class);
                        ActivityManager.Companion.finishActivity(LoginActivity.class);
                        finish();
                    }
                    ToastHelper.Companion.show(R.string.platform_register_success);
                    LogHelper.Companion.getInstance().writeLogSync("完善资料页退出");
                })
                .setRightClick("继续", (view1 -> {

                }))
                .show();
    }

    private static final int REQUEST_CODE_FILL_CAMER_HEAD = 21012;
    private static final int IMAGE_PICKER=32001;

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.sdv_head) {
            rxPermissions.request(Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                    .subscribe(granted -> {
                        if (granted) {
                            ThreeLinesDialog.Builder builder1 = new ThreeLinesDialog.Builder(FillInfoActivity.this);
                            builder1.setTitle("相机");
                            builder1.setMessage("相册中选择");
                            builder1.setbottom("取消");
                            builder1.setFirstButton("相机", (dialog, which) -> {
                                head_path = head_dir + System.currentTimeMillis() + "hand_carmer.jpg";
                                showCameraAction(REQUEST_CODE_FILL_CAMER_HEAD, head_path);
                                dialog.dismiss();
                            });
                            builder1.setSecondButton("相册中选择", (dialog, which) -> {
                                Intent intent = new Intent(FillInfoActivity.this, ImageGridActivity.class);
                                startActivityForResult(intent, IMAGE_PICKER);
                                dialog.dismiss();
                            });
                            builder1.setThridButton("取消", (dialog, which) -> dialog.dismiss());
                            builder1.create().show();
                        } else {
                            ToastHelper.Companion.show("缺少使用相机和读取存储权限，无法获取图片");
                        }
                    });
        } else if (id == R.id.tv_sex) {
            List<String> name = new ArrayList<String>();
            name.add("男");
            name.add("女");
            ListNoCancelDialog.Builder builders = new ListNoCancelDialog.Builder(FillInfoActivity.this, name, 0);
            builders.SetOnItemClickLister(new ListNoCancelDialog.Builder.OnItemClickLister() {
                @Override
                public void onItemClick(Dialog dialog, View view, int position) {
                    switch (position) {
                        case 0:
                            tv_sex.setText("男");
                            gender = 1;
                            dialog.dismiss();
                            break;
                        case 1:
                            tv_sex.setText("女");
                            gender = 2;
                            dialog.dismiss();
                            break;
                    }
                }

                @Override
                public void onItemLongClick(Dialog dialog, View view, int position) {

                }
            });
            builders.create().show();
        } else if (id == R.id.rcb_submit) {
            if (judge()) {
                setInfo();
            }
        }

    }


    /**
     * 调用系统拍照
     */
    private void showCameraAction(int type_code, String file_path) {

        File file_dir = new File(head_dir);
        if (file_dir.exists()) {
            RxFileTool.deleteFilesInDir(file_dir);
        }
        file_dir.mkdirs();
        head_filec = new File(file_path);
        final Intent intent = new Intent();
        final Intent intent_camera = getPackageManager()
                .getLaunchIntentForPackage("com.android.camera");
        if (intent_camera != null) {
            intent.setPackage("com.android.camera");
        }
        intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
            intent.putExtra("android.intent.extras.CAMERA_FACING", Camera.CameraInfo.CAMERA_FACING_FRONT); // 调用前置摄像头
            intent.putExtra("autofocus", true); // 自动对焦
            intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(head_filec));
            intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
            startActivityForResult(intent, type_code);
        } else {
            try {
                head_filec.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }

            Uri uri = RxFileTool.getImageContentUri(FillInfoActivity.this, new File(file_path));
            intent.putExtra("android.intent.extras.CAMERA_FACING", Camera.CameraInfo.CAMERA_FACING_FRONT); // 调用前置摄像头
            intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
            intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
            intent.putExtra("autofocus", true); // 自动对焦
            startActivityForResult(intent, type_code);
        }

    }


    private void setInfo() {
        showProgressDialog("");
        updateInfo("gender", gender + "");
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (LoginHelper.isRegister) {
            UserIn.INSTANCE.setChattingAccountAll();
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (LoginHelper.isRegister) {
            UserIn.INSTANCE.setChattingAccountNone();
        }
    }

    private void updateInfo(String changType, String value) {
        UserHttp userHttp = UserHttpImpl.Companion.getInstance();
        userHttp.setUserInfo(new UserInfoParam(changType, value))
                .subscribeOn(Schedulers.io())
                .compose(RxUtils.resultData())
                .flatMap(o->{
                    return userHttp.setUserInfo(new UserInfoParam("nickName", et_nick.getText().toString()))
                            .compose(RxUtils.resultData());
                })
                .observeOn(AndroidSchedulers.mainThread())
                .doAfterTerminate(this::dismissProgressDialog)
                .subscribe(o -> {
                    UserResponseBean userInfo = UserHelper.INSTANCE.getUserInfo();
                    if (userInfo != null) {
                        userInfo.getUserInfo().setHead(head);
                        userInfo.getUserInfo().setGender(gender);
                        userInfo.getUserInfo().setNick_name(et_nick.getText().toString());
                    }
                    if (isFromSplash) {
                        UserIn.INSTANCE.mainIntent(this);
                        ActivityManager.Companion.finishActivity(InputPhoneActivity.class);
                        ActivityManager.Companion.finishActivity(LoginActivity.class);
                        finish();
                    } else if (isRegisterFromRedPacket) {
                        EventBus.getDefault().post(new RefreshWebEvent());
                        UserIn.INSTANCE.mainIntent(this);
                        finish();
                    } else {
                        EventBus.getDefault().post(new RefreshWebEvent());
                        ActivityManager.Companion.finishActivity(InputPhoneActivity.class);
                        ActivityManager.Companion.finishActivity(LoginActivity.class);
                        finish();
                    }
                    ToastHelper.Companion.show(R.string.platform_register_success);
                    LogHelper.Companion.getInstance().writeLogSync("完善资料成功");

                }, new ThrowableConsumer() {
                    @Override
                    public void accept(@NotNull String msg) {
                        ToastHelper.Companion.show(msg);
                        LogHelper.Companion.getInstance().writeLogSync(String.format("完善资料失败%s", msg));
                    }
                });

    }

    private boolean judge() {
        if (!isSelected && TextUtils.isEmpty(icon)) {
            ToastHelper.Companion.show("选个头像吧");
            return false;
        }
        if (gender == -1) {
            ToastHelper.Companion.show("设置下性别哦");
            return false;
        }
        if (TextUtils.isEmpty(et_nick.getText().toString())) {
            ToastHelper.Companion.show("大侠，请留个名");
            return false;
        }
        if (TextUtils.isEmpty(et_nick.getText().toString())) {
            ToastHelper.Companion.show("昵称最多5个字哦");
            return false;
        }
        return true;
    }

    private static final int REQUEST_CODE_CUT = 21003;

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case REQUEST_CODE_FILL_CAMER_HEAD:
                    imgUri = null;
                    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
                        if (head_filec.exists()) {
                            startPhotoZoom(Uri.fromFile(head_filec));
                        }
                    } else {
                        Uri uri = RxFileTool.getImageContentUri(FillInfoActivity.this, head_filec);
                        if (uri != null) {
                            startPhotoZoom(uri);
                        }

                    }
                    break;
                case REQUEST_CODE_CUT:
                    if (imgUri != null) {
                        String path = RxFileTool.getPathFromUri(this, imgUri);
                        Bitmap bitmap = BitmapFactory.decodeFile(path);
                        bitmap = RxImageTool.compressByQuality(bitmap, 200);
                        RxImageTool.save(bitmap, path, Bitmap.CompressFormat.PNG);
                        File out_file = new File(path);
                        uploadImage(out_file.getAbsolutePath(), 1002);
                        imgUri = null;
                    }
                    break;
            }
        } else if (resultCode == ImagePicker.RESULT_CODE_ITEMS) {
            switch (requestCode) {
                case IMAGE_PICKER:
                    if (data != null) {
                        ArrayList<ImageItem> images = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_RESULT_ITEMS);

                        uploadImage(images.get(0).path, 1002);
                    } else {
                        Toast.makeText(this, "没有数据", Toast.LENGTH_SHORT).show();
                    }
                    break;
            }

        }
    }

    /**
     * 裁剪图片方法实现
     */
    public void startPhotoZoom(Uri uri) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        // 设置裁剪
        intent.putExtra("crop", "true");
        // 图片拉伸，就不会出现黑框了
        intent.putExtra("scaleUpIfNeeded", true);
        //宽高的比例
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        //裁剪图片宽高
        intent.putExtra("outputX", 200);
        intent.putExtra("outputY", 200);
        if (imgUri != null) {
            // 输出路径
            RxFileTool.isFileExists(head_dir);
            imgUri = Uri.fromFile(new File(head_dir + System.currentTimeMillis() + "my_head1.jpg"));
            intent.putExtra(MediaStore.EXTRA_OUTPUT, imgUri);
            intent.putExtra("outputFormat", Bitmap.CompressFormat.PNG.toString());
            // return-data=true传递的为缩略图，小米手机默认传递大图，所以会导致onActivityResult调用失败
            intent.putExtra("return-data", false);
            // 是否需要人脸识别
//        intent.putExtra("noFaceDetection", false);
            startActivityForResult(intent, REQUEST_CODE_CUT);
        } else {
            File bigfile = new File(head_path);
            imgUri = Uri.fromFile(bigfile);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, imgUri);
            intent.putExtra("outputFormat", Bitmap.CompressFormat.PNG.toString());
            // return-data=true传递的为缩略图，小米手机默认传递大图，所以会导致onActivityResult调用失败
            intent.putExtra("return-data", false);
            // 是否需要人脸识别
            intent.putExtra("noFaceDetection", false);
            startActivityForResult(intent, REQUEST_CODE_CUT);
        }

    }

    /**
     * 上传图片
     */
    void uploadImage(final String path, final int requestCode) {
        UserHttp userHttp = UserHttpImpl.Companion.getInstance();
        userHttp.uploadHead(new HeadParam(new File(path)))
                .compose(RxUtils.resultData())
                .observeOn(AndroidSchedulers.mainThread())
                .doOnSubscribe(disposable -> {
                    dismissProgressDialog();
                    GlideApp.with(FillInfoActivity.this).load(R.drawable.user_loading2).into(sdv_head);
                })
                .subscribe(o -> {
                    Map map = (Map) o;
                    String head_url = (String) map.get("url");
                    isSelected = true;
                    GlideApp.with(FillInfoActivity.this)
                            .load(path)
                            .fitCenter()
                            .error(R.drawable.user_regist_photo)
                            .into(sdv_head);
                    head = head_url;
                }, new ThrowableConsumer() {
                    @Override
                    public void accept(@NotNull String msg) {
                        ToastHelper.Companion.show(msg);
                    }
                });

    }

    @Override
    protected void onDestroy() {

        super.onDestroy();
    }
}
