package com.rdiot.yx485;

import static android.view.View.GONE;
import static android.view.View.VISIBLE;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;

import com.bumptech.glide.Glide;
import com.luck.picture.lib.basic.PictureSelector;
import com.luck.picture.lib.config.SelectMimeType;
import com.luck.picture.lib.engine.CompressFileEngine;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.interfaces.OnResultCallbackListener;
import com.luck.picture.lib.utils.SandboxTransformUtils;
import com.rdiot.yx485.bean.PersonBean;
import com.rdiot.yx485.databinding.ActivityPerInfoBinding;
import com.rdiot.yx485.http.Url;
import com.rdiot.yx485.main.MainViewModel;
import com.rdiot.yx485.util.DialogUtils;
import com.rdiot.yx485.util.GlideEngine;
import com.rdiot.yx485.util.IntentUtils;
import com.rdiot.yx485.util.LocalCache;
import com.rdiot.yx485.util.PermissionUtils;

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

import top.zibin.luban.Luban;
import top.zibin.luban.OnNewCompressListener;

public class PerInfoActivity extends BaseActivity {
    private final MainViewModel mViewModel = new MainViewModel();
    private ActivityPerInfoBinding mBinding;
    private String mImageUrl;
    private String mUserName;
    private boolean mChanged = false;
    private PersonBean.UserInfo mUserInfo;

    public static void newIntent(Context context) {
        Intent intent = new Intent(context, PerInfoActivity.class);
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mBinding = ActivityPerInfoBinding.inflate(getLayoutInflater());
        setContentView(mBinding.getRoot());

        initData();
        initView();
    }

    private void initData() {
        mUserInfo = LocalCache.getUserInfo();
        if (mUserInfo == null) {
            onBackPressed();
            return;
        }
        mUserName = mUserInfo.user_name;

        mViewModel.getErrorMessage().observe(this, this::showMessage);
        mViewModel.getUploadInfo().observe(this, uploadInfo -> {
            if (uploadInfo == null) {
                return;
            }

            mImageUrl = uploadInfo.getUrl();
            mChanged = true;
            refreshView();
        });
        mViewModel.getUpdateState().observe(this, success -> {
            if (success) {
                mChanged = false;
                onBackPressed();
            }
        });
        mViewModel.getDeleteAccountState().observe(this, success -> {
            if (success) {
                // 账号注销成功，返回登录页面
                IntentUtils.intentToLogin(this);
//                Intent intent = new Intent(this, LoginWithPwdActivity.class);
//                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
//                startActivity(intent);
//                finish();
            }
        });

        refreshView();
    }

    private void initView() {
        mBinding.layoutTitle.tvTitle.setText("个人资料");
        mBinding.layoutTitle.btnTitleLeft.setOnClickListener(v -> onBackPressed());

        mBinding.headimage.setOnClickListener(v -> {
            if (PermissionUtils.INSTANCE.checkPermissionGranted(this, "")) {
                selectPicture();
            }
        });
        mBinding.username.setOnClickListener(v -> DialogUtils.showInputDialog(this, "修改昵称", mUserName, "请输入昵称", name ->
        {
            mChanged = true;
            mUserName = name;
            refreshView();
        }));
        mBinding.btnSave.setOnClickListener(v -> {
            if (mUserInfo == null) {
                return;
            }

            if (!TextUtils.isEmpty(mUserName)) {
                mUserInfo.user_name = mUserName;
            }

            if (!TextUtils.isEmpty(mImageUrl)) {
                mUserInfo.photo = mImageUrl;
            }

            mViewModel.updateUserInfo(mUserInfo);
        });

        // 修改密码点击事件
        mBinding.layoutResetPassword.setOnClickListener(v -> {
            // 跳转到修改密码页面
            IntentUtils.intentToSetPwd(this, false);
        });

        // 注销账号点击事件
        mBinding.layoutDeleteAccount.setOnClickListener(v -> {
            DialogUtils.showAlertDialog(this, "注销账号", "注销账号后，您的所有数据将被删除且无法恢复。确定要注销账号吗？",
                    (dialog, which) -> {
                        // 确认注销账号
                        mViewModel.deleteAccount();
                    },
                    (dialog, which) -> {
                        // 取消操作
                        dialog.dismiss();
                    });
        });
    }

    private void selectPicture() {
        PictureSelector.create(this)
                .openGallery(SelectMimeType.ofImage())
                .isDisplayCamera(false)
                .setImageEngine(GlideEngine.createGlideEngine())
                .setMaxSelectNum(1)
                .setSandboxFileEngine((context, srcPath, mineType, call) -> {
                    if (call != null) {
                        String sandboxPath = SandboxTransformUtils.copyPathToSandbox(context, srcPath, mineType);
                        call.onCallback(srcPath, sandboxPath);
                    }
                })
                .setCompressEngine((CompressFileEngine) (context, source, call) ->
                        Luban.with(context).load(source).ignoreBy(500)
                                .setCompressListener(new OnNewCompressListener() {
                                    @Override
                                    public void onStart() {

                                    }

                                    @Override
                                    public void onSuccess(String source, File compressFile) {
                                        if (call != null) {
                                            call.onCallback(source, compressFile.getAbsolutePath());
                                        }
                                    }

                                    @Override
                                    public void onError(String source, Throwable e) {
                                        if (call != null) {
                                            call.onCallback(source, null);
                                        }
                                    }
                                }).launch())
                .forResult(new OnResultCallbackListener<LocalMedia>() {
                    @SuppressLint("NotifyDataSetChanged")
                    @Override
                    public void onResult(ArrayList<LocalMedia> result) {
                        if (result.isEmpty()) {
                            return;
                        }

                        mViewModel.uploadFile(result.get(0).getAvailablePath());
                    }

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

    private void refreshView() {
        showUserName();
        showHeaderView();
        mBinding.btnSave.setVisibility(mChanged ? VISIBLE : GONE);
    }

    private void showUserName() {
        if (!TextUtils.isEmpty(mUserName)) {
            mBinding.username.setText(mUserName);
            return;
        }

        if (mUserInfo == null || TextUtils.isEmpty(mUserInfo.user_name)) {
            return;
        }

        mBinding.username.setText(mUserInfo.user_name);
    }

    private void showHeaderView() {
        if (!TextUtils.isEmpty(mImageUrl)) {
            Glide.with(this)
                    .load(Url.BASE_URL + mImageUrl)
                    .error(Glide.with(this).load(R.drawable.tx))
                    .into(mBinding.headimage);
            return;
        }

        if (mUserInfo == null || TextUtils.isEmpty(mUserInfo.photo)) {
            return;
        }

        Glide.with(this)
                .load(Url.BASE_URL + mUserInfo.photo)
                .error(Glide.with(this).load(R.drawable.tx))
                .into(mBinding.headimage);
    }

    @Override
    public void onBackPressed() {
        if (mChanged) {
            DialogUtils.showAlertDialog(this, "温馨提示", "您的资料已经修改，请点击保存提交修改。", (dialog, which) -> {
            }, (dialog, which) -> super.onBackPressed());
            return;
        }
        super.onBackPressed();
    }
}