package com.efounder.chat.activity;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.widget.SwitchCompat;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.efounder.chat.R;
import com.efounder.chat.db.WeChatDBManager;
import com.efounder.chat.http.GetHttpUtil;
import com.efounder.chat.manager.PictureAndCropManager;
import com.efounder.chat.utils.LXGlideImageLoader;
import com.efounder.chat.utils.PansoftCloudUtil;
import com.efounder.constant.EnvironmentVariable;
import com.efounder.mobilecomps.contacts.User;
import com.efounder.util.AppContext;
import com.efounder.util.EnvSupportManager;
import com.efounder.util.ToastUtil;
import com.efounder.utils.EasyPermissionUtils;
import com.efounder.utils.ResStringUtil;
import com.utilcode.util.UriUtils;

import java.io.File;

import pub.devrel.easypermissions.AfterPermissionGranted;

import static com.efounder.frame.utils.Constants.CHAT_USER_ID;
import static com.efounder.frame.utils.Constants.KEY_ALLOW_CHANGEPWD;
import static com.efounder.frame.utils.Constants.KEY_SETTING_APPID;
import static com.efounder.frame.utils.Constants.KEY_TANGZU_JSRQ;
import static com.efounder.frame.utils.NetStateBroadcastReceiver.isNetActive;


/**
 * 个人信息界面
 *
 * @author YQS
 */
@SuppressLint("SdCardPath")
public class MyUserInfoActivity extends BaseActivity {

    private static final int PHOTO_REQUEST_TAKEPHOTO = 1;// 拍照
    private static final int PHOTO_REQUEST_GALLERY = 2;// 从相册中选择
    private static final int PHOTO_REQUEST_CUT = 3;// 结果

    private RelativeLayout re_avatar;
    private RelativeLayout re_name;
    private RelativeLayout re_fxid;
    private RelativeLayout re_sex;
    private RelativeLayout re_region;
    private RelativeLayout re_sign;
    private RelativeLayout re_erweima;
    private RelativeLayout re_alterPassword;//修改密码
    private RelativeLayout re_moneycode;
    private RelativeLayout re_userInfo;

    private ImageView iv_avatar;
    private TextView tv_name;
    private TextView tv_fxid;
    private TextView tv_sex;
    private TextView tv_sign;
    private TextView tv_userId;
    private RelativeLayout rlStrangerChat;
    private SwitchCompat switchAllowChat;

    private int userId;
    private User user;
    private String hxid;
    private String fxid;//帐号
    private String sex;//性别
    private String sign;//个性签名
    private String nick;
    private String avatar;
    private String pictureUrlPath;//头像在网络上的位置
    private PictureAndCropManager pictureAndCropManager;//拍照裁剪


