package com.yidianling.user.mine;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.hardware.Camera;
import android.net.Uri;
import android.os.Build;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.View;
import android.widget.DatePicker;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.tbruyelle.rxpermissions2.RxPermissions;
import com.ydl.ydl_image.module.GlideApp;
import com.ydl.ydl_image.transform.GlideCircleTransform;
import com.ydl.ydlcommon.base.BaseActivity;
import com.ydl.ydlcommon.bean.StatusBarOptions;
import com.ydl.ydlcommon.data.http.RxUtils;
import com.ydl.ydlcommon.data.http.ThrowableConsumer;
import com.ydl.ydlcommon.modular.ModularServiceManager;
import com.ydl.ydlcommon.utils.FileUtils;
import com.ydl.ydlcommon.utils.PopUtils;
import com.ydl.ydlcommon.utils.remind.ToastHelper;
import com.ydl.ydlcommon.view.JumpTextView;
import com.ydl.ydlcommon.view.ListNoCancelDialog;
import com.ydl.ydlcommon.view.TitleBar;
import com.ydl.ydlcommon.view.dialog.ListDialog;
import com.yidianling.common.tools.ToastUtil;
import com.yidianling.im.api.service.IImService;
import com.yidianling.user.R;
import com.yidianling.user.UserHelper;
import com.yidianling.user.api.bean.UserResponseBean;
import com.yidianling.user.http.UserHttp;
import com.yidianling.user.http.UserHttpImpl;
import com.yidianling.user.http.request.HeadParam;
import com.yidianling.user.http.request.UserInfoParam;

import org.jetbrains.annotations.NotNull;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import de.greenrobot.event.EventBus;
import io.reactivex.android.schedulers.AndroidSchedulers;


/**
 * 个人资料
 * Created by softrice on 15/12/2.
 */
@Route(path = "/user/personInfo")
public class PersonalInfoActivity extends BaseActivity implements View.OnClickListener {

    public static final int REQUEST_NAME = 1;


    UserResponseBean.UserInfo userInfoData;

    private static final int REQUEST_IMAGE = 2;

    TitleBar tb_title;
    ImageView persion_head_iv;
    ImageView person_head_hint_iv;
    RelativeLayout persion_head_rel;
    JumpTextView jtv_nick;
    JumpTextView jtv_sex;
    JumpTextView jtv_birthday;
    JumpTextView jtv_marriage_state;
    JumpTextView jtv_career;
    JumpTextView jtv_jianjie;

    private ArrayList<String> mSelectPath = new ArrayList<>();
    List<String> name = new ArrayList<String>();
    DatePickerDialogFragment datePickerDialogFragment = new DatePickerDialogFragment();
    private PopupWindow popupWindow;

    private Uri imgUri;

    FileUtils fileUtils;
    private String head_dir;//目录
    private String head_path;//路径
    File head_filec;

    private RxPermissions rxPermissions;

    public static Intent newIntent(Activity activity) {
        return new Intent(activity, PersonalInfoActivity.class);
    }
    @NotNull
    @Override
    public StatusBarOptions getStatusViewOptions() {
        return new StatusBarOptions(true,true);
    }
    @Override
    protected int layoutResId() {
        return R.layout.user_mine_activity_personal_info;
    }

    @Override
    protected void initDataAndEvent() {
        tb_title = findViewById(R.id.tb_title);
        persion_head_iv = findViewById(R.id.persion_head_iv);
        person_head_hint_iv = findViewById(R.id.person_head_hint_iv);
        persion_head_rel = findViewById(R.id.persion_head_rel);
        jtv_nick = findViewById(R.id.jtv_nick);
        jtv_sex = findViewById(R.id.jtv_sex);
        jtv_birthday = findViewById(R.id.jtv_birthday);
        jtv_marriage_state = findViewById(R.id.jtv_marriage_state);
        jtv_career = findViewById(R.id.jtv_career);
        jtv_jianjie = findViewById(R.id.jtv_jianjie);
        userInfoData = UserHelper.INSTANCE.getUserInfo().getUserInfo();

        jtv_nick.setOnClickListener(this);
        jtv_sex.setOnClickListener(this);
        jtv_birthday.setOnClickListener(this);
        jtv_career.setOnClickListener(this);
        jtv_marriage_state.setOnClickListener(this);
        jtv_jianjie.setOnClickListener(this);
        persion_head_rel.setOnClickListener(this);
        init();
    }


