package com.cooleshow.teacher.ui.mine;

import android.Manifest;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.core.content.FileProvider;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.cooleshow.base.router.RouterPath;
import com.cooleshow.base.utils.MyFileUtils;
import com.cooleshow.teacher.bean.TeacherUserInfo;
import com.cooleshow.usercenter.helper.UserHelper;
import com.cooleshow.base.ui.activity.BaseMVPActivity;
import com.cooleshow.base.utils.ActivityUtils;
import com.cooleshow.base.utils.FileUtils;
import com.cooleshow.base.utils.GlideUtils;
import com.cooleshow.base.utils.PopupUtil;
import com.cooleshow.base.utils.ToastUtil;
import com.cooleshow.base.utils.ToastUtils;
import com.cooleshow.teacher.R;
import com.cooleshow.teacher.contract.PersonalSettingContract;
import com.cooleshow.teacher.databinding.ActivityPersonalSettingBinding;
import com.cooleshow.teacher.presenter.mine.PersonalSettingPresenter;
import com.cooleshow.usercenter.bean.SetDetailBean;
import com.tbruyelle.rxpermissions3.RxPermissions;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;

import io.rong.imkit.utils.StatusBarUtil;

/**
 * 创建日期：2022/5/16 16:07
 *
 * @author Ryan
 * 类说明：
 */
