package com.beanpodtech.allinone.fragment;

import android.annotation.SuppressLint;
import android.app.Fragment;
import android.content.Context;
import android.content.Intent;
import android.graphics.RectF;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings;
import android.text.format.DateFormat;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;

import com.beanpodtech.allinone.activity.NativeAppActivity;
import com.beanpodtech.allinone.activity.StartpageActivity;
import com.beanpodtech.allinone.R;
import com.beanpodtech.allinone.utils.Contants;
import com.beanpodtech.allinone.utils.SpUtil;
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 java.util.Calendar;

public class CourseFragment extends Fragment {
    MainUpView mainUpView;
    TextView data, time, week;
    private View[] views;
    private EffectNoDrawBridge mEffectNoDrawBridge;
    public final static String TAG = "CourseFragment";
    String mWay;
    private View mOldView;
    LinearLayout layoutfather;
    FrameMainLayout frameMainLayout;
    private ReflectItemView picture_two, picture_four, home, mNativeAppLLayout, mSettingLLayout;
    private ImageButton mFileExplorerIBtn, mNetworkSettingIBtn, mWifiSettingIBtn;
    //在主线程里面处理消息并更新UI界面
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    long sysTime = System.currentTimeMillis();//获取系统时间
                    CharSequence sysDataStr = DateFormat.format("yyyy年MM月dd日", sysTime);//时间显示格式
                    CharSequence sysTimeStr = DateFormat.format(" hh:mm:ss", sysTime);//时间显示格式
                    data.setText(sysDataStr); //更新时间
                    time.setText(sysTimeStr);
                    final Calendar c = Calendar.getInstance();
                    mWay = String.valueOf(c.get(Calendar.DAY_OF_WEEK));
                    if ("1".equals(mWay)) {
                        mWay = "天";
                    } else if ("2".equals(mWay)) {
                        mWay = "一";
                    } else if ("3".equals(mWay)) {
                        mWay = "二";
                    } else if ("4".equals(mWay)) {
                        mWay = "三";
                    } else if ("5".equals(mWay)) {
                        mWay = "四";
                    } else if ("6".equals(mWay)) {
                        mWay = "五";
                    } else if ("7".equals(mWay)) {
                        mWay = "六";
                    }
                    week.setText("星期" + mWay);
                    break;
                default:
                    break;

            }
        }
    };
    private boolean loginStatus;

    @SuppressLint("WrongConstant")
    @RequiresApi(api = Build.VERSION_CODES.M)
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
        views = new View[]{home, picture_two, mNativeAppLLayout, picture_four, mSettingLLayout};
        View view = inflater.inflate(R.layout.course_fragment, container, false);
//------------------------------分割线  为了demo版   后续删除------------------------------------------//


        //------------------------------分割线  为了demo版   后续删除------------------------------------------//
        data = view.findViewById(R.id.date);
        time = view.findViewById(R.id.time);
        week = view.findViewById(R.id.week);
        initView(view);
        new TimeThread().start();
        mainUpView = view.findViewById(R.id.mainUpView);
        initMoveBridge();
        return view;

    }

    private void initMoveBridge() {
        float density = getResources().getDisplayMetrics().density;
//        ButterKnife.bind(getActivity());
        mEffectNoDrawBridge = new EffectNoDrawBridge();
        mainUpView.setEffectBridge(mEffectNoDrawBridge);
//        mEffectNoDrawBridge.setUpRectResource(R.drawable.white_light); // 设置移动边框图片.
        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);
        }
        if (view.getId() == R.id.home1) {
            mOldView = view;
            mEffectNoDrawBridge.setVisibleWidget(false);
            mEffectNoDrawBridge.setFocusView(view, 1.06f);
        } else {
            mOldView = view;
            mEffectNoDrawBridge.setVisibleWidget(false);
            mEffectNoDrawBridge.setFocusView(view, 1.08f);
            view.bringToFront();
        }
    }

    private void initView(View view) {
        if (null == view) {
            Log.e(TAG, "initView view is null");
            return;
        }
        home = view.findViewById(R.id.home1);
        picture_two = view.findViewById(R.id.picture_two);
        picture_four = view.findViewById(R.id.picture_four);
        mNativeAppLLayout = view.findViewById(R.id.ll_native_app);
        mSettingLLayout = view.findViewById(R.id.ll_system_settings);
        mFileExplorerIBtn = view.findViewById(R.id.iv_earphone);
        mNetworkSettingIBtn = view.findViewById(R.id.iv_wifi);
        mWifiSettingIBtn = view.findViewById(R.id.iv_setting);
        frameMainLayout = view.findViewById(R.id.FrameMainLayout);
        frameMainLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mEffectNoDrawBridge.setUnFocusView(mOldView);
                mEffectNoDrawBridge.setVisibleWidget(true);
            }
        });
        layoutfather = view.findViewById(R.id.layout_father);
        layoutfather.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mEffectNoDrawBridge.setUnFocusView(mOldView);
                mEffectNoDrawBridge.setVisibleWidget(true);
            }
        });
        mNativeAppLLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getActivity(), NativeAppActivity.class);
