package cn.dankal.yunlaboratory.ui.fragment;

import android.Manifest;
import android.app.Activity;
import android.content.ContentValues;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.icu.lang.UScript;
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.ImageView;
import android.widget.TextView;

import androidx.core.content.ContextCompat;
import androidx.core.content.FileProvider;
import androidx.core.os.EnvironmentCompat;

import com.tbruyelle.rxpermissions2.RxPermissions;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;

import api.UserServiceFactory;
import butterknife.BindView;
import butterknife.OnClick;
import cn.dankal.basiclib.DKUserManager;
import cn.dankal.basiclib.base.fragment.BaseFragment;
import cn.dankal.basiclib.bus.InfoChange;
import cn.dankal.basiclib.eventbus.AppBus;
import cn.dankal.basiclib.eventbus.Subscribe;
import cn.dankal.basiclib.model.BaseModel;
import cn.dankal.basiclib.model.UserInfoBody;
import cn.dankal.basiclib.model.UserModel;
import cn.dankal.basiclib.rx.MapFunc;
import cn.dankal.basiclib.rx.NormalSubscriber;
import cn.dankal.basiclib.util.FileUtil;
import cn.dankal.basiclib.util.GlideUtils;
import cn.dankal.basiclib.util.Logger;
import cn.dankal.basiclib.util.ToastUtils;
import cn.dankal.yunlaboratory.R;
import cn.dankal.yunlaboratory.ui.activity.ChangeNicknameActivity;
import cn.dankal.yunlaboratory.ui.activity.LoginActivity;
import cn.dankal.yunlaboratory.ui.dialog.ChooseAvatarDialog;
import cn.dankal.yunlaboratory.ui.dialog.RenderDialog;
import cn.dankal.yunlaboratory.ui.util.FileUtils;
import cn.dankal.yunlaboratory.ui.widget.MainButton;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;

public class PersonFragment extends BaseFragment implements View.OnClickListener {

    public static final int RC_CHOOSE_PHOTO = 1;
    public static final int CAMERA_REQUEST_CODE = 2;

