package com.tofly.ghrq_route.common.ui.activity;

import android.app.AlertDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
import androidx.annotation.NonNull;
import com.gaoyuan.weixinrecord.utils.PermissionHelper;
import com.mgq.base.utils.customview.CircleImageView;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.listener.ImageLoadingListener;
import com.tofly.ghrq_route.R;
import com.tofly.ghrq_route.base.BaseApp;
import com.tofly.ghrq_route.base.ui.BaseUi;
import com.tofly.ghrq_route.base.url.NetRequestURL;
import com.tofly.ghrq_route.common.ui.dialog.UserModifyDailog;
import com.tofly.ghrq_route.common.ui.dialog.UserPasswordModifyDailog;
import com.tofly.ghrq_route.common.util.dialog.DialogUtil;
import com.tofly.ghrq_route.module.user.UserInfoTool;
import com.tofly.ghrq_route.module.user.controller.UserCallBack;
import com.tofly.ghrq_route.module.user.domain.UserBean;
import com.tofly.ghrq_route.common.util.image.ImageUtil;
import com.tofly.ghrq_route.common.util.image.PhotoHelper;
import org.greenrobot.eventbus.EventBus;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by zombiexq on 2016/7/1.
 */
public class UiUserInfo extends BaseUi implements View.OnClickListener {
    @BindView(R.id.image_user_icon)
    CircleImageView imgviewFace;
    @BindView(R.id.text_user_name)
    TextView textUserName;
    @BindView(R.id.text_dep_name)
    TextView textDepName;
    @BindView(R.id.userinfo_phone)
    TextView textUserPhone;
    @BindView(R.id.text_user_password)
    TextView textPassword;

    //private final static String TAG = UiUserInfo.class.getSimpleName();

    private PhotoHelper photoHelper;
    private PermissionHelper permissionHelper;

    private ImageUtil imageUtil;

