package com.rv.rvmine.traveler;

import android.Manifest;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
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.image.round.RoundImageView;
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.base.presenter.PickerPresenter;
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.component.dialog.PickerDialog;
import com.rv.component.utils.CacheEnum;
import com.rv.component.utils.RvCache;
import com.rv.home.rv.module.ApiConfig;
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.rv.rvmine.view.DateTimeWheelDialog;
import com.yuyife.okgo.OkGoUtil;

import java.io.File;
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;
import pub.devrel.easypermissions.AppSettingsDialog;

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

    private final int TYPE_ALTER_NICK = 1006;

    @BindView(R2.id.iv_avatar)
    RoundImageView ivAvatar;
    @BindView(R2.id.tv_nickname)
    TextView tvNickname;
    @BindView(R2.id.tv_date_of_birth)
    TextView tvDateOfBirth;
    @BindView(R2.id.tv_sex)
    TextView tvSex;
    @BindView(R2.id.et_phone)
    EditText etPhone;
    private UserInfoBean.UserInfo info;
    private String ivAvatarUrl;
    public ProgressDialog dialog;

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

    private String birthday = "";
    private static final int SDK_AUTH_FLAG = 2;

    private boolean hasNickName;

    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("个人资料");
        tvNickname.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent in = new Intent(PersonalInformationActivity.this, AlterNickNameActivity.class);
                if (hasNickName) {
                    in.putExtra("nick", tvNickname.getText().toString().trim());
                }
                startActivityForResult(in, TYPE_ALTER_NICK);
            }
        });
        dialog = new ProgressDialog(this);
        info = ((UserInfoBean) RvCache.getInstance().get(CacheEnum.USER)).getData();
        if (info != null) {
            ivAvatarUrl = info.getHeadimgurl();

            GlideManager.getInstance(mActivity).loadImage(info.getHeadimgurl(), ivAvatar);
            if (!TextUtils.isEmpty(info.getNickname())) {
                hasNickName = true;
                tvNickname.setText(info.getNickname());
                tvNickname.setTextColor(getResources().getColor(R.color.colorMain));
            }
            if (!TextUtils.isEmpty(info.getBirthday())) {
                birthday = info.getBirthday();
                tvDateOfBirth.setText(birthday);
            }
            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());
            }
        }
    }

    @Override
    public void onShowResult(int requestType, BaseBean result) {
        switch (requestType) {
            case 0:
                ImageUploadBean bean = (ImageUploadBean) result;
                ivAvatarUrl = bean.getData();
                UserInfo userInfo = new UserInfo();
                userInfo.setHeadimgurl(ivAvatarUrl);
                upUserinfo(userInfo, true);
                break;
            case 1:
                RxBus.post(new UserInfoEvent());
                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");
        } else if (requestCode == TYPE_ALTER_NICK && resultCode == RESULT_OK) {
            if (data != null) {
                String nickName = data.getStringExtra("nick");
                if (!TextUtils.isEmpty(nickName)) {
                    hasNickName = true;
                    if (!nickName.equals(tvNickname.getText().toString().trim())) {
                        tvNickname.setText(nickName);
                        tvNickname.setTextColor(getResources().getColor(R.color.colorMain));
                        UserInfo userInfo = new UserInfo();
                        userInfo.setNickname(nickName);
                        upUserinfo(userInfo, false);
                    }
                }
            }
        }

    }

    @OnClick({R2.id.rl_item_avatar, R2.id.ll_item_date_of_birth, R2.id.ll_item_sex})
    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();
        }
    }

    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 || id == R.id.rl_man) {
                            if (sex != 1) {
                                sex = 1;
                                helper.setChecked(R.id.cb_girl, false);
                                tvSex.setText("男");
                                upUserinfo(new UserInfo(), true);
                            }
                        } else if (id == R.id.cb_girl || id == R.id.rl_woman) {
                            if (sex != 0) {
                                sex = 0;
                                helper.setChecked(R.id.cb_man, false);
                                tvSex.setText("女");
                                upUserinfo(new UserInfo(), true);
                            }
                        }
                        dismiss();
                    }
                }, R.id.cb_man, R.id.cb_girl, R.id.rl_man, R.id.rl_woman);
            }
        }.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.M) {
            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 {
                        new AppSettingsDialog.Builder(PersonalInformationActivity.this).
                                setTitle("需要获取相机权限、存储权限")
                                .setRationale("如果没有此权限，此应用程序可能无法正常工作,是否打开设置修改该应用权限")
                                .build().show();
                    }
                }
            });
        } 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   uploadVideo