    void init() {
        rxPermissions = new RxPermissions(this);
        tb_title.setRightImageListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow = PopUtils.showMoreItem(PersonalInfoActivity.this,
                        tb_title.getRootView(),
                        0,
                        0);
            }
        });
        tb_title.setRightImageIfShouldSee();

        setData();
//        mChooseSexDialog.setListener(this);
        datePickerDialogFragment.setDateChangedListener(new DatePicker.OnDateChangedListener() {
            @Override
            public void onDateChanged(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                monthOfYear++;
                updateInfo("birthday", year + "-" + monthOfYear + "-" + dayOfMonth);

            }
        });
        fileUtils = new FileUtils(this);
        head_dir = fileUtils.getStorageDirectory() + "/img/head_img/";
    }

    private void setData() {
        if (userInfoData == null || userInfoData == null)
            return;

        String head_url = UserHelper.INSTANCE.getUserInfo().getUserInfo().getHead();
        GlideApp.with(PersonalInfoActivity.this)
                .load(head_url)
                .override(100, 100)
                .transform(new GlideCircleTransform(PersonalInfoActivity.this))
                .error(R.drawable.platform_head_place_hold_pic)
                .into(persion_head_iv);
        String nick_name = UserHelper.INSTANCE.getUserInfo().getUserInfo().getNick_name();
        if (!TextUtils.isEmpty(nick_name))
            jtv_nick.setRightText(nick_name);
        else
            jtv_nick.setRightText("");

        if (userInfoData.getGender() == 1)
            jtv_sex.setRightText("男");
        else
            jtv_sex.setRightText("女");

        setCareer(userInfoData.getProfession());
        setMarriage(userInfoData.getMarriage());

        if (userInfoData.getProfession() == 0) {
            jtv_career.setRightText("请选择");
        }

        jtv_birthday.setRightText(userInfoData.getBirthday());
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.persion_head_rel) {
            rxPermissions.request(Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                    .subscribe(granted -> {
                        if (granted) {
                            List<String> name = new ArrayList<>();
                            name.add("相册");
                            name.add("拍照");
                            ListNoCancelDialog.Builder builders = new ListNoCancelDialog.Builder(PersonalInfoActivity.this, name, 0);
                            builders.SetOnItemClickLister(new ListNoCancelDialog.Builder.OnItemClickLister() {
                                @Override
                                public void onItemClick(Dialog dialog, View view, int position) {
                                    File file_dir = new File(head_dir);
                                    if (file_dir.exists()) {
                                        fileUtils.deleteAllFiles(file_dir);
                                        file_dir.mkdirs();
                                    }
                                    switch (position) {
                                        case 0://相册
                                            Intent intent1 = new Intent(Intent.ACTION_PICK, null);
                                            intent1.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
                                            startActivityForResult(intent1, 21001);
                                            dialog.dismiss();
                                            break;
                                        case 1://拍照
                                            head_path = head_dir + System.currentTimeMillis() + "hand_carmer.jpg";
                                            showCameraAction(21002, head_path);
                                            dialog.dismiss();
                                            break;
                                    }
                                }

                                @Override
                                public void onItemLongClick(Dialog dialog, View view, int position) {

                                }
                            });
                            if (!PersonalInfoActivity.this.isFinishing()) {
                                builders.create().show();
                            }
                        } else {
                            ToastUtil.toastLong(this, "缺少使用相机和读取存储权限，无法获取图片");
                        }
                    });
        } else if (id == R.id.jtv_nick) {//昵称
            Intent intent = new Intent(this, SetInfoActivity.class);
            intent.putExtra("mOldString", jtv_nick.getRightText());
            intent.putExtra("mTitle", "修改昵称");
            startActivityForResult(intent, REQUEST_NAME);
        } else if (id == R.id.jtv_sex) {//性别
            List<String> sexs = new ArrayList<String>();
            sexs.add("男");
            sexs.add("女");
            ListNoCancelDialog.Builder builder1 = new ListNoCancelDialog.Builder(PersonalInfoActivity.this, sexs, 0);
            builder1.SetOnItemClickLister(new ListNoCancelDialog.Builder.OnItemClickLister() {
                @Override
                public void onItemClick(Dialog dialog, View view, int position) {
                    switch (position) {
                        case 0:
                            if (userInfoData != null && userInfoData.getGender() == 1) {

                            } else {
                                updateInfo("gender", "1");
                            }
                            dialog.dismiss();
                            break;
                        case 1:
                            if (userInfoData != null && userInfoData.getGender() == 2) {

                            } else {
                                updateInfo("gender", "2");
                            }
                            dialog.dismiss();
                            break;
                    }
                }

                @Override
                public void onItemLongClick(Dialog dialog, View view, int position) {

                }
            });
            builder1.create().show();
        } else if (id == R.id.jtv_birthday) {//生日
            datePickerDialogFragment.show(getFragmentManager(), datePickerDialogFragment.getClass().getName());
        } else if (id == R.id.jtv_career) {//职业
            List<String> jobs = new ArrayList<String>();
            jobs.add("学生党");
            jobs.add("上班族");
            jobs.add("全职父母");
            jobs.add("商人");
            ListDialog.Builder builderj = new ListDialog.Builder(PersonalInfoActivity.this, jobs, 0);
            builderj.SetLastStr("取消");
            builderj.SetLastButton("取消", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                }
            });
            builderj.SetOnItemClickLister(new ListDialog.Builder.OnItemClickLister() {
                @Override
                public void onItemClick(Dialog dialog, View view, int position) {
                    switch (position) {
                        case 0:
                        case 1:
                        case 2:
                        case 3:
                            updateInfo("profession", String.valueOf(position + 1));
                            dialog.dismiss();
                            break;
                    }
                }

                @Override
                public void onItemLongClick(Dialog dialog, View view, int position) {

                }
            });
            builderj.create().show();
        } else if (id == R.id.jtv_marriage_state) {//婚姻状态
            List<String> marriages = new ArrayList<String>();
            marriages.add("单身");
            marriages.add("恋爱中");
            marriages.add("已婚");
            ListDialog.Builder builderm = new ListDialog.Builder(PersonalInfoActivity.this, marriages, 0);
            builderm.SetLastStr("取消");
            builderm.SetLastButton("取消", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                }
            });
            builderm.SetOnItemClickLister(new ListDialog.Builder.OnItemClickLister() {
                @Override
                public void onItemClick(Dialog dialog, View view, int position) {
                    switch (position) {
                        case 0:
                        case 1:
                        case 2:
                            updateInfo("marriage", String.valueOf(position + 1));
                            dialog.dismiss();
                            break;
                    }
                }

                @Override
                public void onItemLongClick(Dialog dialog, View view, int position) {

                }
            });
            builderm.create().show();
        } else if (id == R.id.jtv_jianjie) {//个人简介
            Intent intent1 = new Intent(this, PersonalDesActivity.class);
            startActivity(intent1);
        }
    }


    /**
     * 调用系统拍照
     */
    private void showCameraAction(int type_code, String file_path) {

        File file_dir = new File(head_dir);
        if (file_dir.exists()) {
            fileUtils.deleteAllFiles(file_dir);
        }
        file_dir.mkdirs();
        head_filec = new File(file_path);
//            fileUtils.isFilleExit(head_dir);
//            BigHeadFile = new File(file_path);
//            try {
//                if (BigHeadFile.exists()) {
//                    BigHeadFile.delete();
//                }
//            } catch (Exception e) {
//                e.printStackTrace();
//            }
        final Intent intent = new Intent();
        final Intent intent_camera = getPackageManager()
                .getLaunchIntentForPackage("com.android.camera");
        if (intent_camera != null) {
            intent.setPackage("com.android.camera");
        }
        intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
//            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        /*获取当前系统的android版本号*/
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
            intent.putExtra("android.intent.extras.CAMERA_FACING", Camera.CameraInfo.CAMERA_FACING_FRONT); // 调用前置摄像头
            intent.putExtra("autofocus", true); // 自动对焦
            intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(head_filec));
            intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
            startActivityForResult(intent, type_code);
        } else {
            try {
                head_filec.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
            Uri uri = fileUtils.getImageContentUri(PersonalInfoActivity.this, new File(file_path));
            intent.putExtra("android.intent.extras.CAMERA_FACING", Camera.CameraInfo.CAMERA_FACING_FRONT); // 调用前置摄像头
            intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
            intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
            intent.putExtra("autofocus", true); // 自动对焦
            startActivityForResult(intent, type_code);
        }

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case 21001:
                    if (data != null) {
                        imgUri = data.getData();
                        startPhotoZoom(data.getData());
                    }
                    break;

                case 21002:
                    imgUri = null;
                    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
                        if (head_filec.exists()) {
                            startPhotoZoom(Uri.fromFile(head_filec));
                        }
                    } else {
                        Uri uri = fileUtils.getImageContentUri(PersonalInfoActivity.this, head_filec);
                        if (uri != null) {
                            startPhotoZoom(uri);
                        }

                    }
                    break;

                case 21003:
                    if (imgUri != null) {
                        String path = fileUtils.getPathByUri4kitkat(this, imgUri);
                        Bitmap bitmap = BitmapFactory.decodeFile(path);
                        bitmap = fileUtils.getZoomImage(bitmap, 200);
                        try {
                            File out_file = fileUtils.SaveBitmap(bitmap, path);
                            uploadImage(out_file.getAbsolutePath(), 1001);
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        imgUri = null;
                    }

                    break;

                case REQUEST_NAME: {
                    updateInfo("nickName", SetInfoActivity.getInput(data));
                    break;
                }
            }
        }
    }

    /**
     * 裁剪图片方法实现
     */
    public void startPhotoZoom(Uri uri) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        // 设置裁剪
        intent.putExtra("crop", "true");
        // 图片拉伸，就不会出现黑框了
        intent.putExtra("scaleUpIfNeeded", true);
        //宽高的比例
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        //裁剪图片宽高
        intent.putExtra("outputX", 200);
        intent.putExtra("outputY", 200);
        if (imgUri != null) {
            // 输出路径
            fileUtils.isFilleExit(head_dir);
            imgUri = Uri.fromFile(new File(head_dir + System.currentTimeMillis() + "my_head1.jpg"));
            intent.putExtra(MediaStore.EXTRA_OUTPUT, imgUri);
            intent.putExtra("outputFormat", Bitmap.CompressFormat.PNG.toString());
            // return-data=true传递的为缩略图，小米手机默认传递大图，所以会导致onActivityResult调用失败
            intent.putExtra("return-data", false);
            // 是否需要人脸识别
//        intent.putExtra("noFaceDetection", false);
            startActivityForResult(intent, 21003);
        } else {
            File bigfile = new File(head_path);
            imgUri = Uri.fromFile(bigfile);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, imgUri);
            intent.putExtra("outputFormat", Bitmap.CompressFormat.PNG.toString());
            // return-data=true传递的为缩略图，小米手机默认传递大图，所以会导致onActivityResult调用失败
            intent.putExtra("return-data", false);
            // 是否需要人脸识别
            intent.putExtra("noFaceDetection", false);
            startActivityForResult(intent, 21003);
        }

    }


    @SuppressLint("CheckResult")
    void updateInfo(final String changType, final String value) {
        showProgressDialog("保存中...");

        UserHttp userHttp = UserHttpImpl.Companion.getInstance();

        userHttp.setUserInfo(new UserInfoParam(changType, value))
                .compose(com.ydl.ydlcommon.data.http.RxUtils.resultData())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(o -> {
                    jtv_sex.postDelayed(() -> {
                        dismissProgressDialog();
                        ToastUtil.toastShort("保存成功");
                    }, 500);
                    UserResponseBean.UserInfo userInfo = UserHelper.INSTANCE.getUserInfo().getUserInfo();
                    switch (changType) {
                        case "gender":
                            switch (value) {
                                case "1":
                                    jtv_sex.setRightText("男");
                                    userInfo.setGender(1);
                                    break;
                                case "2":
                                    jtv_sex.setRightText("女");
                                    userInfo.setGender(2);
                                    break;
                            }
                            break;
                        case "nickName":
                            jtv_nick.setRightText(value);
                            userInfo.setNick_name(value);
                            //更新用户昵称到云信
                            try {
                                ModularServiceManager.INSTANCE.provide(IImService.class).updateUserName(value);
                            }catch (Exception e) {}
                            break;
                        case "profession":
                            setCareer(Integer.valueOf(value));
                            userInfo.setProfession(Integer.valueOf(value));
                            break;
                        case "marriage":
                            setMarriage(Integer.valueOf(value));
                            userInfo.setMarriage(Integer.valueOf(value));
                            break;
                        case "birthday":
                            jtv_birthday.setRightText(value);
                            userInfo.setBirthday(value);
                            break;
                        case "homeBg":
                            //封面背景
                            userInfo.setHome_bg(value);
                            break;
                        case "home_desc":
                            //简介
                            userInfo.setDescription(value);
                            break;
                    }
                    EventBus.getDefault().post(userInfoData);
                }, new ThrowableConsumer() {
                    @Override
                    public void accept(@NotNull String msg) {
                        ToastHelper.Companion.show(msg);
                    }
                });

    }


    /**
     * 上传图片
     */
    @SuppressLint("CheckResult")
    void uploadImage(final String path, final int requestCode) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                showProgressDialog("保存中...");
            }
        });

        UserHttp userHttp = UserHttpImpl.Companion.getInstance();
        userHttp.uploadHead(new HeadParam(new File(path)))
                .compose(RxUtils.resultData())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(o -> {
                    Map map = (Map) o;
                    String head_url = (String) map.get("url");
                    userInfoData.setHead(head_url);
                    // 跟新本地云信数据库信息
                    try {
                        ModularServiceManager.INSTANCE.provide(IImService.class).updateUserHead(userInfoData.getHead());
                    }catch (Exception e) {}
                    UserResponseBean.UserInfo userInfo = UserHelper.INSTANCE.getUserInfo().getUserInfo();
                    if (userInfo != null) {
                        userInfo.setHead(head_url);
                    }


                    UserChangeEvent changeEvent = new UserChangeEvent(true);
                    EventBus.getDefault().post(changeEvent);
                    EventBus.getDefault().post(userInfoData);
                    if (head_url != null && !"".equals(head_url)) {
                        GlideApp.with(PersonalInfoActivity.this)
                                .load(userInfoData.getHead())
                                .override(100, 100)
                                .transform(new GlideCircleTransform(PersonalInfoActivity.this))
                                .error(R.drawable.platform_head_place_hold_pic)
                                .into(persion_head_iv);
                    } else {
                        GlideApp.with(PersonalInfoActivity.this)
                                .load(R.drawable.platform_head_place_hold_pic)
                                .transform(new GlideCircleTransform(PersonalInfoActivity.this))
                                .into(persion_head_iv);
                    }
                }, new ThrowableConsumer() {
                    @Override
                    public void accept(@NotNull String msg) {
                        ToastHelper.Companion.show(msg);
                        dismissProgressDialog();
                    }
                });

    }


    private void setCareer(int select) {
        switch (select) {
            case 0:
                jtv_career.setRightText("请选择");
                break;
            case 1:
                jtv_career.setRightText("学生党");
                break;
            case 2:
                jtv_career.setRightText("上班族");
                break;
            case 3:
                jtv_career.setRightText("全职父母");
                break;
            case 4:
                jtv_career.setRightText("商人");
                break;
        }
    }

    private void setMarriage(int select) {
        switch (select) {
            case 0:
                jtv_marriage_state.setRightText("请选择");
                break;
            case 1:
                jtv_marriage_state.setRightText("单身");
                break;
            case 2:
                jtv_marriage_state.setRightText("恋爱中");
                break;
            case 3:
                jtv_marriage_state.setRightText("已婚");
                break;

        }
    }

}