    private UserBean modifyUser = new UserBean();

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.ui_userinfo);
        ButterKnife.bind(this);

        permissionHelper = new PermissionHelper(this);
        imageUtil = new ImageUtil(this);

        initView();
        initData();
        initListener();

    }

    private void initView() {

    }

    private void initData() {
        initUserInfo();
        getUserInfo();
    }

    private void initUserInfo() {
        UserBean user = BaseApp.getInstance().getLoginUser();

        textUserName.setText(user.getRealName());
        textDepName.setText(user.getDepartmentName());
        textUserPhone.setText(user.getMobile());

        String avatar = user.getAvatar();
        if (avatar != null && !avatar.isEmpty()) {//根据用户名下载头像
            String faceurl = NetRequestURL.newApi_dyrq.getFormattedPicture(avatar);
            ImageLoader loader = ImageLoader.getInstance();
            loader.displayImage(faceurl, imgviewFace, BaseApp.getDefaultDisplayOptions(), new ImageLoadingListener() {
                @Override
                public void onLoadingStarted(String s, View view) {
                    showLoadBar();
                }

                @Override
                public void onLoadingFailed(String s, View view, FailReason failReason) {
                    imgviewFace.setImageResource(R.mipmap.userinfo_modify_face);
                    hideLoadBar();
                }

                @Override
                public void onLoadingComplete(String s, View view, Bitmap bitmap) {
                    if (bitmap != null) {
                        imgviewFace.setImageBitmap(bitmap);
                    }
                    hideLoadBar();
                }

                @Override
                public void onLoadingCancelled(String s, View view) {
                    hideLoadBar();
                }
            });
        }
    }

    private void initListener() {

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_save, menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == R.id.action_save) {
            updateAccount();
        }
        return super.onOptionsItemSelected(item);
    }

    private void getUserInfo(){
        UserInfoTool userInfoTool = UserInfoTool.getInstance();
        userInfoTool.getUserInfo(this, new UserCallBack(){
            @Override
            public void onGetAccountInfo(boolean isSuccess, int errorCode, String errMsg, UserBean user) {
                super.onGetAccountInfo(isSuccess, errorCode, errMsg, user);
                hideLoadBar();
                if (isSuccess){
                    initUserInfo();
                }else {
                    DialogUtil.showTokenFailedDialog(UiUserInfo.this, errorCode);
                }
            }
        });
    }

    private void updateAccount(){
        String name = modifyUser.getUsername();
        String mobile = modifyUser.getMobile();
        String password = modifyUser.getPassword();
        String avatar = modifyUser.getAvatar();
        showLoadBar();
        UserInfoTool userInfoTool = UserInfoTool.getInstance();
        userInfoTool.updateAccount(this, name, mobile, password, avatar, new UserCallBack(){
            @Override
            public void onUpdateAccount(boolean isSuccess, int errorCode, String errMsg) {
                super.onUpdateAccount(isSuccess, errorCode, errMsg);
                if (isSuccess){
                }else
                    hideLoadBar();
            }

            @Override
            public void onGetAccountInfo(boolean isSuccess, int errorCode, String errMsg, UserBean user) {
                super.onGetAccountInfo(isSuccess, errorCode, errMsg, user);
                hideLoadBar();
                if (isSuccess){
                    initUserInfo();
                    EventBus.getDefault().post(new MessageEvent(USER_ACCOUNT_CHANGED));
                }else {
                    DialogUtil.showTokenFailedDialog(UiUserInfo.this, errorCode);
                }
            }
        });
    }

    @OnClick({R.id.layout_user_face, R.id.layout_user_name, R.id.layout_user_phone, R.id.layout_user_password, R.id.image_user_icon})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.layout_user_face:
                showChangAvatarDialog();
                break;
            case R.id.layout_user_name:
                showChangeUserInfoDialog(UserModifyDailog.INPUT_NAME);
                break;
            case R.id.layout_user_phone:
                showChangeUserInfoDialog(UserModifyDailog.INPUT_MOBILE);
                break;
            case R.id.layout_user_password:
                showChangePasswordDialog();
                break;
            case R.id.image_user_icon:
                showBigImage();
                break;
        }
    }

    private void showBigImage() {
        String avatar = modifyUser.getAvatar();
        if (avatar == null || avatar.isEmpty()) {
            UserBean user = BaseApp.getInstance().getLoginUser();
            String file_url = user.getAvatar();
            avatar = NetRequestURL.newApi_dyrq.getFormattedPicture(file_url);
        }
        if (avatar != null && !avatar.isEmpty())
            imageUtil.showBigImage(avatar);
    }

    private void showChangeUserInfoDialog(int input_type){
        String userName = textUserName.getText().toString();
        String userPhone = textUserPhone.getText().toString();
        UserModifyDailog modifyDailog = new UserModifyDailog(this, userName, userPhone, input_type);
        modifyDailog.setClicklistener(new UserModifyDailog.ClickListenerInterface() {
            @Override
            public void doOk(String name, String mobile) {
                if (input_type == UserModifyDailog.INPUT_NAME){
                    modifyUser.setUsername(name);
                    textUserName.setText(name);
                }else if (input_type == UserModifyDailog.INPUT_MOBILE) {
                    modifyUser.setMobile(mobile);
                    textUserPhone.setText(mobile);
                }
            }

            @Override
            public void doCancel() {
            }
        });
        modifyDailog.show();
    }

    private void showChangePasswordDialog(){
        UserPasswordModifyDailog modifyDailog = new UserPasswordModifyDailog(this);
        modifyDailog.setClicklistener(new UserPasswordModifyDailog.ClickListenerInterface() {
            @Override
            public void doOk(String oldPassword, String newPassword) {
                String password = BaseApp.SHA1EncodeString(newPassword);
                modifyUser.setPassword(password);
                textPassword.setVisibility(View.VISIBLE);
                textPassword.setText(password);
            }

            @Override
            public void doCancel() {
            }
        });
        modifyDailog.show();
    }

    private void showChangAvatarDialog() {
        AlertDialog.Builder dialog = new AlertDialog.Builder(UiUserInfo.this)
                .setItems(new String[]{"从手机相册选择", "拍照"}
                        , (arg0, i) -> {
                            if (i == 0) {
                                getPicFromSysAlbums();
                            }
                            if (i == 1) {
                                getPicFromSysCamera();
                            }
                        }).setTitle("设置头像");
        dialog.setCancelable(true);
        dialog.show();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        permissionHelper.handleRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (photoHelper != null){
            photoHelper.handleActivityResult(requestCode, resultCode, data);
        }
    }

    private void getPicFromSysAlbums(){
        if (photoHelper == null)
            photoHelper = new PhotoHelper(this, permissionHelper);
        photoHelper.requestImagePhoto(true, (success, errStr, pictureBean) -> {
            if (success){
                if (pictureBean != null){
                    String picPath = pictureBean.getFilepath();
                    if (picPath != null && !picPath.isEmpty()){
                        modifyUser.setAvatar(picPath);
                        ImageLoader loader = ImageLoader.getInstance();
                        String real_url = "file://" + picPath;
                        loader.displayImage(real_url, imgviewFace);
                    }
                }
            }else {
                toast(errStr);
            }
        });
    }

    private void getPicFromSysCamera(){
        if (photoHelper == null)
            photoHelper = new PhotoHelper(this, permissionHelper);
        photoHelper.requestCameraPhoto(true, (success, errStr, pictureBean) -> {
            if (success){
                if (pictureBean != null){
                    String picPath = pictureBean.getFilepath();
                    if (picPath != null && !picPath.isEmpty()){
                        modifyUser.setAvatar(picPath);
                        ImageLoader loader = ImageLoader.getInstance();
                        String real_url = "file://" + picPath;
                        loader.displayImage(real_url, imgviewFace, BaseApp.getDefaultDisplayOptions());
                    }
                }
            }else {
                toast(errStr);
            }
        });
    }


    public final static String USER_ACCOUNT_CHANGED = "userAccountChanged";
    public final static String USER_SIGN_STATUS_CHANGED = "userSignStatusChanged";
    public static class MessageEvent{
        public final String message;
        MessageEvent(String message) {
            this.message = message;
        }
    }

    @Override
    protected void onStop() {
        BaseApp.cancelAllRequest(getClass().getName());
        super.onStop();
    }
}
