package com.halo.assistant.fragment.user;

import android.app.Dialog;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.lifecycle.ViewModelProviders;

import com.gh.common.util.DialogUtils;
import com.gh.gamecenter.common.constant.EntranceConsts;
import com.gh.gamecenter.common.utils.ImageUtils;
import com.gh.gamecenter.common.utils.PermissionHelper;
import com.gh.gamecenter.core.utils.RandomUtils;
import com.gh.gamecenter.R;
import com.gh.gamecenter.common.base.fragment.ToolbarFragment;
import com.gh.gamecenter.login.user.UserViewModel;
import com.lightgame.utils.Utils;
import com.zhihu.matisse.internal.utils.PathUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Locale;

/**
 * Created by CsHeng on 19/12/2017.
 * <p>
 * 选择用户头像
 */
public class SelectPortraitFragment extends ToolbarFragment {

    public final static int REQUEST_CROP_ICON = 12;
    public final static int REQUEST_MEDIA_ICON = 13;

    private UserViewModel mUserViewModel;

    private Dialog mLoadingDialog;

    private SharedPreferences mSharedPreferences;

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

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (data == null || getActivity() == null) {
            return;
        }

        switch (requestCode) {
            case REQUEST_MEDIA_ICON:
                Uri selectedImage = data.getData();
                if (selectedImage == null) {
                    return;
                }
                String picturePath = PathUtils.getPath(requireContext(), selectedImage);
                Utils.log("picturePath = " + picturePath);
                // 上传头像
                Intent intent = UserPortraitCropImageActivity.getIntent(getContext(),
                        picturePath, 1F, "我的光环(选择头像)");
                startActivityForResult(intent, REQUEST_CROP_ICON);
                break;
            case REQUEST_CROP_ICON:
                if (data != null && data.getExtras() != null) {
                    String url = data.getExtras().getString(EntranceConsts.KEY_URL);
                    change(url);
                }
                break;
        }
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setNavigationTitle(getString(R.string.title_select_portrait));

        mSharedPreferences = PreferenceManager.getDefaultSharedPreferences(getContext());

        UserViewModel.Factory factory = new UserViewModel.Factory(getActivity().getApplication());
        mUserViewModel = ViewModelProviders.of(this, factory).get(UserViewModel.class);
        mUserViewModel.getEditObsUserinfo().observe(this, userInfoEntity -> {
            if (mLoadingDialog != null) {
                mLoadingDialog.dismiss();
            }
            if (mLoadingDialog != null && userInfoEntity != null && userInfoEntity.getData() != null) {
                getActivity().finish();
            }
        });
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        view.findViewById(R.id.user_default_icon_1).setOnClickListener(this);
        view.findViewById(R.id.user_default_icon_2).setOnClickListener(this);
        view.findViewById(R.id.user_default_icon_3).setOnClickListener(this);
        view.findViewById(R.id.user_default_icon_4).setOnClickListener(this);
        view.findViewById(R.id.user_default_icon_5).setOnClickListener(this);
        view.findViewById(R.id.user_default_icon_6).setOnClickListener(this);
        view.findViewById(R.id.user_default_icon_7).setOnClickListener(this);
        view.findViewById(R.id.user_default_icon_8).setOnClickListener(this);
        view.findViewById(R.id.skip_media_store).setOnClickListener(this);

        ArrayList<ImageView> iconViewList = new ArrayList<>();
        iconViewList.add(view.findViewById(R.id.iconIv1));
        iconViewList.add(view.findViewById(R.id.iconIv2));
        iconViewList.add(view.findViewById(R.id.iconIv3));
        iconViewList.add(view.findViewById(R.id.iconIv4));
        iconViewList.add(view.findViewById(R.id.iconIv5));
        iconViewList.add(view.findViewById(R.id.iconIv6));
        iconViewList.add(view.findViewById(R.id.iconIv7));
        iconViewList.add(view.findViewById(R.id.iconIv8));

        for (int i = 0; i < iconViewList.size(); i++) {
            ImageUtils.getPicasso().load(getDefaultIconUrl(i + 1)).into(iconViewList.get(i));
        }

    }

    @Override
    public void onClick(View view) {
        int id = view.getId();
        if (id == R.id.user_default_icon_1) {
            postUserIcon(1);
        } else if (id == R.id.user_default_icon_2) {
            postUserIcon(2);
        } else if (id == R.id.user_default_icon_3) {
            postUserIcon(3);
        } else if (id == R.id.user_default_icon_4) {
            postUserIcon(4);
        } else if (id == R.id.user_default_icon_5) {
            postUserIcon(5);
        } else if (id == R.id.user_default_icon_6) {
            postUserIcon(6);
        } else if (id == R.id.user_default_icon_7) {
            postUserIcon(7);
        } else if (id == R.id.user_default_icon_8) {
            postUserIcon(8);
        } else if (id == R.id.skip_media_store) {
            PermissionHelper.checkStoragePermissionBeforeAction(requireContext(), this::startMediaStore);
        }
    }

    private void startMediaStore() {
        String iconCount = mSharedPreferences.getString("updateIconCount", null);
        if (!TextUtils.isEmpty(iconCount)) {
            long l = System.currentTimeMillis();
            SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd", Locale.CHINA);
            String time = format.format(new Date(l));

            JSONObject json;
            try {
                json = new JSONObject(iconCount);
                String lastTime = json.getString("time");
                if (lastTime.equals(time) && json.getInt("count") >= 2) {
                    toast("每天最多只能上传2次头像");
                    return;
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        try {
            startActivityForResult(intent, REQUEST_MEDIA_ICON);
        } catch (ActivityNotFoundException e) {
            Utils.toast(requireContext(), "找不到图片选择器");
        }
    }

    public void postUserIcon(int i) {
        postDefaultIcon(i);
    }

    public void postDefaultIcon(final int i) {
        String iconUrl = getDefaultIconUrl(i);

        //初始化热点名称
        String chars = "abcdefghijklmnopqrstuvwxyz";
        int[] randomArray = RandomUtils.getRandomArray(2, 25);

        String mySsid = "ghZS-";
        for (int j : randomArray) {
            mySsid = mySsid + chars.charAt(j);
        }
        mySsid = mySsid + i;
        mSharedPreferences.edit().putString("hotspotName", mySsid).apply();

        mSharedPreferences.edit().putInt("default_user_icon", i).apply();

        mSharedPreferences.edit().putBoolean("changeDefaultIcon", true).apply();

        change(iconUrl);
    }


    private void change(String url) {
        mLoadingDialog = DialogUtils.showWaitDialog(getActivity(), "正在修改信息...");
        mUserViewModel.changeUserInfo(url, UserViewModel.TYPE_PORTRAIT);
    }

    private String getDefaultIconUrl(int i) {
        switch (i) {
            case 2:
                return "https://image.ghzs666.com/pic/default_icon_2.png";
            case 3:
                return "https://image.ghzs666.com/pic/default_icon_3.png";
            case 4:
                return "https://image.ghzs666.com/pic/default_icon_4.png";
            case 5:
                return "https://image.ghzs666.com/pic/default_icon_5.png";
            case 6:
                return "https://image.ghzs666.com/pic/default_icon_6.png";
            case 7:
                return "https://image.ghzs666.com/pic/default_icon_7.png";
            case 8:
                return "https://image.ghzs666.com/pic/default_icon_8.png";
            case 1:
            default:
                return "https://image.ghzs666.com/pic/default_icon_1.png";
        }
    }

}
