package com.rv.rvmine.traveler;

import android.Manifest;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.base.utils.ui.datetime.selector.util.TextUtil;
import com.base.utils.ui.image.round.RoundImageView;
import com.bigkoo.pickerview.TimePickerView;
import com.frame.base.bus.RxBus;
import com.frame.rv.config.RvFrameConfig;
import com.ruiwenliu.wrapper.base.BaseBean;
import com.ruiwenliu.wrapper.base.BaseStatusActivity;
import com.ruiwenliu.wrapper.bean.UserInfoBean;
import com.ruiwenliu.wrapper.util.ViewHolder;
import com.ruiwenliu.wrapper.util.glide.GlideManager;
import com.ruiwenliu.wrapper.util.permission.RxPermission;
import com.ruiwenliu.wrapper.weight.TitleView;
import com.rv.home.rv.module.ApiConfig;
import com.rv.home.rv.module.basic.dialog.PickerDialog;
import com.rv.home.rv.module.basic.presenter.PickerPresenter;
import com.rv.home.rv.module.ui.main.home.bean.ImageUploadBean;
import com.rv.rvmine.R;
import com.rv.rvmine.R2;
import com.rv.rvmine.dialog.ChooseGenderDialog;
import com.rv.rvmine.rxbusevent.UserInfoEvent;
import com.umeng.socialize.UMAuthListener;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.utils.SocializeUtils;
import com.yuyife.okgo.OkGoUtil;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.functions.Consumer;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;

/**
 * 个人资料
 */
public class PersonalInformationActivity extends BaseStatusActivity<PickerPresenter>  implements UMAuthListener {

    @BindView(R2.id.iv_avatar)
    RoundImageView ivAvatar;
    @BindView(R2.id.et_nickname)
    EditText etNickname;
    @BindView(R2.id.et_name)
    EditText etName;
    @BindView(R2.id.tv_date_of_birth)
    TextView tvDateOfBirth;
    @BindView(R2.id.tv_sex)
    TextView tvSex;
    @BindView(R2.id.et_phone)
    EditText etPhone;
    @BindView(R2.id.et_id_card)
    EditText etIdCard;
    @BindView(R2.id.tv_binding_qq)
    TextView tvBindingQq;
    @BindView(R2.id.tv_binding_wx)
    TextView tvBindingWx;
    private UserInfoBean.UserInfo info;
    private String ivAvatarUrl;
    public ProgressDialog dialog;
    private int mLoginType;
    private String mName;

    private int sex;// 0-女，1-男

    private String mQQOpenid;
    private String mWXOpenid;
    private String mUnionid;
    private String mHeadImg;

    private String birthday;

    public static Intent getIntent(Context context, UserInfoBean.UserInfo info) {
        return new Intent(context, PersonalInformationActivity.class)
                .putExtra("userinfo", info);
    }

    @Override
    protected int setLayout() {
        return R.layout.activity_personal_information;
    }