//        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(UserInfo userInfo, boolean isShow) {
        if (userInfo != null) {
            userInfo.setSex(sex);
            userInfo.setUserid(info.getUserid() + "");
            userInfo.setId(info.getId() + "");
            mPresenter.postBodyData(RvFrameConfig.ADMIN_POST, 1, ApiConfig.HTTP_URL_UPUSER_EDIT, BaseBean.class, userInfo, getHeadMap(), isShow);
        }

    }

    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 onDestroy() {
        super.onDestroy();
    }

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

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }


    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;
        private String aliCode;

        public UserInfo() {
        }

        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, String aliCode) {
            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;
            this.aliCode = aliCode;
        }

        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;
        }

        public String getAliCode() {
            return aliCode;
        }

        public void setAliCode(String aliCode) {
            this.aliCode = aliCode;
        }
    }

    private DateTimeWheelDialog dateTimeWheelDialog = null;

    private void initTimePicker1() {
        if (dateTimeWheelDialog == null)
            dateTimeWheelDialog = createDialog();
        else
            dateTimeWheelDialog.show();
    }

    private DateTimeWheelDialog createDialog() {
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.YEAR, 1900);
        calendar.set(Calendar.MONTH, 0);
        calendar.set(Calendar.DAY_OF_MONTH, 1);
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        Date startDate = calendar.getTime();
        calendar = Calendar.getInstance();
        calendar.set(Calendar.YEAR, calendar.get(Calendar.YEAR) + 1);
        Date endDate = calendar.getTime();

        DateTimeWheelDialog dialog = new DateTimeWheelDialog(this);
        dialog.show();
        dialog.setTitle("选择时间");
        int config = DateTimeWheelDialog.SHOW_YEAR_MONTH;
        dialog.configShowUI(config);
        dialog.setOkListener(new DateTimeWheelDialog.OnClickCallBack() {
            @Override
            public boolean callBack(View v, int year, int month) {
                String newBirthDay;
                if (month >= 10) {
                    newBirthDay = year + "-" + month;
                } else {
                    newBirthDay = year + "-0" + month;
                }
                if (!newBirthDay.equals(birthday)) {
                    birthday = newBirthDay;
                    tvDateOfBirth.setText(birthday);
                    UserInfo userInfo = new UserInfo();
                    userInfo.setBirthday(birthday);
                    upUserinfo(userInfo, true);
                }
                return false;
            }
        });
        dialog.setDateArea(startDate, endDate, true);
        dialog.updateSelectedDate(birthday);
        return dialog;
    }

//    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
//
//            }
//        })
//                .setType(new boolean[]{true, true, true, false, false, false}) //年月日时分秒 的显示与否，不设置则默认全部显示
//                .setLabel("年", "月", "日", "", "", "")//默认设置为年月日时分秒
//                .isCenterLabel(false)
//                .setSubmitColor(getResources().getColor(R.color.colorMain))
//                .setCancelColor(getResources().getColor(R.color.colorMain))
//                .setDividerColor(getResources().getColor(R.color.gray_FFB74B))
//                .setTextColorCenter(getResources().getColor(R.color.colorMain))//设置选中项的颜色
//                .setTextColorOut(getResources().getColor(R.color.colorGray))//设置没有被选中项的颜色
//                .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);
//    }
}
