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.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.yunbao.common.Constants;
import com.yunbao.common.activity.AbsActivity;
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.ClickUtil;
import com.yunbao.common.utils.DialogUitl;
import com.yunbao.common.utils.L;
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 java.io.File;
import java.util.ArrayList;
import java.util.List;

import cn.qqtheme.framework.picker.OptionPicker;

/**
 * 我的 编辑资料
 */

// +———————————————————————————————————
// | 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 EditProfileActivity extends AbsActivity {

    private static final String TAG = "EditProfileActivity";
    private Dialog mLoading;
    private ProcessImageUtil mImageUtil;
    private Dialog mChooseImageDialog;

    private File mAvatarFile;
    private String mAvatarUrl;
    private ImageView mAvatar;//头像
    private EditText mName;//昵称
    private EditText mHeight;//身高
    private EditText mWeight;//体重
    private TextView mSex;//性别
    private TextView mStar;//星座

    private Integer[] mSexArray;
    private String[] mStarArray;

    private String mNameVal;
    private String mHeightVal;
    private String mWeightVal;
    private Integer mSexVal;
    private String mStarVal;


    public static void forward(Context context, int sex) {
        Intent intent = new Intent(context, EditProfileActivity.class);
        intent.putExtra(Constants.MAIN_SEX, sex);
        context.startActivity(intent);
    }

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

    @Override
    protected void main() {
        setTitle(WordUtil.getString(R.string.edit_profile));
        mSexVal = getIntent().getIntExtra(Constants.MAIN_SEX, 2);

        mAvatar = findViewById(R.id.avatar);
        mName = findViewById(R.id.nickname);//昵称
        mHeight = findViewById(R.id.height);//身高
        mWeight = findViewById(R.id.weight);//体重
        mSex = findViewById(R.id.sex);//性别
        mStar = findViewById(R.id.star);//星座

        if (mSex != null) {
            mSex.setText(mSexVal == 1 ? R.string.sex_male : R.string.sex_female);
        }
        mImageUtil = new ProcessImageUtil(this);
        mImageUtil.setImageResultCallback(new ImageResultCallback() {
            @Override
            public void beforeCamera() {

            }

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

            }

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

        getAuthInfo();

    }

    public void authClick(View v) {
        if (!ClickUtil.canClick()) {
            return;
        }
        int i = v.getId();
        if (i == R.id.btn_avatar) {
            chooseImage();
        } else if (i == R.id.btn_star) {
            chooseXinZuo();
        } else if (i == R.id.btn_sex) {
            chooseSex();
        } else if (i == R.id.btn_save) {
            submit();
        }
    }

    /**
     * 选择图片
     */
    public void chooseImage() {
        if (mChooseImageDialog == null) {
            mChooseImageDialog = DialogUitl.getStringArrayDialog(mContext, new Integer[]{
                    R.string.camera, R.string.alumb}, true, new DialogUitl.StringArrayDialogCallback() {
                @Override
                public void onItemClick(String text, int tag) {
                    if (tag == R.string.camera) {
                        mImageUtil.getImageByCamera(true);
                    } else {
                        mImageUtil.getImageByAlumb(false);
                    }
                }
            });
        }
        mChooseImageDialog.show();
    }

    private void getAuthInfo() {
        MainHttpUtil.getUserMaterial(new HttpCallback() {
            @Override
            public void onSuccess(int code, String msg, String[] info) {
                if (code == 0 && info.length > 0) {
                    JSONObject obj = JSON.parseObject(info[0]);
                    mAvatarUrl = obj.getString("avatar");
                    if (mAvatar != null) {
                        ImgLoader.display(mContext, mAvatarUrl, mAvatar);
                    }
                    mNameVal = obj.getString("user_nickname");
                    if (mName != null) {
                        mName.setText(mNameVal);
                    }

                    mSexVal = obj.getIntValue("sex");
                    if (mSex != null) {
                        mSex.setText(mSexVal == 1 ? R.string.sex_male : R.string.sex_female);
                    }
                    mHeightVal = obj.getString("height");
                    if (mHeight != null) {
                        mHeight.setText(mHeightVal);
                    }
                    mWeightVal = obj.getString("weight");
                    if (mWeight != null) {
                        mWeight.setText(mWeightVal);
                    }
                    mStarVal = obj.getString("constellation");
                    if (mStar != null) {
                        mStar.setText(mStarVal);
                    }
                }
            }
        });
    }

    /**
     * 选择性别
     */
    private void chooseSex() {
        if (mSexArray == null) {
            mSexArray = new Integer[]{R.string.sex_male, R.string.sex_female};
        }
        DialogUitl.showStringArrayDialog(mContext, mSexArray, new DialogUitl.StringArrayDialogCallback() {
            @Override
            public void onItemClick(String text, int tag) {
                mSexVal = tag == mSexArray[0] ? 1 : 2;
                if (mSex != null) {
                    mSex.setText(text);
                }
            }
        });
    }

    /**
     * 选择星座
     */
    private void chooseXinZuo() {
        if (mStarArray == null) {
            mStarArray = new String[]{
                    WordUtil.getString(R.string.xingzuo_00),
                    WordUtil.getString(R.string.xingzuo_01),
                    WordUtil.getString(R.string.xingzuo_02),
                    WordUtil.getString(R.string.xingzuo_03),
                    WordUtil.getString(R.string.xingzuo_04),
                    WordUtil.getString(R.string.xingzuo_05),
                    WordUtil.getString(R.string.xingzuo_06),
                    WordUtil.getString(R.string.xingzuo_07),
                    WordUtil.getString(R.string.xingzuo_08),
                    WordUtil.getString(R.string.xingzuo_09),
                    WordUtil.getString(R.string.xingzuo_10),
                    WordUtil.getString(R.string.xingzuo_11)
            };
        }
        DialogUitl.showXinZuoDialog(this, mStarArray, new OptionPicker.OnOptionPickListener() {
            @Override
            public void onOptionPicked(int index, String item) {
                if (mStar != null) {
                    mStar.setText(item.substring(0, item.indexOf("(")));
                }
            }
        });
    }


    /**
     * 提交认证信息
     */
    private void submit() {
        mNameVal = mName.getText().toString().trim();
        if (mSexVal == null) {
            ToastUtil.show(R.string.auth_tip_24);
            return;
        }
        mHeightVal = mHeight.getText().toString().trim();
        mWeightVal = mWeight.getText().toString().trim();
        mStarVal = mStar.getText().toString().trim();
        if (mAvatarFile != null && mAvatarFile.exists()) {
            uploadFile();
        } else {
            doSubmit();
        }
    }

    /**
     * 上传图片
     */
    private void uploadFile() {
        if (mLoading == null) {
            mLoading = DialogUitl.loadingDialog(mContext);
        }
        mLoading.show();
        L.e(TAG, "上传图片开始--------->");
        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;
                }
                List<UploadBean> list = new ArrayList<>();
                UploadBean uploadBean = new UploadBean(mAvatarFile);
                uploadBean.setType(UploadBean.IMG);
                list.add(uploadBean);
                strategy.upload(list, true, new UploadCallback() {
                    @Override
                    public void onFinish(List<UploadBean> list, boolean success) {
                        L.e(TAG, "上传图片完成---------> " + success);
                        if (success) {
                            if (list != null && list.size() > 0) {
                                mAvatarUrl = list.get(0).getRemoteFileName();
                            }
                            doSubmit();
                        }
                    }
                });

            }
        });
    }

    private String getPrefixUrl(String completeUrl) {
        if (TextUtils.isEmpty(completeUrl)) {
            return "";
        }
        if (completeUrl.contains("http://") || completeUrl.contains("https://")) {
            String tempStr = completeUrl.substring(0, completeUrl.lastIndexOf(".") + 4);
            String lastName = tempStr.substring(tempStr.lastIndexOf("/") + 1);
            if (completeUrl.contains(Constants.UPLOAD_TYPE_AWS)) {
                completeUrl = Constants.UPLOAD_TYPE_PREFIX_AWS + lastName;
            } else if (completeUrl.contains(Constants.UPLOAD_TYPE_QINIU)) {
                completeUrl = Constants.UPLOAD_TYPE_PREFIX_QINIU + lastName;
            }
            L.e(TAG, "getPrefixUrl--->tempStr-->" + tempStr + " ---fileName--->" + completeUrl);
        }
        return completeUrl;
    }

    private void doSubmit() {
        if (!TextUtils.isEmpty(mAvatarUrl)) {
            mAvatarUrl = getPrefixUrl(mAvatarUrl);
        }
        MainHttpUtil.updateUserInfo(mAvatarUrl, mNameVal, mSexVal, mHeightVal, mWeightVal, mStarVal,
                new HttpCallback() {
                    @Override
                    public void onSuccess(int code, String msg, String[] info) {
                        if (code == 0) {
                            finish();
                        }
                        ToastUtil.show(msg);
                        if (mLoading != null) {
                            mLoading.dismiss();
                        }
                    }

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

    @Override
    protected void onDestroy() {
        MainHttpUtil.cancel(MainHttpConsts.UPDATE_USER_INFO);
        if (mImageUtil != null) {
            mImageUtil.release();
        }
        mImageUtil = null;
        super.onDestroy();
    }


}
