package com.beanpodtech.allinone.fragment;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.RectF;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.fragment.app.Fragment;

import com.beanpodtech.allinone.BuildConfig;
import com.beanpodtech.allinone.activity.ChangePasswordActivity;
import com.beanpodtech.allinone.activity.HomeActivity;
import com.beanpodtech.allinone.activity.LoginActivity;
import com.beanpodtech.allinone.activity.MyAccountActivity;
import com.beanpodtech.allinone.activity.RecordActivity;
import com.beanpodtech.allinone.R;
import com.beanpodtech.allinone.bean.Signout;
import com.beanpodtech.allinone.http.UrlConfig;
import com.beanpodtech.allinone.utils.BoxUtil;
import com.beanpodtech.allinone.utils.Contants;
import com.beanpodtech.allinone.utils.OkGoUtil;
import com.beanpodtech.allinone.utils.SpUtil;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Response;
import com.open.androidtvwidget.bridge.EffectNoDrawBridge;
import com.open.androidtvwidget.view.FrameMainLayout;
import com.open.androidtvwidget.view.MainUpView;
import com.open.androidtvwidget.view.ReflectItemView;
import com.tencent.bugly.beta.Beta;

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

import okhttp3.MediaType;
import okhttp3.RequestBody;

public class PersonalCenterFragment extends Fragment {
    private TextView Myaccount, LearningRecord, SourceSettings, Feedback, changePassword, ChangeBackground, APPdownload, SignOut;
    private Drawable drawable;
    private ReflectItemView ll_account, ll_studyrecord, ll_feedback, ll_changeback, ll_changepsw, ll_logout, ll_downloadapp, ll_source;
    private View[] views;
    MainUpView mainUpView;
    FrameMainLayout frameMainLayout;
    private EffectNoDrawBridge mEffectNoDrawBridge;
    private View mOldView;
    private TextView tvVersion;

    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
        views = new View[]{ll_account, ll_studyrecord, ll_feedback, ll_changeback, ll_changepsw, ll_logout, ll_downloadapp, ll_source};
        View view = inflater.inflate(R.layout.activity_personalcenter, container, false);
        initView(view);
        initData();
        initListener();
        mainUpView = view.findViewById(R.id.mainUpView);
        initMoveBridge();
//        change_background.setOnClickListener(click);

        String verName = "";
        try {
            verName = getContext().getPackageManager().
                    getPackageInfo(getContext().getPackageName(), 0).versionName;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }

        if (BuildConfig.DEBUG) {
            tvVersion.setText("测试版 " + verName);
        } else {
            tvVersion.setText(verName);
        }

