package com.yunbao.main.activity;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioGroup;

import com.yunbao.common.CommonAppConfig;
import com.yunbao.common.Constants;
import com.yunbao.common.activity.AbsActivity;
import com.yunbao.common.bean.UserBean;
import com.yunbao.common.event.LoginSuccessEvent;
import com.yunbao.common.glide.ImgLoader;
import com.yunbao.common.http.HttpCallback;
import com.yunbao.common.interfaces.CommonCallback;
import com.yunbao.common.interfaces.ImageResultCallback;
import com.yunbao.common.upload.FileUploadManager;
import com.yunbao.common.upload.UploadBean;
import com.yunbao.common.upload.UploadCallback;
import com.yunbao.common.upload.UploadStrategy;
import com.yunbao.common.utils.DialogUitl;
import com.yunbao.common.utils.ProcessImageUtil;
import com.yunbao.common.utils.ToastUtil;
import com.yunbao.common.utils.WordUtil;
import com.yunbao.main.R;
import com.yunbao.main.http.MainHttpConsts;
import com.yunbao.main.http.MainHttpUtil;

import org.greenrobot.eventbus.EventBus;

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

/**
 * 设置个人资料
 */
// +———————————————————————————————————
// | Created by Yunbao
// +———————————————————————————————————
// | Copyright (c) 2013~2022 http://www.yunbaokj.com All rights reserved.
// +———————————————————————————————————
// | Author: https://gitee.com/yunbaokeji
// +———————————————————————————————————
// | Date: 2022-03-22
// +———————————————————————————————————
public class SetProfileActivity extends AbsActivity implements View.OnClickListener {

    public static void forward(Context context, UserBean userBean, boolean isShowRecommend) {
        Intent intent = new Intent(context, SetProfileActivity.class);
        intent.putExtra(Constants.USER_BEAN, userBean);
        intent.putExtra(Constants.SHOW_RECOMMEND, isShowRecommend);
        context.startActivity(intent);
    }

    private ImageView mAvatar;
    private EditText mNickname;

    private View mBtnSave;
    private int mSexVal = 2;//默认女
    private ProcessImageUtil mImageUtil;
    private File mAvatarFile;
    private String mAvatarFileUrl = "";
    private UploadStrategy mUploadStrategy;
    private Dialog mLoading;
    private RadioGroup mRgSelectSex;
    private boolean isShowRecommend;

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

    @Override
    protected void main() {
        setTitle(WordUtil.getString(R.string.set_profile));
        mAvatar = findViewById(R.id.avatar);
        mNickname = findViewById(R.id.nickname);
        mRgSelectSex = findViewById(R.id.rg_select_sex);
        mBtnSave = findViewById(R.id.btn_save);
        mBtnSave.setOnClickListener(this);
        mAvatar.setOnClickListener(this);
        mImageUtil = new ProcessImageUtil(this);
        mImageUtil.setImageResultCallback(new ImageResultCallback() {
            @Override
            public void beforeCamera() {

            }

            @Override
            public void onSuccess(File file) {
                if (file != null) {
                    ImgLoader.display(mContext, file, mAvatar);
                    mAvatarFile = file;
                }
            }

            @Override
            public void onFailure() {

            }
        });

        Intent intent = getIntent();
        UserBean userBean = intent.getParcelableExtra(Constants.USER_BEAN);
        isShowRecommend = intent.getBooleanExtra(Constants.SHOW_RECOMMEND, false);
        if (userBean != null) {
            ImgLoader.display(mContext, userBean.getAvatar(), mAvatar);
            String nickname = userBean.getUserNiceName();
            mNickname.setText(nickname);
            mNickname.setSelection(nickname.length());
        }

        mRgSelectSex.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                if (checkedId == R.id.rb_select_girl) {
                    mSexVal = 2;
                } else if (checkedId == R.id.rb_select_boy) {
                    mSexVal = 1;
                }
            }
        });
    }


    @Override
    public void onClick(View v) {
        int i = v.getId();
        if (i == R.id.btn_save) {
            save();
        } else if (i == R.id.avatar) {
            chooseAvatar();
        }
    }

    /**
     * 保存
     */
    private void save() {
        if (mAvatarFile != null && mAvatarFile.exists()) {
            String name = mNickname.getText().toString().trim();
            if (TextUtils.isEmpty(name)) {
                ToastUtil.show(R.string.set_profile_nickname);
                return;
            }
            uploadAvatarImage();
        } else {
            submit();
        }
    }

    /**
     * 选择图片
     */
    private void chooseAvatar() {
        DialogUitl.showStringArrayDialog(mContext, new Integer[]{
                R.string.camera, R.string.alumb}, new DialogUitl.StringArrayDialogCallback() {
            @Override
            public void onItemClick(String text, int tag) {
                if (tag == R.string.camera) {
                    mImageUtil.getImageByCamera();
                } else {
                    mImageUtil.getImageByAlumb();
                }
            }
        });
    }


    /**
     * 上传头像
     */
    private void uploadAvatarImage() {
        mLoading = DialogUitl.loadingDialog(mContext);
        mLoading.show();
        FileUploadManager.getInstance().createUploadImpl(mContext, new CommonCallback<UploadStrategy>() {
            @Override
            public void callback(UploadStrategy strategy) {
                if (strategy == null) {
                    ToastUtil.show(WordUtil.getString(R.string.upload_type_error));
                    return;
                }
                mUploadStrategy = strategy;
                List<UploadBean> list = new ArrayList<>();
                list.clear();
                list.add(new UploadBean(mAvatarFile));
                mUploadStrategy.upload(list, true, new UploadCallback() {
                    @Override
                    public void onFinish(List<UploadBean> list, boolean success) {
                        if (success) {
                            if (list != null && list.size() > 0) {
                                mAvatarFileUrl = list.get(0).getRemoteFileName();
                                submit();
                            }
                        }
                    }
                });
            }
        });
    }

    /**
     * 提交信息
     */
    private void submit() {
        String name = mNickname.getText().toString().trim();
        if (TextUtils.isEmpty(name)) {
            ToastUtil.show(R.string.set_profile_nickname);
            return;
        }
        MainHttpUtil.setUserProfile(mAvatarFileUrl, name, mSexVal, new HttpCallback() {
            @Override
            public void onSuccess(int code, String msg, String[] info) {
                if (code == 0 && info.length > 0) {
                    getBaseInfo();
                } else {
                    ToastUtil.show(msg);
                }
            }

            @Override
            public void onFinish() {
                if (mLoading != null) {
                    mLoading.dismiss();
                }
            }
        });
    }

    private void getBaseInfo() {
        MainHttpUtil.getBaseInfo(new CommonCallback<Object[]>() {
            @Override
            public void callback(Object[] bean) {
                if (bean[0] != null) {
                    MainActivity.forward(mContext, true, isShowRecommend);
                    CommonAppConfig.getInstance().setLoginInfo(
                            CommonAppConfig.getInstance().getUid(),
                            CommonAppConfig.getInstance().getToken(), true);
                    EventBus.getDefault().post(new LoginSuccessEvent());
                    finish();
                }
            }
        });
    }


    @Override
    protected void onDestroy() {
        if (mLoading != null) {
            mLoading.dismiss();
        }
        MainHttpUtil.cancel(MainHttpConsts.SET_USER_PROFILE);
        super.onDestroy();
    }
}