//                startActivity(intent);
//                Beta.checkAppUpgrade();
                clearFocus(mNativeAppLLayout);
            }
        });
        mSettingLLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(Settings.ACTION_SETTINGS);
                startActivity(intent);
                clearFocus(mSettingLLayout);

            }
        });
        mFileExplorerIBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
                intent.setType("*/*");
                intent.addCategory(Intent.CATEGORY_OPENABLE);
                startActivity(intent);
            }
        });
        mNetworkSettingIBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Beta.checkAppUpgrade();
//                Intent intent = new Intent(Settings.ACTION_WIFI_SETTINGS);
//                startActivity(intent);
            }
        });
        mWifiSettingIBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(Settings.ACTION_WIFI_SETTINGS);
                startActivity(intent);
            }
        });
        picture_two.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                clearFocus(picture_two);

            }
        });
        picture_four.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                clearFocus(picture_four);
                // TODO: 2020/6/23 退出登录
//                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();
            }
        });
        home.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                clearFocus(home);
                String userName = SpUtil.getInstace().getString(Contants.USER_NAME, null);
                if (userName == null) {
                    SpUtil.getInstace().save(Contants.LOGIN_STATE, true);

                }
                //----------------------------------------------------------------------------------//
//                loginStatus = SpUtil.getInstace().getBoolean(Contants.LOGIN_STATE, true);
//                if (loginStatus == true) {
//                    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);
//                                    startActivity(intent);
////                                    getActivity().finish();
//                                }
//                            })

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

                // } else {
                //     clearFocus(home);
                //     Bundle bundle = new Bundle();
                //     bundle.putCharSequence(Contants.CLASS_NAME, "终极预测");
                //     bundle.putCharSequence(Contants.CLASS_ID, "1");
                //     PlayvideoActivity.startActivity(getActivity(), bundle);
                // }

//                final SharedPreferences sharedPreferences = getActivity().getSharedPreferences("user", MODE_PRIVATE);
//                loginStatus = sharedPreferences.getBoolean("loginState", true);
//                if (loginStatus == true) {
////                    AlertDialog alertDialog = new AlertDialog.Builder(getActivity(), R.style.AppTheme)
////                            .setTitle("登录")
////                            .setMessage("您还未登录,请前往登录")
////                            .setPositiveButton("确定", new DialogInterface.OnClickListener() {//添加"Yes"按钮
////                                @Override
////                                public void onClick(DialogInterface dialogInterface, int i) {
//                                    getActivity().finish();
//                                    Intent intent = new Intent(getActivity(), LoginActivity.class);
//                                    startActivity(intent);
////                                }
////                            })
////
////                            .setNegativeButton("取消", new DialogInterface.OnClickListener() {//添加取消
////                                @Override
////                                public void onClick(DialogInterface dialogInterface, int i) {
////                                }
////                            })
////                            .create();
////                    alertDialog.show();
//
//                } else {
//                    //-----------------------------------------------------------------------------------//
//                    Intent intent = new Intent(getActivity(), PlayvideoActivity.class);
//                    Bundle bundle = new Bundle();
//                    bundle.putCharSequence("name", "课程");
//                    intent.putExtras(bundle);
//                    startActivity(intent);
//                Intent intent = new Intent(getActivity(), HomeActivity.class);
//                startActivity(intent);
//                Intent intent = new Intent(getActivity(), HomeActivity.class);
                Intent intent = new Intent(getActivity(), StartpageActivity.class);
                startActivity(intent);
//                Intent intent=new Intent(getActivity(), SystematicsActivity.class);
//                startActivity(intent);}
//                }
            }
        });
    }

    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();
    }

    class TimeThread extends Thread {
        @Override
        public void run() {
            do {
                try {
                    Thread.sleep(500);
                    Message msg = new Message();
                    msg.what = 1;  //消息(一个整型值)
                    mHandler.sendMessage(msg);// 每隔1秒发送一个msg给mHandler
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            } while (true);
        }
    }

    public DisplayMetrics getScreeenSize(Context context) {
        DisplayMetrics dm = context.getResources().getDisplayMetrics();

        int screenWidth = dm.widthPixels;    // 屏幕宽度
        int screenHeight = dm.heightPixels;    // 屏幕高度
        Toast.makeText(getActivity(), "w=" + screenWidth + "\nh=" + screenHeight, Toast.LENGTH_LONG).show();
        Log.i("TAG", "=====w=" + screenWidth + "\nh=" + screenHeight);
        return dm;
    }
}