    public static void start(Context context,String userId) {
        Intent starter = new Intent(context, MyUserInfoActivity.class);
        starter.putExtra("id",userId);
        context.startActivity(starter);
    }
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_myinfo);
        pictureAndCropManager = new PictureAndCropManager(this);
        initView();
        initData();
    }

    @Override
    protected void onResume() {
        super.onResume();
        user = WeChatDBManager.getInstance().getOneUserById(Integer.valueOf(EnvironmentVariable.getProperty(CHAT_USER_ID)));
        refreshUserData();
    }

    private void initView() {
        TextView tvTitle = (TextView) findViewById(R.id.tv_title);
        tvTitle.setText(R.string.chat_user_info);
        re_avatar = (RelativeLayout) this.findViewById(R.id.re_avatar);
        re_name = (RelativeLayout) this.findViewById(R.id.re_name);
        re_fxid = (RelativeLayout) this.findViewById(R.id.re_fxid);
        re_sex = (RelativeLayout) this.findViewById(R.id.re_sex);
        re_region = (RelativeLayout) this.findViewById(R.id.re_region);
        re_sign = (RelativeLayout) findViewById(R.id.re_sign);
        re_erweima = (RelativeLayout) findViewById(R.id.re_erweima);
        re_userInfo = (RelativeLayout) findViewById(R.id.re_alterUserInforData);
        re_alterPassword = (RelativeLayout) findViewById(R.id.re_alterpassword);
        re_moneycode = (RelativeLayout) findViewById(R.id.re_moneycode);
        re_erweima.setOnClickListener(new MyListener());
        re_avatar.setOnClickListener(new MyListener());
        re_name.setOnClickListener(new MyListener());
        re_fxid.setOnClickListener(new MyListener());
        re_sex.setOnClickListener(new MyListener());
        re_region.setOnClickListener(new MyListener());
        re_sign.setOnClickListener(new MyListener());
        re_alterPassword.setOnClickListener(new MyListener());
        re_userInfo.setOnClickListener(new MyListener());
        re_moneycode.setOnClickListener(new MyListener());
        iv_avatar = (ImageView) this.findViewById(R.id.iv_avatar);
        tv_name = (TextView) this.findViewById(R.id.tv_name);
        tv_fxid = (TextView) this.findViewById(R.id.tv_fxid);
        tv_sex = (TextView) this.findViewById(R.id.tv_sex);
        tv_sign = (TextView) this.findViewById(R.id.tv_sign);
        tv_userId = (TextView) this.findViewById(R.id.tv_userId);
        rlStrangerChat = (RelativeLayout) findViewById(R.id.rl_stranger_chat);
        switchAllowChat = (SwitchCompat) findViewById(R.id.switch_allow_chat);
    }

    private void initData() {
        userId = getIntent().getIntExtra("id", 1);
        //是否显示 我的收款码菜单
        if ("1".equals(EnvironmentVariable.getProperty("isShowMoneyCode"))) {
            re_moneycode.setVisibility(View.VISIBLE);
        }
        //是否允许修改密码
        if ("0".equals(EnvironmentVariable.getProperty(KEY_ALLOW_CHANGEPWD))) {
            re_alterPassword.setVisibility(View.GONE);
        } else {
            re_alterPassword.setVisibility(View.VISIBLE);
        }
        //是否支持设置允许陌生人聊天
        if (EnvSupportManager.isSupportSetStrangerChat()) {
            rlStrangerChat.setVisibility(View.VISIBLE);
            switchAllowChat.setOnClickListener(new MyListener());
        }
        if ("OSPMobileTZu".equals(EnvironmentVariable.getProperty(KEY_SETTING_APPID))) {
            re_userInfo.setVisibility(View.VISIBLE);
        } else {
            re_userInfo.setVisibility(View.GONE);
        }
    }

    //刷新数据
    private void refreshUserData() {
        nick = user.getNickName();
        fxid = EnvironmentVariable.getUserName();
        sex = user.getSex();
        sign = user.getSigNature();
        avatar = user.getAvatar();
        boolean allow = user.isAllowStrangerChat();
        if (allow) {
            switchAllowChat.setChecked(true);
        } else {
            switchAllowChat.setChecked(false);
        }
//        tv_userId.setText(String.valueOf(userId)); fix 用户ID显示异常
        tv_userId.setText(EnvironmentVariable.getProperty( CHAT_USER_ID ));
        tv_name.setText(nick);
        tv_fxid.setText(fxid == null || "".equals(fxid) ? ResStringUtil.getString(R.string.chat_not_set) : fxid);
        tv_sex.setText("M".equals(sex) ? ResStringUtil.getString(R.string.chat_male) : ResStringUtil.getString(R.string.chat_female));
        tv_sign.setText(sign != null && !sign.equals("") ? sign : ResStringUtil.getString(R.string.chat_unfilled));
        showUserAvatar(avatar);
    }

    class MyListener implements OnClickListener {

        @Override
        public void onClick(View v) {
            int id = v.getId();
            if (id == R.id.re_avatar) {
                //修改头像
                showPhotoDialog();
            } else if (id == R.id.re_name) {
                ///修改昵称
                String appId = EnvironmentVariable.getProperty(KEY_SETTING_APPID);
                if (appId.equals("OSPMobileSD")) {
                    return;
                }
                Intent intent = new Intent(MyUserInfoActivity.this, UpdatePersonalInfoActivity.class);
                intent.putExtra("type", "nickName");
                startActivity(intent);
            } else if (id == R.id.re_fxid) {

            } else if (id == R.id.re_sex) {
                //修改性别
                showSexDialog();
            } else if (id == R.id.re_sign) {
                //修改签名
                Intent intent = new Intent(MyUserInfoActivity.this, UpdatePersonalInfoActivity.class);
                intent.putExtra("type", "sigNature");
                startActivity(intent);
            } else if (id == R.id.re_erweima) {
                Intent intent = new Intent(MyUserInfoActivity.this, CreateUserQRCode.class);
                Bundle bundle = new Bundle();
                bundle.putString("type", "addFriend");
                bundle.putString("id", EnvironmentVariable.getProperty(CHAT_USER_ID));
                bundle.putString("avatar", user.getAvatar());
                bundle.putString("nickname", user.getNickName());
                bundle.putString("name", user.getName());
                bundle.putString("sex", user.getSex());
                intent.putExtras(bundle);
                startActivity(intent);
            } else if (id == R.id.re_alterpassword) {
                //判断是否是标准restful登录的项目
                String loginType = EnvironmentVariable.getProperty("LoginType");
                if (null != loginType && loginType.equals("0")) {
                    Intent intent = new Intent(MyUserInfoActivity.this, AlterPassWordByRestFulActivity.class);
                    startActivity(intent);
                } else {
                    Intent intent = new Intent(MyUserInfoActivity.this, AlterPassWordActivity.class);
                    startActivity(intent);
                }
            } else if (id == R.id.re_alterUserInforData) {
                //完善患者;
                startToPerfectUserData();
            } else if (id == R.id.re_moneycode) {
                //我的收款码;
                startActivity(new Intent(MyUserInfoActivity.this, SetMyReceiveMoneyCodeActivity.class));
            } else if (id == R.id.switch_allow_chat) {
                //设置是否接收陌生人消息
                updateAllowStrangerChat(switchAllowChat.isChecked());
            }
        }
    }

    /***
     * 完善信息（糖足）
     */
    @Deprecated
    private void startToPerfectUserData() {
        String enterName = "";
        if ("3".equals(EnvironmentVariable.getProperty(KEY_TANGZU_JSRQ))) {
            // 患者
            enterName = "SDPerfectDiabeteInfo";
        } else if ("9".equals(EnvironmentVariable.getProperty(KEY_TANGZU_JSRQ))
                || "2".equals(EnvironmentVariable.getProperty(KEY_TANGZU_JSRQ))
                || "7".equals(EnvironmentVariable.getProperty(KEY_TANGZU_JSRQ))
                ) {
            //医生
            enterName = "SDPerfectDoctorInfo";
        } else if ("10".equals(EnvironmentVariable.getProperty(KEY_TANGZU_JSRQ))) {
            //医生助理
            enterName = "SDPerfectAssistantInfo";
        } else if ("10".equals(EnvironmentVariable.getProperty(KEY_TANGZU_JSRQ))) {
            //医生助理
            enterName = "SDPerfectAssistantInfo";
        }
        if (TextUtils.isEmpty(enterName)) {
            ToastUtil.showToast(this, R.string.chat_not_need_improve);
            return;
        }
        JumpToRN(enterName);
    }

    private void JumpToRN(String enterName) {
        try {
            Class<?> clazz = Class.forName("com.efounder.SDReactNativeContainerForTZ");
            Intent intent = new Intent(this, clazz);
            Bundle bundle = new Bundle();
            bundle.putString("enterName", enterName);
            bundle.putBoolean("isEdit", true);
            intent.putExtra("data", bundle);
            startActivity(intent);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
            Log.e(this.getClass().getName(), ResStringUtil.getString(R.string.chat_no_find_class));
        }
    }

    private void showPhotoDialog() {
        final AlertDialog dlg = new AlertDialog.Builder(this).create();
        dlg.show();
        Window window = dlg.getWindow();
        // *** 主要就是在这里实现这种效果的.
        // 设置窗口的内容页面,shrew_exit_dialog.xml文件中定义view内容
        window.setContentView(R.layout.alertdialog);
        // 为确认按钮添加事件,执行退出应用操作
        TextView tv_paizhao = (TextView) window.findViewById(R.id.tv_content1);
        tv_paizhao.setText(R.string.common_text_take_picture);
        tv_paizhao.setOnClickListener(new OnClickListener() {
            @Override
            @SuppressLint("SdCardPath")
            public void onClick(View v) {
                dlg.cancel();
                startTakePhoto();
            }
        });
        TextView tv_xiangce = (TextView) window.findViewById(R.id.tv_content2);
        tv_xiangce.setText(R.string.common_text_photo_album);
        View lineView = window.findViewById(R.id.line1);
        lineView.setVisibility(View.VISIBLE);
        tv_xiangce.setVisibility(View.VISIBLE);
        tv_xiangce.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                pictureAndCropManager.selectPhoto();
                dlg.cancel();
            }
        });

    }

    @AfterPermissionGranted(EasyPermissionUtils.PERMISSION_REQUEST_CODE_CAMERA)
    private void startTakePhoto() {
        if (EasyPermissionUtils.checkCameraPermission()) {
            pictureAndCropManager.takePicture();
        } else {
            EasyPermissionUtils.requestCameraPermission(this);
        }
    }


    private void showSexDialog() {
        final AlertDialog dlg = new AlertDialog.Builder(this).create();
        dlg.show();
        Window window = dlg.getWindow();
        // *** 主要就是在这里实现这种效果的.
        // 设置窗口的内容页面,shrew_exit_dialog.xml文件中定义view内容
        window.setContentView(R.layout.alertdialog);
        LinearLayout ll_title = (LinearLayout) window
                .findViewById(R.id.ll_title);
        ll_title.setVisibility(View.VISIBLE);
        TextView tv_title = (TextView) window.findViewById(R.id.tv_title);
        tv_title.setText(R.string.chat_sex);
        // 为确认按钮添加事件,执行退出应用操作
        TextView tv_paizhao = (TextView) window.findViewById(R.id.tv_content1);
        View lineView = window.findViewById(R.id.line1);
        lineView.setVisibility(View.VISIBLE);
        tv_paizhao.setVisibility(View.VISIBLE);
        tv_paizhao.setText(R.string.chat_male);
        tv_paizhao.setOnClickListener(new OnClickListener() {
            @Override
            @SuppressLint("SdCardPath")
            public void onClick(View v) {
                if (!sex.equals("M")) {
                    tv_sex.setText(R.string.chat_male);
                    updateSex("M");
                }
                dlg.cancel();
            }
        });
        TextView tv_xiangce = (TextView) window.findViewById(R.id.tv_content2);
        tv_xiangce.setText(R.string.chat_female);
        tv_xiangce.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!sex.equals("F")) {
                    tv_sex.setText(R.string.chat_female);
                    updateSex("F");
                }
                dlg.cancel();
            }
        });
    }

    @SuppressLint("SdCardPath")
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case PHOTO_REQUEST_TAKEPHOTO:
                    pictureAndCropManager.startPhotoZoom(UriUtils.getUriForFile(
                            new File(pictureAndCropManager.getPicturePath())), 300);
                    break;

                case PHOTO_REQUEST_GALLERY:
                    if (data != null) {
                        pictureAndCropManager.startPhotoZoom(data.getData(), 300);
                    }
                    break;

                case PHOTO_REQUEST_CUT:
                    Log.i(ResStringUtil.getString(R.string.chat_cut_after_path), pictureAndCropManager.getPicturePath());
                    if (!isNetActive()) {
                        ToastUtil.showToast(AppContext.getInstance(), R.string.common_text_network_error_please_again);
                        return;
                    }
                    showLoading(ResStringUtil.getString(R.string.common_text_uploading));
                    try {
                        PansoftCloudUtil.getCloudRes(pictureAndCropManager.getPicturePath(), new PansoftCloudUtil.UpLoadListener() {
                            @Override
                            public void getHttpUrl(Boolean isSuccess, String url) {
                                if (isSuccess) {
                                    Log.i("MyUserInfoActivity", ResStringUtil.getString(R.string.chat_path_of_head) + url);
                                    pictureUrlPath = url;
                                    pictureUrlPath.trim();
                                    GetHttpUtil.updateMyselfInfo(MyUserInfoActivity.this,
                                            "avatar", pictureUrlPath, new GetHttpUtil
                                                    .UpdateUserInfoCallBack() {

                                                @Override
                                                public void updateSuccess(boolean isSuccess) {
                                                    if (isSuccess) {
                                                        showUserAvatar(pictureUrlPath);
                                                        user.setAvatar(pictureUrlPath);
                                                        WeChatDBManager.getInstance().insertUserTable(user);
                                                        dismissLoading();
                                                        ToastUtil.showToast(AppContext.getInstance(), R.string.common_text_upload_success);
                                                    } else {
                                                        dismissLoading();
                                                        ToastUtil.showToast(AppContext.getInstance(), R.string.common_text_upload_fail_again);
                                                    }

                                                }
                                            });

                                } else {
                                    showUserAvatar(avatar);
                                    dismissLoading();
                                    ToastUtil.showToast(AppContext.getInstance(), R.string.common_text_upload_fail_again);
                                }
                            }
                        });
                    } catch (Exception e) {
                        e.printStackTrace();
                        ToastUtil.showToast(AppContext.getInstance(), R.string.common_text_upload_fail_again);
                    }
                    break;
            }
            super.onActivityResult(requestCode, resultCode, data);
        }
    }

    @Override
    public void back(View view) {
        finish();
    }

    /**
     * 显示用户头像
     */
    private void showUserAvatar(String url) {
        LXGlideImageLoader.getInstance().showRoundUserAvatar(this, iv_avatar, url
                , LXGlideImageLoader.DEFATLT_AVATAR_RADIUS_10);
    }

    /**
     * 更新性别
     *
     * @param sexnum
     */
    public void updateSex(final String sexnum) {
        showLoading(ResStringUtil.getString(R.string.common_text_please_wait));
        try {
            GetHttpUtil.updateMyselfInfo(MyUserInfoActivity.this, "sex", sexnum, new GetHttpUtil
                    .UpdateUserInfoCallBack() {


                @Override
                public void updateSuccess(boolean isSuccess) {
                    if (isSuccess) {
                        dismissLoading();
                        sex = sexnum;
                        if (sexnum.equals("M")) {
                            tv_sex.setText(R.string.chat_male);
                        } else {
                            tv_sex.setText(R.string.chat_female);
                        }
                        user.setSex(sexnum);
                        WeChatDBManager.getInstance().insertUserTable(user);
                        ToastUtil.showToast(MyUserInfoActivity.this, R.string.chat_update_success);
                    } else {
                        dismissLoading();
                        ToastUtil.showToast(MyUserInfoActivity.this, R.string.chat_update_fail);

                    }
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 更新是否允许陌生人聊天
     *
     * @param isAllow
     */
    public void updateAllowStrangerChat(final boolean isAllow) {
        showLoading(ResStringUtil.getString(R.string.common_text_please_wait));
        //fixme 在后台 0 是允许陌生人聊天，注意
        String value = isAllow ? "0" : "1";
        try {
            GetHttpUtil.updateMyselfInfo(MyUserInfoActivity.this, "disableStrangers", value, new GetHttpUtil
                    .UpdateUserInfoCallBack() {


                @Override
                public void updateSuccess(boolean isSuccess) {
                    if (isSuccess) {
                        dismissLoading();
                        user.setAllowStrangerChat(isAllow);
                        WeChatDBManager.getInstance().insertUserTable(user);
                        ToastUtil.showToast(MyUserInfoActivity.this, R.string.chat_update_success);
                    } else {
                        dismissLoading();
                        switchAllowChat.setChecked(!switchAllowChat.isChecked());
                        ToastUtil.showToast(MyUserInfoActivity.this, R.string.chat_update_fail);
                    }
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
