package com.example.cloudmusic.fragment;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.viewpager.widget.ViewPager;

import com.bumptech.glide.Glide;
import com.example.cloudmusic.been.MineBeen;
import com.example.cloudmusic.R;
import com.example.cloudmusic.adapter.ViewPagerAdapter;
import com.example.cloudmusic.utils.OkHttpUtil;
import com.google.android.material.tabs.TabLayout;

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

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Response;

public class MineFragment extends Fragment {

    private OkHttpUtil util;
    private View root;
    private TextView login;
    private ImageView title;
    private MineBeen been;
    private Handler mHandler;
    private SharedPreferences sp;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        root = inflater.inflate(R.layout.fragment_mine, container, false);
        sp = getActivity().getPreferences(Context.MODE_PRIVATE);
        initUI();
        initLogin();

        ViewPager viewPager = root.findViewById(R.id.mine_vp);
        ViewPagerAdapter adapter = new ViewPagerAdapter(getActivity().getSupportFragmentManager());
        TabLayout tabs = root.findViewById(R.id.tabs);
        tabs.setupWithViewPager(viewPager);
        viewPager.setAdapter(adapter);
        return root;
    }

    @SuppressLint("HandlerLeak")
    private void initUI() {
        login = root.findViewById(R.id.mine_login);
        TextView login_no = root.findViewById(R.id.mine_login_no);
        title = root.findViewById(R.id.mine_title_no);
        TextView follows = root.findViewById(R.id.mine_follow);
        TextView followeds = root.findViewById(R.id.mine_followeds);
        TextView level = root.findViewById(R.id.mine_level);
        login.setOnClickListener(v -> {

        });

        mHandler = new Handler() {
            @SuppressLint("SetTextI18n")
            @Override
            public void handleMessage(@NonNull Message msg) {
                super.handleMessage(msg);
                switch (msg.what) {
                    case 1:
                        been = (MineBeen) msg.obj;
                        been.toString();
                        login.setText(been.getName());
                        Glide.with(root)
                                .load(been.getPeopleImg())
                                .placeholder(R.drawable.cloudmusic_white)
                                .error(R.drawable.cloudmusic_white)
                                .into(title);
                        initData();
                        break;
                    case 2:
                        follows.setText(been.getFollows() + " 关注");
                        followeds.setText(been.getFolloweds() + " 粉丝");
                        level.setText("Lv." + been.getLevel() + " 等级");

                }
            }
        };
    }

    private void initLogin() {
        util = new OkHttpUtil();
        util.sendGetRequest("http://192.168.86.158:3000/login/cellphone?phone=19138688251&password=12345678i", new OkHttpUtil.OkhttpInterface() {
            @Override
            public void success(Call call, Response response) {
                //   Toast.makeText(root.getContext(), "登录成功", Toast.LENGTH_SHORT).show();
                try {
                    String string = response.body().string();
                    JSONObject object = new JSONObject(string);
                    JSONObject account = object.optJSONObject("profile");
                    MineBeen been = new MineBeen();
                    if (account != null) {
                        String peopleImg = account.optString("avatarUrl");
                        String backgroundImg = account.optString("backgroundUrl");
                        String name = account.optString("nickname");
                        String id = account.optString("userId");
                        been.setBackgroundImg(backgroundImg);
                        been.setPeopleImg(peopleImg);
                        been.setName(name);
                        been.setId(id);
                        SharedPreferences.Editor edit = sp.edit();
                        edit.putString("userId", id);
                        edit.apply();
                        Message msg = new Message();
                        msg.what = 1;
                        msg.obj = been;
                        mHandler.sendMessage(msg);
                    }
                } catch (IOException | JSONException e) {
                    e.printStackTrace();
                }

            }

            @Override
            public void failure(Call call, IOException e) {

            }
        });
    }

    private void initData() {
        util.sendGetRequest("http://192.168.86.158:3000/user/detail?uid=" + been.getId(), new OkHttpUtil.OkhttpInterface() {
            @Override
            public void success(Call call, Response response) {
                try {
                    String body = response.body().string();
                    JSONObject object = new JSONObject(body);
                    String level = object.optString("level");
                    JSONObject json = object.optJSONObject("profile");
                    String follows = json.optString("follows");
                    String followeds = json.optString("followeds");
                    been.setFollows(follows);
                    been.setFolloweds(followeds);
                    been.setLevel(level);
                    Message msg = new Message();
                    msg.what = 2;
                    mHandler.sendMessage(msg);

                } catch (IOException | JSONException e) {
                    e.printStackTrace();
                }

            }

            @Override
            public void failure(Call call, IOException e) {
                System.out.println("失败了");
            }
        });
    }


}