    @Override
    protected void initView(Bundle savedInstanceState, TitleView titleView, Intent intent) {
        titleView.setTitle("个人资料");
        titleView.setText(R.id.tv_title_right, "保存");
        titleView.setChildClickListener(R.id.tv_title_right, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                upUserinfo();
            }
        });
        dialog = new ProgressDialog(this);
        info = (UserInfoBean.UserInfo) intent.getSerializableExtra("userinfo");
        if (info != null) {
            ivAvatarUrl = info.getHeadimgurl();
            mWXOpenid = info.getWxOpenid();
            mUnionid = info.getUnionid();
            mQQOpenid =info.getOpenid() ;

            GlideManager.getInstance(mActivity).loadImage(info.getHeadimgurl(), ivAvatar);
            if (info.getNickname() != null) {
                etNickname.setText(info.getNickname());
                etNickname.setSelection(info.getNickname().length());
            }
            if (info.getRealname() != null) {
                etName.setText(info.getRealname());
            }
            if (info.getBirthday() != null) {
                birthday = info.getBirthday();
                tvDateOfBirth.setText(info.getBirthday());
            }
            if (info.getSex() != null) {
                sex = info.getSex();
                if (info.getSex() == 0) { // 0-女，1-男
                    tvSex.setText("女");
                } else if (info.getSex() == 1) {
                    tvSex.setText("男");
                } else {
                    tvSex.setText("");
                }
            }
            if (info.getUsername() != null) {
                etPhone.setText(info.getUsername());
            }
            if (info.getIdNumber() != null) {
                etIdCard.setText(info.getIdNumber());
            }

            if (TextUtils.isEmpty(info.getWxOpenid())) {
                tvBindingWx.setText("去授权绑定微信");
            } else {
                tvBindingWx.setText("已绑定");
            }

            if (TextUtils.isEmpty(info.getOpenid())) {
                tvBindingQq.setText("去授权绑定QQ");
            } else {
                tvBindingQq.setText("已绑定");
            }
        }
    }

    @Override
    public void onShowResult(int requestType, BaseBean result) {
        switch (requestType) {
            case 0:
                ImageUploadBean bean = (ImageUploadBean) result;
                ivAvatarUrl = bean.getData();
                break;
            case 1:
                RxBus.post(new UserInfoEvent());
                finish();
                break;
        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == mPresenter.TYPE_ALBUM_CODE) {
            if (data != null && data.getData() != null) {
                mPresenter.cropPhoto(data.getData());
            }
        } else if (requestCode == mPresenter.TYPE_CAMERA_CODE && resultCode == RESULT_OK) {
            mPresenter.cropPhoto(Uri.fromFile(new File(mPresenter.gerCameraStoreUrl())));
        } else if (requestCode == mPresenter.TYPE_CROP_CODE && resultCode == RESULT_OK) {
            String url = mPresenter.gerCameraStoreUrl();
            GlideManager.getInstance(mActivity).loadImage(url, ivAvatar);
            uploadFile(new File(mPresenter.gerCameraStoreUrl()), "camera");
        }

    }

    @OnClick({R2.id.rl_item_avatar, R2.id.ll_item_date_of_birth, R2.id.ll_item_sex, R2.id.ll_item_binding_qq, R2.id.ll_item_binding_wechat})
    public void onViewClicked(View view) {
        int id = view.getId();
        if (id == R.id.rl_item_avatar) {
            //头像
            showPickerDialog();

        } else if (id == R.id.ll_item_date_of_birth) {
            //出生日期
            initTimePicker1();
        } else if (id == R.id.ll_item_sex) {
            //性别
            chooseGender();

        } else if (id == R.id.ll_item_binding_qq) {
            //绑定qq
            bindThirdParty(SHARE_MEDIA.QQ);

        } else if (id == R.id.ll_item_binding_wechat) {
            //绑定微信
            bindThirdParty(SHARE_MEDIA.WEIXIN);
        }
    }

    private void bindThirdParty(SHARE_MEDIA share_media) {
        UMShareAPI.get(mActivity).getPlatformInfo(mActivity, share_media, this);
    }

    private void chooseGender() {
        new ChooseGenderDialog(mActivity) {
            @Override
            public void helper(final ViewHolder helper) {
                super.helper(helper);
                if (sex == 0) { // 0-女，1-男
                    helper.setChecked(R.id.cb_girl, true);
                } else if (sex == 1) {
                    helper.setChecked(R.id.cb_man, true);
                }

                helper.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        int id = v.getId();
                        if (id == R.id.cb_man) {
                            sex = 1;
                            helper.setChecked(R.id.cb_girl, false);
                        } else if (id == R.id.cb_girl) {
                            sex = 0;
                            helper.setChecked(R.id.cb_man, false);
                        } else if (id == R.id.tv_ok) {
                            if (sex == 0) { // 0-女，1-男
                                tvSex.setText("女");
                            } else if (sex == 1) {
                                tvSex.setText("男");
                            }
                            dismiss();
                        }
                    }
                }, R.id.cb_man, R.id.cb_girl, R.id.tv_ok);
            }
        }.show();
    }

    /**
     * 显示相机弹窗
     */
    private void showPickerDialog() {

        new PickerDialog(mActivity) {
            @Override
            public void helper(ViewHolder helper) {
                super.helper(helper);
                helper.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        int i = v.getId();
                        if (i == com.rv.home.R.id.btn_camera) {
                            processPicker(mPresenter.TYPE_CAMERA_CODE);
                            dismiss();

                        } else if (i == com.rv.home.R.id.btn_album) {
                            processPicker(mPresenter.TYPE_ALBUM_CODE);
                            dismiss();

                        } else if (i == com.rv.home.R.id.btn_cancel) {
                            dismiss();
                        }

                    }
                }, com.rv.home.R.id.btn_camera, com.rv.home.R.id.btn_album, com.rv.home.R.id.btn_cancel);
            }
        }.show();
    }

    /**
     * 打开相机和相册
     *
     * @param type 1、相机2、相册
     */
    private void processPicker(final int type) {
        /**
         * 6.0以上手机做权限处理
         */
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            new RxPermission(mActivity).request(
                    Manifest.permission.WRITE_EXTERNAL_STORAGE,
                    Manifest.permission.CAMERA).subscribe(new Consumer<Boolean>() {
                @Override
                public void accept(Boolean aBoolean) throws Exception {
                    if (aBoolean == true) {
                        switch (type) {
                            case 1001:
                                mPresenter.openCamera(false);
                                break;
                            case 1002:
                                mPresenter.openAlbum(false);
                                break;
                        }

                    }
                }
            });
        } else {
            switch (type) {
                case 1001:
                    mPresenter.openCamera(false);
                    break;
                case 1002:
                    mPresenter.openAlbum(false);
                    break;
            }
        }
    }


    /**
     * 上传文件
     *
     * @param file
     */
    private void uploadFile(File file, String fileName) {

        RequestBody requestFile =
                RequestBody.create(MediaType.parse("application/otcet-stream"), file);
        MultipartBody.Part body =
                MultipartBody.Part.createFormData("file", file.getName(), requestFile);
        RequestBody description =
                RequestBody.create(
                        MediaType.parse("multipart/form-data"), fileName);

//        // 创建 RequestBody，用于封装构建RequestBody
//        RequestBody requestFile =
//                RequestBody.create(MediaType.parse("multipart/form-data"), file);
//        MultipartBody.Part body =
//                MultipartBody.Part.createFormData("file", file.getName(), requestFile);
        mPresenter.getUploadFile(RvFrameConfig.VEHICLE_UPLOAD, 0, ApiConfig.HTTP_URL_FILE_UPLOAD, ImageUploadBean.class, description, body, true);
    }


    private void upUserinfo() {
        String nickName = etNickname.getText().toString().trim();
        if (TextUtil.isEmpty(nickName)) {
            showToast("昵称不为空！");
            return;
        }

        if (TextUtil.isEmpty(birthday)) {
            showToast("生日不为空！");
            return;
        }
        mPresenter.postBodyData(RvFrameConfig.ADMIN_POST, 1, ApiConfig.HTTP_URL_UPUSER_EDIT, BaseBean.class, new UserInfo(info.getId() + "", info.getUserid() + "", info.getUsername(), "0", nickName, info.getRealname(), ivAvatarUrl, birthday, sex,mWXOpenid,mUnionid,mQQOpenid), getHeadMap(), true);
    }

    private Map<String, Object> getHeadMap() {
        Map<String, Object> headMap = new LinkedHashMap<>();
        if (OkGoUtil.getToken() != null)
            headMap.put("Authorization", OkGoUtil.getToken());
        return headMap;
    }

    @Override
    public void onStart(SHARE_MEDIA share_media) {
        SocializeUtils.safeShowDialog(dialog);
    }

    @Override
    public void onComplete(SHARE_MEDIA share_media, int i, Map<String, String> data) {
        if (dialog != null) {
            SocializeUtils.safeCloseDialog(dialog);
        }

        mHeadImg = data.get("iconurl");
        mLoginType = share_media.getName().equals("qq") ? 1 : 0;
        if (mLoginType == 0) {
            mUnionid = data.get("unionid");
            mWXOpenid = data.get("openid");
            tvBindingWx.setText("已绑定");
        }else {
            mQQOpenid = data.get("openid");
            tvBindingQq.setText("已绑定");
        }
        mName = data.get("name");
    }

    @Override
    public void onError(SHARE_MEDIA share_media, int i, Throwable t) {
        SocializeUtils.safeCloseDialog(dialog);
        showToast(mActivity.getString(com.rv.home.R.string.rv_login_authorization_failure) + t.getMessage());
    }

    @Override
    public void onCancel(SHARE_MEDIA share_media, int i) {
        SocializeUtils.safeCloseDialog(dialog);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        UMShareAPI.get(mActivity).release();
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        UMShareAPI.get(mActivity).onSaveInstanceState(outState);
    }


    private class UserInfo {
        private String id;//":23,
        private String userid;//": 27,
        private String username;//": "13612688539",
        private String status;//": 0,
        private String nickname;//": "XX_414908",
        private String realname;//":"何振",
        private String headimgurl;//": "https://xxtest.upyuns.com/image/app/default_%20avatar.png"
        private String birthday;
        private int sex;
        private String wxOpenid;
        private String unionid;
        private String openid;

        public UserInfo(String id, String userid, String username, String status, String nickname, String realname, String headimgurl, String birthday, int sex, String wxOpenid, String unionid, String openid) {
            this.id = id;
            this.userid = userid;
            this.username = username;
            this.status = status;
            this.nickname = nickname;
            this.realname = realname;
            this.headimgurl = headimgurl;
            this.birthday = birthday;
            this.sex = sex;
            this.wxOpenid = wxOpenid;
            this.unionid = unionid;
            this.openid = openid;
        }

        public String getId() {
            return id;
        }

        public void setId(String id) {
            this.id = id;
        }

        public String getUserid() {
            return userid;
        }

        public void setUserid(String userid) {
            this.userid = userid;
        }

        public String getUsername() {
            return username;
        }

        public void setUsername(String username) {
            this.username = username;
        }

        public String getStatus() {
            return status;
        }

        public void setStatus(String status) {
            this.status = status;
        }

        public String getNickname() {
            return nickname;
        }

        public void setNickname(String nickname) {
            this.nickname = nickname;
        }

        public String getRealname() {
            return realname;
        }

        public void setRealname(String realname) {
            this.realname = realname;
        }

        public String getHeadimgurl() {
            return headimgurl;
        }

        public void setHeadimgurl(String headimgurl) {
            this.headimgurl = headimgurl;
        }

        public String getBirthday() {
            return birthday;
        }

        public void setBirthday(String birthday) {
            this.birthday = birthday;
        }

        public int getSex() {
            return sex;
        }

        public void setSex(int sex) {
            this.sex = sex;
        }

        public String getWxOpenid() {
            return wxOpenid;
        }

        public void setWxOpenid(String wxOpenid) {
            this.wxOpenid = wxOpenid;
        }

        public String getUnionid() {
            return unionid;
        }

        public void setUnionid(String unionid) {
            this.unionid = unionid;
        }

        public String getOpenid() {
            return openid;
        }

        public void setOpenid(String openid) {
            this.openid = openid;
        }
    }


    private void initTimePicker1() {//选择出生年月日
        //控制时间范围(如果不设置范围，则使用默认时间1900-2100年，此段代码可注释)
        //因为系统Calendar的月份是从0-11的,所以如果是调用Calendar的set方法来设置时间,月份的范围也要是从0-11
        Date curDate = new Date(System.currentTimeMillis());//获取当前时间
        SimpleDateFormat formatter_year = new SimpleDateFormat("yyyy ");
        String year_str = formatter_year.format(curDate);
        int year_int = (int) Double.parseDouble(year_str);


        SimpleDateFormat formatter_mouth = new SimpleDateFormat("MM ");
        String mouth_str = formatter_mouth.format(curDate);
        int mouth_int = (int) Double.parseDouble(mouth_str);

        SimpleDateFormat formatter_day = new SimpleDateFormat("dd ");
        String day_str = formatter_day.format(curDate);
        int day_int = (int) Double.parseDouble(day_str);


        Calendar selectedDate = Calendar.getInstance();//系统当前时间
        Calendar startDate = Calendar.getInstance();
        startDate.set(1900, 0, 1);
        Calendar endDate = Calendar.getInstance();
        endDate.set(year_int, mouth_int - 1, day_int);

        //时间选择器
        TimePickerView build = new TimePickerView.Builder(this, new TimePickerView.OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {//选中事件回调
                // 这里回调过来的v,就是show()方法里面所添加的 View 参数，如果show的时候没有添加参数，v则为null
                birthday = getTime(date);
                tvDateOfBirth.setText(getTime(date));
            }
        })
                .setType(new boolean[]{true, true, true, false, false, false}) //年月日时分秒 的显示与否，不设置则默认全部显示
                .setLabel("年", "月", "日", "", "", "")//默认设置为年月日时分秒
                .isCenterLabel(false)
                .setDividerColor(Color.RED)
                .setTextColorCenter(Color.RED)//设置选中项的颜色
                .setTextColorOut(Color.BLUE)//设置没有被选中项的颜色
                .setContentSize(21)
                .setDate(selectedDate)
                .setLineSpacingMultiplier(1.2f)
                .setTextXOffset(-10, 0, 10, 0, 0, 0)//设置X轴倾斜角度[ -90 , 90°]
                .setRangDate(startDate, endDate)
//                .setBackgroundId(0x00FFFFFF) //设置外部遮罩颜色
                .setDecorView(null)
                .build();
        build.show();
    }

    private String getTime(Date date) {//可根据需要自行截取数据显示
//        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        return format.format(date);
    }
}