    @BindView(R.id.iv_onback)
    ImageView ivOnback;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.iv_avatar)
    ImageView ivAvatar;
    @BindView(R.id.tv_no)
    TextView tvNo;
    @BindView(R.id.tv_nickname)
    TextView tvNickname;
    @BindView(R.id.tv_sex)
    TextView tvSex;
    @BindView(R.id.btn_exit)
    MainButton btnExit;
    private ChooseAvatarDialog chooseAvatarDialog;
    private RenderDialog renderDialog;
    //用于保存拍照图片的uri
    private Uri mCameraUri;

    // 用于保存图片的文件路径，Android 10以下使用图片路径访问图片
    private String mCameraImagePath;

    // 是否是Android 10以上手机
    private boolean isAndroidQ = Build.VERSION.SDK_INT > Build.VERSION_CODES.P;

    private File tempPhotoFile;

    public static PersonFragment getInstance() {
        PersonFragment personFragment = new PersonFragment();
        return personFragment;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_person;
    }

    @Override
    protected void initComponents() {
        AppBus.getInstance().register(this);
        chooseAvatarDialog = new ChooseAvatarDialog(getContext());
        chooseAvatarDialog.setViewClick(R.id.tv_camera, this);
        chooseAvatarDialog.setViewClick(R.id.tv_album, this);

        renderDialog = new RenderDialog(getContext());

        btnExit.setEnabled(true);
        tvTitle.setText("个人中心");

        if (DKUserManager.getUserInfo() != null) {
            UserModel userModel = DKUserManager.getUserInfo();

            tvNickname.setText(userModel.getName());
            tvNo.setText(userModel.getEmployee_id());

            tvSex.setText(userModel.getRealSex());

            GlideUtils.loadCircleImage(getContext(), userModel.getAvatar(), ivAvatar);
        }

        renderDialog.setViewClick(R.id.tv_positive, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                renderDialog.dismiss();
                updateSex(renderDialog.getCurrentSex());
            }
        });
    }


    @Subscribe
    public void onUserInfoChange(InfoChange change) {
        if (DKUserManager.getUserInfo() != null) {
            UserModel userModel = DKUserManager.getUserInfo();

            tvNickname.setText(userModel.getName());
            tvNo.setText(userModel.getEmployee_id());

            tvSex.setText(userModel.getRealSex());

            GlideUtils.loadCircleImage(getContext(), userModel.getAvatar(), ivAvatar);
        }
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_camera:

                openCamera();
                chooseAvatarDialog.dismiss();
                break;
            case R.id.tv_album:

                Intent intentToPickPic = new Intent(Intent.ACTION_PICK, null);
                intentToPickPic.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
                startActivityForResult(intentToPickPic, RC_CHOOSE_PHOTO);
                chooseAvatarDialog.dismiss();
                break;
        }
    }


    /**
     * 调起相机拍照
     */
    private void openCamera() {
        if (ContextCompat.checkSelfPermission(getContext(), Manifest.permission.CAMERA)
                != PackageManager.PERMISSION_GRANTED
                || ContextCompat.checkSelfPermission(getContext(), Manifest.permission.WRITE_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {
            requestPermissions(new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE}, CAMERA_REQUEST_CODE);
            return;
        }

        Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

        if (cameraIntent.resolveActivity(getContext().getPackageManager()) != null) {
            tempPhotoFile = new File(FileUtils.createRootPath(getContext()) + "/" + System.currentTimeMillis() + ".jpg");

            FileUtils.createFile(tempPhotoFile);

            Uri uri = FileProvider.getUriForFile(getContext(),
                     "cn.dankal.yunlaboratory.image_provider", tempPhotoFile);

            List<ResolveInfo> resInfoList = getContext().getPackageManager().queryIntentActivities(cameraIntent, PackageManager.MATCH_DEFAULT_ONLY);
            for (ResolveInfo resolveInfo : resInfoList) {
                String packageName = resolveInfo.activityInfo.packageName;
                getActivity().grantUriPermission(packageName, uri, Intent.FLAG_GRANT_WRITE_URI_PERMISSION | Intent.FLAG_GRANT_READ_URI_PERMISSION);
            }

            cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, uri); //Uri.fromFile(tempFile)
            startActivityForResult(cameraIntent, CAMERA_REQUEST_CODE);
        } else {
            ToastUtils.showLong("打开相机失败");
        }
    }

    /**
     * 创建图片地址uri,用于保存拍照后的照片 Android 10以后使用这种方法
     */
    private Uri createImageUri() {
        String status = Environment.getExternalStorageState();
        // 判断是否有SD卡,优先使用SD卡存储,当没有SD卡时使用手机存储
        if (status.equals(Environment.MEDIA_MOUNTED)) {
            return getContext().getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, new ContentValues());
        } else {
            return getContext().getContentResolver().insert(MediaStore.Images.Media.INTERNAL_CONTENT_URI, new ContentValues());
        }
    }

    /**
     * 创建保存图片的文件
     */
    private File createImageFile() throws IOException {
        String imageName = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(new Date());
        File storageDir = getContext().getExternalFilesDir(Environment.DIRECTORY_PICTURES);
        if (!storageDir.exists()) {
            storageDir.mkdir();
        }
        File tempFile = new File(storageDir, imageName);
        if (!Environment.MEDIA_MOUNTED.equals(EnvironmentCompat.getStorageState(tempFile))) {
            return null;
        }
        return tempFile;
    }

    @OnClick({R.id.iv_avatar, R.id.linear_nickname, R.id.linear_sex, R.id.btn_exit})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_avatar:
                new RxPermissions(getActivity()).request(Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA).subscribe(new Consumer<Boolean>() {
                    @Override
                    public void accept(Boolean aBoolean) throws Exception {
                        if (aBoolean) {
                            chooseAvatarDialog.show();
                        }
                    }
                });

                break;
            case R.id.linear_nickname:
                Intent intent = new Intent(getContext(), ChangeNicknameActivity.class);
                startActivity(intent);
                break;
            case R.id.linear_sex:
                renderDialog.show();
                break;
            case R.id.btn_exit:
                DKUserManager.resetUserInfo();
                DKUserManager.resetToken();
                Intent intent2=new Intent(getContext(), LoginActivity.class);
                startActivity(intent2);
                getActivity().finish();
                break;
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == Activity.RESULT_OK) {

            if (requestCode == RC_CHOOSE_PHOTO) {
                Uri uri = data.getData();

                updateAvatar(FileUtil.getRealFilePath(getContext(), uri));
            } else if (requestCode == CAMERA_REQUEST_CODE) {

                if (tempPhotoFile != null) {
                    updateAvatar(tempPhotoFile.getAbsolutePath());
                }
            }
        }else {
            if (tempPhotoFile != null && tempPhotoFile.exists()) {
                tempPhotoFile.delete();
            }
        }
    }

    public void updateSex(int sex) {


        UserServiceFactory.updateSex("sex", sex).map(new MapFunc<>()).subscribe(new NormalSubscriber<BaseModel>() {
            @Override
            public void onSubscribe(Disposable d) {
            showLoadingDialog();
            }

            @Override
            public void onNext(BaseModel stringBaseModel) {

                UserModel userModel = DKUserManager.getUserInfo();

                userModel.setSex(sex);
                DKUserManager.updateUserInfo(userModel);

                tvSex.setText(userModel.getRealSex());

            }

            @Override
            public void onComplete() {
                super.onComplete();
                dismissLoadingDialog();
            }
        });

    }



    /**
     * 更新头像
     */
    private void updateAvatar(String path) {

        if (!TextUtils.isEmpty(path)) {


            HashMap<String,RequestBody> map=new HashMap<>();

            RequestBody updateTypeBody=RequestBody.create(MediaType.parse("application/json"),"avatar");
            map.put("update_type",updateTypeBody);

            File file = new File(path);

            RequestBody fileRQ = RequestBody.create(MediaType.parse("image/png"), file);
            MultipartBody.Part part = MultipartBody.Part.createFormData("file", file.getName(), fileRQ);

//            map.put("file",fileRQ);

            UserServiceFactory.updateInfo(map,part).map(new MapFunc<>()).subscribe(new NormalSubscriber<BaseModel<UserModel>>() {
                @Override
                public void onSubscribe(Disposable d) {
                    showLoadingDialog();
                }

                @Override
                public void onNext(BaseModel<UserModel> stringBaseModel) {
                    if (stringBaseModel.getData()!=null){
                        String avatar = stringBaseModel.getData().getAvatar();
                        UserModel userModel = DKUserManager.getUserInfo();

                        userModel.setAvatar(avatar);
                        DKUserManager.updateUserInfo(userModel);
                        GlideUtils.loadCircleImage(getContext(), avatar, ivAvatar);
                    }

                }
                @Override
                public void onComplete() {
                    super.onComplete();
                    dismissLoadingDialog();
                }
            });

        }
    }




    @Override
    public void onDestroy() {
        AppBus.getInstance().unregister(this);
        super.onDestroy();
    }
}