@Route(path = RouterPath.MineCenter.MINE_PERSONAL_SETTING)
public class PersonalSettingActivity extends BaseMVPActivity<ActivityPersonalSettingBinding, PersonalSettingPresenter> implements PersonalSettingContract.PersonalSettingView, View.OnClickListener {
    private TeacherUserInfo mySetDetailBean;
    private final int MODIFY_NICKNAME = 1001;
    private final int MODIFY_PHONE = 1002;
    private final int PERSONAL_CERTIFICATION = 1003;
    private final int REQUEST_CODE_CAMERA = 0x44;
    public final int REQUEST_CODE_LOCAL = 0x19;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        StatusBarUtil.setStatusBarDarkTheme(this, true);

    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.cl_header:
                selectHeader();
                break;
            case R.id.cl_name:
                if (null != mySetDetailBean) {
                    ARouter.getInstance().build(RouterPath.MineCenter.MINE_MODIFY_NICKNAME)
                            .withString("userName", mySetDetailBean.username)
                            .navigation(this, MODIFY_NICKNAME);
                }
                break;
            case R.id.cl_sex:
                modifySex();
                break;
            case R.id.cl_phone:
                ARouter.getInstance().build(RouterPath.MineCenter.MINE_CHECK_MODIFY_PHONENUM)
                        .navigation(this, MODIFY_PHONE);
                break;
            case R.id.cl_modify_psd:
                ARouter.getInstance().build(RouterPath.MineCenter.MINE_MODIFY_PASSWORD)
                        .withString("phoneNum", UserHelper.getUserPhone())
                        .navigation();
                break;
            case R.id.cl_certification:
                if (viewBinding.tvCertificationStatus.getText().equals("未认证")) {
                    ARouter.getInstance().build(RouterPath.MineCenter.MINE_PERSONAL_CERTIFICATION)
                            .navigation(this, PERSONAL_CERTIFICATION);
                }
                break;

        }
    }

    private void modifySex() {
        PopupUtil.showInBottom(this, R.layout.pop_modify_sex, (view, popupWindow) -> {
            TextView tv_boy = view.findViewById(R.id.tv_boy);
            TextView tv_girl = view.findViewById(R.id.tv_girl);
            TextView tv_cancel = view.findViewById(R.id.tv_cancel);
            tv_boy.setOnClickListener(view13 -> {
                JSONObject jsonObject = new JSONObject();
                try {
                    jsonObject.put("gender", 1);
                } catch (JSONException e) {
                    e.printStackTrace();
                }

                popupWindow.dismiss();
                presenter.submitSetDetail(jsonObject.toString());
            });
            tv_girl.setOnClickListener(view12 -> {
                JSONObject jsonObject = new JSONObject();
                try {
                    jsonObject.put("gender", 0);
                } catch (JSONException e) {
                    e.printStackTrace();
                }

                popupWindow.dismiss();
                presenter.submitSetDetail(jsonObject.toString());
            });
            tv_cancel.setOnClickListener(view1 -> popupWindow.dismiss());

        });

    }

    private void selectHeader() {
        PopupUtil.showInBottom(this, R.layout.pop_modify_header, (view, popupWindow) -> {
            TextView tv_camera = view.findViewById(R.id.tv_camera);
            TextView tv_album = view.findViewById(R.id.tv_album);
            TextView tv_cancel = view.findViewById(R.id.tv_cancel);
            tv_camera.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    toCamera();
                    popupWindow.dismiss();
                }
            });
            tv_album.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    toAlbum();
                    popupWindow.dismiss();
                }
            });
            tv_cancel.setOnClickListener(view1 -> popupWindow.dismiss());
        });
    }

    private void toCamera() {
        new RxPermissions(this)
                .request(Manifest.permission.CAMERA,
                        Manifest.permission.READ_EXTERNAL_STORAGE,
                        Manifest.permission.WRITE_EXTERNAL_STORAGE)
                .subscribe(granted -> {
                    if (granted) {
                      /*  Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                        File file = new File(imagePath);
                        Uri imageUri = Uri.fromFile(file);
                        intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
                        Log.e("asdfasdfasdfadfs", "111111" );
                        ActivityUtils.startActivityForResult(this, intent, REQUEST_CODE_CAMERA);*/
                        imagePath = Environment.getExternalStorageDirectory().getPath() + "/DCIM/Camera/" + System.currentTimeMillis() + ".jpg";
                        requestCamera(imagePath);
                    } else {
                        ToastUtil.getInstance().show(this, "请选择存储和相机权限！");
                    }
                });
    }

    private void requestCamera(String filePath) {
        File outputImage = new File(filePath);
                /*
                创建一个File文件对象，用于存放摄像头拍下的图片，我们把这个图片命名为output_image.jpg
                并把它存放在应用关联缓存目录下，调用getExternalCacheDir()可以得到这个目录，为什么要
                用关联缓存目录呢？由于android6.0开始，读写sd卡列为了危险权限，使用的时候必须要有权限，
                应用关联目录则可以跳过这一步
                 */
        try//判断图片是否存在，存在则删除在创建，不存在则直接创建
        {
            if (!outputImage.getParentFile().exists()) {
                outputImage.getParentFile().mkdirs();
            }
            if (outputImage.exists()) {
                outputImage.delete();
            }

            outputImage.createNewFile();
            Uri imageUri;
            if (Build.VERSION.SDK_INT >= 24) {
                imageUri = FileProvider.getUriForFile(this,
                        "com.cooleshow.teacher.fileprovider", outputImage);
            } else {
                imageUri = Uri.fromFile(outputImage);
            }
            //使用隐示的Intent，系统会找到与它对应的活动，即调用摄像头，并把它存储
            Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
            intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
            ActivityUtils.startActivityForResult(this, intent, REQUEST_CODE_CAMERA);
            //调用会返回结果的开启方式，返回成功的话，则把它显示出来
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    private String imagePath = null;//当前图片的路径


    private void toAlbum() {
        new RxPermissions(this)
                .request(Manifest.permission.CAMERA,
                        Manifest.permission.READ_EXTERNAL_STORAGE,
                        Manifest.permission.WRITE_EXTERNAL_STORAGE)
                .subscribe(granted -> {
                    if (granted) {
                        Intent intent;
                        if (Build.VERSION.SDK_INT < 19) {
                            intent = new Intent(Intent.ACTION_GET_CONTENT);
                            intent.setType("image/*");
                        } else {
                            intent = new Intent(Intent.ACTION_PICK,
                                    android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                        }
                        ActivityUtils.startActivityForResult(this, intent, REQUEST_CODE_LOCAL);
                    } else {
                        ToastUtil.getInstance().show(this, "请选择存储和相机权限！");
                    }
                });
    }


    @Override
    protected void initView() {
        initMidTitleToolBar(viewBinding.toolbarInclude.toolbar, "设置");
        viewBinding.clHeader.setOnClickListener(this);
        viewBinding.clName.setOnClickListener(this);
        viewBinding.clSex.setOnClickListener(this);
        viewBinding.clPhone.setOnClickListener(this);
        viewBinding.clModifyPsd.setOnClickListener(this);
        viewBinding.clCertification.setOnClickListener(this);
    }

    @Override
    public void initData() {
        super.initData();
    }

    @Override
    protected ActivityPersonalSettingBinding getLayoutView() {
        return ActivityPersonalSettingBinding.inflate(getLayoutInflater());
    }

    @Override
    protected PersonalSettingPresenter createPresenter() {
        return new PersonalSettingPresenter();
    }

    @Override
    public void getSetDetailSuccess(TeacherUserInfo setDetailBean) {
        mySetDetailBean = setDetailBean;
        GlideUtils.INSTANCE.loadImage(this, setDetailBean.heardUrl, viewBinding.imHeader, R.drawable.icon_teacher_default_head);
        viewBinding.tvNickname.setText(setDetailBean.username);
        if (!TextUtils.isEmpty(setDetailBean.gender) && setDetailBean.gender.equals("0")) {
            //女
            viewBinding.tvSex.setText("女");
        } else {
            //男
            viewBinding.tvSex.setText("男");
        }
        viewBinding.tvPhone.setText(UserHelper.getUserPhone());
        if (setDetailBean.isReal == 1) {
            //是
            viewBinding.tvCertificationStatus.setText("已认证");
        } else {
            //否
            viewBinding.tvCertificationStatus.setText("未认证");
        }
    }

    @Override
    public void submitSetDetailSuccess(SetDetailBean setDetailBean) {
        if (setDetailBean.gender == 0) {
            //女
            viewBinding.tvSex.setText("女");
        } else {
            //男
            viewBinding.tvSex.setText("男");
        }
        ToastUtil.getInstance().showShort("修改成功");
        GlideUtils.INSTANCE.loadImage(this, setDetailBean.avatar, viewBinding.imHeader, R.drawable.icon_teacher_default_head);


    }

    @Override
    protected void onResume() {
        super.onResume();
        presenter.getSetDetail();

    }

    @Override
    public void upLoadImageSuccess(String url) {
        hideLoading();
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("avatar", url);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        presenter.submitSetDetail(jsonObject.toString());
    }

    @Override
    public void upLoadImageFailure() {
        hideLoading();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == MODIFY_NICKNAME) {
                String userName = data.getStringExtra("userName");
                mySetDetailBean.username = userName;
                viewBinding.tvNickname.setText(userName);
            } else if (requestCode == MODIFY_PHONE) {
                String newPhoneNum = data.getStringExtra("newPhoneNum");
                mySetDetailBean.phone = newPhoneNum;
                viewBinding.tvPhone.setText(newPhoneNum);
            } else if (requestCode == PERSONAL_CERTIFICATION) {
                viewBinding.tvCertificationStatus.setText("已认证");
            } else if (requestCode == REQUEST_CODE_CAMERA) {
                if (!TextUtils.isEmpty(imagePath)) {
                    boolean isImg = MyFileUtils.isImg(imagePath);
                    if (isImg) {
                        presenter.upLoadImage(PersonalSettingActivity.this, imagePath);
                    } else {
                        ToastUtil.getInstance().showShort("请选择图片类型文件");
                    }
                }

            } else if (requestCode == REQUEST_CODE_LOCAL) {
                if (data != null) {
                    Uri selectedImage = data.getData();
                    if (selectedImage != null) {
                        String v_path = FileUtils.getFilePathForN(selectedImage, PersonalSettingActivity.this);
                        boolean isImg = MyFileUtils.isImg(v_path);
                        if (isImg) {
                            presenter.upLoadImage(PersonalSettingActivity.this, v_path);
                        } else {
                            ToastUtil.getInstance().showShort("请选择图片类型文件");
                        }
                    }
                }
            }
        }
    }
}