        return view;
    }

    private void initMoveBridge() {
        float density = getResources().getDisplayMetrics().density;
        mEffectNoDrawBridge = new EffectNoDrawBridge();
        mainUpView.setEffectBridge(mEffectNoDrawBridge);
        RectF rectF = new RectF(12 * density, 10 * density, 11 * density, 11 * density);
        mEffectNoDrawBridge.setDrawUpRectPadding(rectF);

    }

    private void clearFocus(View view) {
        for (int i = 0; i < views.length; i++) {
            mEffectNoDrawBridge.setUnFocusView(mOldView);
            mEffectNoDrawBridge.setVisibleWidget(true);
        }
        mOldView = view;
        mEffectNoDrawBridge.setVisibleWidget(false);


        //可以对某个view进行特殊处理
//            if (v.getId()==R.id.card_img) {
//                mEffectNoDrawBridge.setFocusView(v, 1.05f);
//            } else {
//                mEffectNoDrawBridge.setFocusView(v, 1.15f);
//            }

        mEffectNoDrawBridge.setFocusView(view, 1.1f);
        view.bringToFront();
    }

    private void initView(View view) {
        frameMainLayout = view.findViewById(R.id.frameMainLayout);
        ll_account = view.findViewById(R.id.ll_account);
        ll_studyrecord = view.findViewById(R.id.ll_studyrecord);
        ll_feedback = view.findViewById(R.id.ll_feedback);
        ll_changeback = view.findViewById(R.id.ll_changeback);
        ll_changepsw = view.findViewById(R.id.ll_changepsw);
        ll_logout = view.findViewById(R.id.ll_logout);
        ll_downloadapp = view.findViewById(R.id.ll_downloadapp);
        ll_source = view.findViewById(R.id.ll_source);


        Myaccount = view.findViewById(R.id.Myaccount);
        LearningRecord = view.findViewById(R.id.LearningRecord);
        SourceSettings = view.findViewById(R.id.SourceSettings);
        Feedback = view.findViewById(R.id.Feedback);
        changePassword = view.findViewById(R.id.changePassword);
        ChangeBackground = view.findViewById(R.id.ChangeBackground);
        APPdownload = view.findViewById(R.id.APPdownload);
        SignOut = view.findViewById(R.id.SignOut);
//        tvVersion = view.findViewById(R.id.tv_version);
        addIconForView();
    }

    private void addIconForView() {
        drawable = getResources().getDrawable(R.drawable.account);
        drawable.setBounds(0, 0, 75, 90);
        Myaccount.setCompoundDrawables(null, drawable, null, null);
        drawable = getResources().getDrawable(R.drawable.studay_icon);
        drawable.setBounds(0, 0, 80, 90);
        LearningRecord.setCompoundDrawables(null, drawable, null, null);
        drawable = getResources().getDrawable(R.drawable.check_version);
        drawable.setBounds(0, 0, 80, 80);
        SourceSettings.setCompoundDrawables(null, drawable, null, null);
        drawable = getResources().getDrawable(R.drawable.feedback_icon);
        drawable.setBounds(0, 0, 80, 80);
        Feedback.setCompoundDrawables(null, drawable, null, null);
        drawable = getResources().getDrawable(R.drawable.changepsw_icon);
        drawable.setBounds(0, 0, 80, 80);
        changePassword.setCompoundDrawables(null, drawable, null, null);
        drawable = getResources().getDrawable(R.drawable.changeback_icon);
        drawable.setBounds(0, 0, 80, 80);
        ChangeBackground.setCompoundDrawables(null, drawable, null, null);
        drawable = getResources().getDrawable(R.drawable.downloadapp_icon);
        drawable.setBounds(0, 0, 80, 80);
        APPdownload.setCompoundDrawables(null, drawable, null, null);
        drawable = getResources().getDrawable(R.drawable.logout_icon);
        drawable.setBounds(0, 0, 80, 80);
        SignOut.setCompoundDrawables(null, drawable, null, null);
    }

    private void initData() {

    }

    private void initListener() {
        frameMainLayout.setOnClickListener(click);
        ll_account.setOnClickListener(click);
        ll_studyrecord.setOnClickListener(click);
        ll_feedback.setOnClickListener(click);
        ll_changeback.setOnClickListener(click);
        ll_changepsw.setOnClickListener(click);
        ll_logout.setOnClickListener(click);
        ll_downloadapp.setOnClickListener(click);
        ll_source.setOnClickListener(click);
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);

    }

    View.OnClickListener click = new View.OnClickListener() {
        Intent intent;

        @Override
        public void onClick(View v) {
            boolean loginStatus = SpUtil.getInstace().getBoolean(Contants.LOGIN_STATE, true);
            if (v.getId() == R.id.ll_source) {
                Beta.checkAppUpgrade();
                clearFocus(ll_source);
                return;
            }
            if (loginStatus) {
                AlertDialog alertDialog = new AlertDialog.Builder(getActivity())
                        .setTitle("登录")
                        .setMessage("您还未登录,请前往登录")
                        .setPositiveButton("确定", new DialogInterface.OnClickListener() {//添加"Yes"按钮
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                Intent intent = new Intent(getActivity(), LoginActivity.class);
                                startActivityForResult(intent, 0X11);
                            }
                        })

                        .setNegativeButton("取消", new DialogInterface.OnClickListener() {//添加取消
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {

                            }
                        })
                        .create();
                alertDialog.show();
            } else {
                switch (v.getId()) {
                    case R.id.frameMainLayout:
                        mEffectNoDrawBridge.setUnFocusView(mOldView);
                        mEffectNoDrawBridge.setVisibleWidget(true);
                        break;
                    case R.id.ll_account:
                        MyAccountActivity.startActivity(getActivity(), null);
                        clearFocus(ll_account);
                        break;
                    case R.id.ll_studyrecord:
                        clearFocus(ll_studyrecord);
                        RecordActivity.startActivity(getActivity());
                        break;
                    case R.id.ll_feedback:
                        clearFocus(ll_feedback);
                        break;
                    case R.id.ll_changeback:
                        clearFocus(ll_changeback);
                        break;
                    case R.id.ll_changepsw:
                        intent = new Intent(getActivity(), ChangePasswordActivity.class);
                        startActivity(intent);
                        clearFocus(ll_changepsw);
                        break;
                    case R.id.ll_logout:
                        clearFocus(ll_logout);
                        AlertDialog alertDialog = new AlertDialog.Builder(getActivity())
                                .setTitle("退出登录")
                                .setPositiveButton("确定", new DialogInterface.OnClickListener() {//添加"Yes"按钮
                                    @Override
                                    public void onClick(DialogInterface dialogInterface, int i) {
                                        String userId = SpUtil.getInstace().getString(Contants.USER_ID, null);
                                        String boxId = BoxUtil.getDeviceSN();
                                        ;
                                        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json;charset=utf-8"), initJson(userId, boxId));
                                        OkGo.<Signout>post(UrlConfig.SIGN_OUT).upRequestBody(requestBody).execute(new OkGoUtil<Signout>(Signout.class) {
                                            @Override
                                            public void onSuccess(Response<Signout> response) {
                                                Signout body = response.body();
                                                if (body.getstatus() == 0) {
                                                    SpUtil.getInstace().clear();
                                                    getActivity().finish();
                                                    Intent intent = new Intent(getActivity(), HomeActivity.class);
                                                    startActivity(intent);
                                                    Toast.makeText(getActivity(), "退出登录成功", Toast.LENGTH_SHORT).show();
                                                } else if (body.getstatus() == -1) {
                                                    Toast.makeText(getActivity(), "退出登录失败", Toast.LENGTH_SHORT).show();
                                                }
                                            }
                                        });
                                    }
                                })
                                .setNegativeButton("取消", new DialogInterface.OnClickListener() {//添加取消
                                    @Override
                                    public void onClick(DialogInterface dialogInterface, int i) {
                                    }
                                })
                                .create();
                        alertDialog.show();
                        break;
                    case R.id.ll_downloadapp:
                        clearFocus(ll_downloadapp);
                        break;
                    case R.id.ll_source:
                        Beta.checkAppUpgrade();
                        clearFocus(ll_source);
                        break;

//                case R.id.ChangeBackground:
//                    intent = new Intent(getActivity(), ChangeBackgroundActivity.class);
//                    startActivity(intent);
//                    break;
//                case R.id.changePassword:
//
//                    break;
//                case R.id.SignOut:
//
//                    break;
                }
            }

        }
    };

    private String initJson(String userId, String boxId) {
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("userId", userId);
            jsonObject.put("boxId", boxId);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return jsonObject.toString();
    }
}
