package com.sheep.gamegroup.module.login.fragments;

import android.app.Dialog;
import android.content.Intent;
import android.net.Uri;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.bumptech.glide.Glide;
import com.sheep.gamegroup.dateview.DatePickerDialog;
import com.sheep.gamegroup.model.entity.BaseMessage;
import com.sheep.gamegroup.model.entity.LoginEntity;
import com.sheep.gamegroup.model.util.SheepSubscriber;
import com.sheep.gamegroup.module.login.controller.LoginController;
import com.sheep.gamegroup.util.DataUtil;
import com.sheep.gamegroup.util.GlideImageLoader;
import com.sheep.gamegroup.util.upfile.UpFileListener;
import com.sheep.gamegroup.util.upfile.UpFileUtils;
import com.sheep.jiuyan.samllsheep.R;
import com.sheep.jiuyan.samllsheep.SheepApp;
import com.sheep.jiuyan.samllsheep.base.BaseFragment;
import com.sheep.jiuyan.samllsheep.utils.G;
import com.yalantis.ucrop.UCrop;

import java.io.File;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import me.iwf.photopicker.PhotoPicker;

import static android.app.Activity.RESULT_OK;


public class EditUserInfoFgt extends BaseFragment {

    private LoginEntity mLoginResult;
    private LoginController mController;

    @BindView(R.id.avatar_view)
    ImageView avaterView;
    @BindView(R.id.nickname_box)
    EditText nickNameBox;
    @BindView(R.id.birthday_box)
    TextView birthdayBox;
    @BindView(R.id.gender_box)
    RadioGroup genderRadio;

    private String newAvatar;

    public EditUserInfoFgt() {
        // Required empty public constructor
    }

    public static EditUserInfoFgt newInstance(LoginEntity entity, LoginController controller) {
        EditUserInfoFgt fgt = new EditUserInfoFgt();
        fgt.mLoginResult = entity;
        fgt.mController = controller;
        return fgt;
    }

    @Override
    public int getLayoutId() {
        return R.layout.fragment_edit_user_info;
    }

    @Override
    public void onViewCreated() {
        new Thread() {
            public void run() {
                Glide.get(SheepApp.getInstance()).clearDiskCache();
            }
        }.start();
        Glide.get(SheepApp.getInstance()).clearMemory();
        if (!TextUtils.isEmpty(mLoginResult.getUser().getAvatar())) {
            GlideImageLoader.circleImage(avaterView, mLoginResult.getUser().getAvatar());
        }
        if (!TextUtils.isEmpty(mLoginResult.getUser().getNickname())) {
            nickNameBox.setText(mLoginResult.getUser().getNickname());
        }
        if (mLoginResult.getUser().getGender() == 2) {
            genderRadio.check(R.id.female_radio);
        } else {
            genderRadio.check(R.id.male_radio);
        }
    }

    @OnClick(R.id.birthday_box)
    public void doSelectBirthday(View v) {
        DatePickerDialog.Builder builder = new DatePickerDialog.Builder(getActivity());
        builder.setOnDateSelectedListener(new DatePickerDialog.OnDateSelectedListener() {
            @Override
            public void onDateSelected(int[] dates) {
                birthdayBox.setText(dates[0] + "-" + (dates[1] > 9 ? dates[1] : ("0" + dates[1])) + "-" + (dates[2] > 9 ? dates[2] : ("0" + dates[2])));
            }

            @Override
            public void onCancel() {

            }
        }).setSelectYear(1989)
                .setSelectMonth(0)
                .setSelectDay(0);
        Dialog dateDialog = builder.create();
        dateDialog.show();
    }

    @OnClick(R.id.submit_btn)
    public void doSubmit() {
        if (TextUtils.isEmpty(nickNameBox.getText().toString().trim())) {
            G.shortToast("请输入昵称");
            return;
        }
        if (nickNameBox.getText().toString().trim().length() > 30) {
            G.shortToast("昵称长度不能超过30");
            return;
        }
        if (TextUtils.isEmpty(birthdayBox.getText().toString().trim())) {
            G.shortToast("请选择生日");
            return;
        }
        if (newAvatar != null) {
            UpFileUtils.upImage(new File(newAvatar), new UpFileListener() {
                @Override
                public void Success(String msg, int index) {
                    JSONObject json = JSONObject.parseObject(msg);
                    JSONObject data = json.getJSONObject("data");
                    mLoginResult.getUser().setAvatar(data.getString("url"));
                    submit();
                }

                @Override
                public void Progress(String progress, int index) {

                }

                @Override
                public void Failure(String err) {
                    G.shortToast("头像上传失败");
                }
            });
        } else {
            submit();
        }

    }

    private void submit() {
        JSONObject json = new JSONObject();
        json.put("nickname", nickNameBox.getText().toString().trim());
        json.put("avatar", mLoginResult.getUser().getAvatar());
        json.put("birthday", birthdayBox.getText().toString() + "T00:00:00Z");
        json.put("gender", genderRadio.getCheckedRadioButtonId() == R.id.male_radio ? 1 : 2);
        SheepApp.getInstance().getNetComponent().getApiService()
                .changeBaseInfo(json)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new SheepSubscriber<BaseMessage>(SheepApp.getInstance()) {

                    @Override
                    public void onNext(BaseMessage baseMessage) {
                        DataUtil.getInstance().setUserNickName(nickNameBox.getText().toString());
                        DataUtil.getInstance().setUserAvatar(newAvatar);
                        mController.whenEditedInfo(mLoginResult);
                    }

                    @Override
                    public void onError(BaseMessage baseMessage) {
                        if (baseMessage != null && !TextUtils.isEmpty(baseMessage.getMsg())) {
                            G.shortToast(baseMessage.getMsg());
                        } else {
                            G.shortToast("提交失败");
                        }
                    }
                });
    }

    @OnClick(R.id.avatar_view)
    public void doSelectAvatar(View v) {
        PhotoPicker.builder()
                .setPhotoCount(1)
                .setShowCamera(true)
                .setShowGif(false)
                .setPreviewEnabled(true)
                .start(getActivity(), PhotoPicker.REQUEST_CODE);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == PhotoPicker.REQUEST_CODE) {//拍照或者选择照片
                if (data != null) {
                    List<String> photos = data.getStringArrayListExtra(PhotoPicker.KEY_SELECTED_PHOTOS);
                    if (photos != null && !photos.isEmpty() && !TextUtils.isEmpty((newAvatar = photos.get(0)))) {
                        UCrop.of(Uri.fromFile(new File(newAvatar)),
                                Uri.fromFile(new File(new File(newAvatar).getParentFile(), "temp.png")))
                                .withAspectRatio(1, 1)
                                .withMaxResultSize(500, 500)
                                .start(getActivity());
                        GlideImageLoader.circleImage(avaterView, newAvatar);
                    }
                }
            } else if (requestCode == UCrop.REQUEST_CROP) {//裁剪
                Uri resultUri;
                if (data != null && (resultUri = UCrop.getOutput(data)) != null) {
                    String cropPath;
                    if (!TextUtils.isEmpty(cropPath = resultUri.getPath())) {
                        newAvatar = cropPath;
                        GlideImageLoader.circleImage(avaterView, newAvatar);
                    }

                }
            }
        }
    }

}
