package com.rehome.meetingbook.ui.activity;


import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.drawable.Drawable;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import com.rehome.meetingbook.R;
import com.rehome.meetingbook.base.BaseActivity2;
import com.rehome.meetingbook.bean.MeetingBookBean;
import com.rehome.meetingbook.contans.Contans;
import com.rehome.meetingbook.databinding.ActivityLoginBinding;
import com.rehome.meetingbook.utils.ControllerActivity;
import com.rehome.meetingbook.utils.GsonUtils;
import com.rehome.meetingbook.utils.HttpListener;
import com.rehome.meetingbook.utils.NoProgresshttpUtils;
import com.rehome.meetingbook.weiget.CustomLoadingDialog;
import com.yolanda.nohttp.NoHttp;
import com.yolanda.nohttp.RequestMethod;
import com.yolanda.nohttp.rest.Request;
import com.yolanda.nohttp.rest.Response;
import java.util.HashMap;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;
import androidx.activity.result.ActivityResult;
import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.appcompat.widget.Toolbar;
import androidx.core.content.ContextCompat;



/**
 * Create By HuangWenFei
 * 创建日期：2022-11-29 10:44
 * 描述：登录界面
 */
public class LoginActivity extends BaseActivity2<ActivityLoginBinding> {

    private long exitTime = 0;
    //private String meetingRoomName = "报告厅";
    //private String meetingRoomName = "3楼多媒体会议室";
    //private String meetingRoomName = "302 #2会议室"; //id=5




    //private String meetingRoomName = "105 报告厅";  //id=1
    private String meetingRoomName = "303 多功能会议室";  //id=3



    private CustomLoadingDialog customDialog;
    private String xm;

    //定时器
    private Timer timer;


    private final ActivityResultLauncher<Intent> mAppointmentSearchStartActivityForResult = registerForActivityResult(
            new ActivityResultContracts.StartActivityForResult(),
            new ActivityResultCallback<ActivityResult>() {
                @Override
                public void onActivityResult(ActivityResult result) {
                    // 处理 result
//                    Intent data = result.getData();
//                    if (data != null) {
//                        String idCardNo = data.getStringExtra("sfzh");
//                        if (idCardNo != null) {
//                            Intent intent = new Intent();
//                            intent.setClass(LoginActivity.this, AppointmentListActivity.class);
//                            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
//                            intent.putExtra("idCardNo", idCardNo);
//                            startActivity(intent);
//                        }
//                    }
                }
            }
    );


    //隐藏
    @Override
    protected void initView() {

        getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
        binding.tvVersion.setText("版本号:" + getVersionName());


        binding.llCloseKey.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                hideKeyBoard(LoginActivity.this);
            }
        });


    }

    @Override
    protected void initData() {
        binding.tvRoomTitle.setText("欢迎使用" + meetingRoomName);
        getMeetingRoomBookData();
    }

    @Override
    protected ActivityLoginBinding getBinding() {
        return ActivityLoginBinding.inflate(LayoutInflater.from(this));
    }

    @Override
    protected Toolbar getToolbar() {
        return binding.toolbarView.toolbar;
    }


    public void setBack() {
        mToolbar.setNavigationIcon(R.mipmap.back);
        mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
    }

    public static void hideKeyBoard(Activity activity) {
        InputMethodManager imm = (InputMethodManager) activity.getSystemService(Activity.INPUT_METHOD_SERVICE);
        //Find the currently focused view, so we can grab the correct window token from it.
        View view = activity.getCurrentFocus();
        //If no view currently has focus, create a new one, just so we can grab a window token from it
        if (view == null) {
            view = new View(activity);
        }
        imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
    }

    @Override
    protected void onResume() {
        super.onResume();
        if(timer==null){
            try {
                timer = new Timer();
                timer.schedule(new TimerTask() {
                    public void run() {
                        getMeetingRoomBookData();
                    }
                }, 20000, 20000);
                // 设定指定的时间time,此处为10000毫秒
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void onDestroy() {
        if(timer!=null){
            timer.cancel();
        }
        super.onDestroy();
    }

    //身份证号码格式校验
    public boolean checkIdCardNoFormat(String idCardNo) {
        String reg = "^\\d{15}$|^\\d{17}[0-9Xx]$";
        return idCardNo.matches(reg);
    }


    // 按两次返回键退出程序
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK
                && event.getAction() == KeyEvent.ACTION_DOWN) {
            if ((System.currentTimeMillis() - exitTime) > 2000) {
                showToast("再按一次退出程序");
                exitTime = System.currentTimeMillis();
            } else {
                ControllerActivity.getAppManager().finishAllActivity();
                finish();
                System.exit(0);
                //NohttpUtils.getInstance().cancelAll();
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    /**
     * 获取版本名称:清单文件中
     *
     * @return 应用版本名称    返回null代表异常
     */
    private String getVersionName() {
        //1,包管理者对象packageManager
        PackageManager pm = getPackageManager();
        //2,从包的管理者对象中,获取指定包名的基本信息(版本名称,版本号),传0代表获取基本信息
        try {
            PackageInfo packageInfo = pm.getPackageInfo(getPackageName(), 0);
            //3,获取版本名称
            return packageInfo.versionName;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    public String getPhoneInfo(int id) {
        Map<String, Integer> param = new HashMap<>();
        param.put("id", id);
        String json = GsonUtils.GsonString(param);
        showLog(json);
        return json;
    }

    private void getMeetingRoomBookData() {
        int id = 1;
        if("105 报告厅".equals(meetingRoomName)){
            id=1;
        }
        if("303 多功能会议室".equals(meetingRoomName)){
            id=3;
        }

        String json = getPhoneInfo(id);
        String url = Contans.IP + Contans.GET_MEETING_STATUS;
        Request<String> request = NoHttp.createStringRequest(url, RequestMethod.POST);

        request.setDefineRequestBodyForJson(json);
        NoProgresshttpUtils.getInstance().add(0, request, callback);
        //NohttpUtils.getInstance().add(LoginActivity.this, 0, request, callback, true, true, "登录中...");
    }

    private HttpListener<String> callback = new HttpListener<String>() {
        @Override
        public void onSucceed(int what, Response<String> response) {
            String result = response.get();
            showLog("-----getMeetingRoomBookData-----");
            showLog(result);
//            showToast(result);

            MeetingBookBean meetingBookBean = GsonUtils.GsonToBean(result, MeetingBookBean.class);

            if (meetingBookBean != null && meetingBookBean.isSuccess() && meetingBookBean.getData() != null) {
                MeetingBookBean.RowsBean rowsBean = meetingBookBean.getData();
                String status = rowsBean.getStatus();
                String startTime = rowsBean.getStartTime();
                String endTime = rowsBean.getEndTime();
                String name = rowsBean.getName();
                if(!TextUtils.isEmpty(name)){
                    binding.tvRoomTitle.setText("欢迎使用" + name);
                }
                if (status.equals("空闲")) {
                    Drawable drawable = ContextCompat.getDrawable(context, R.drawable.free);
                    if (drawable != null) {
                        // 使用drawable
                        binding.containerMeeting.setBackground(drawable);
                        binding.tvShowTime.setVisibility(View.INVISIBLE);
                        binding.tvMeetingTime.setVisibility(View.INVISIBLE);
                        binding.tvStatus.setText("空闲");
                    }
                }
                if (status.equals("会议中")) {
                    Drawable drawable = ContextCompat.getDrawable(context, R.drawable.busy);
                    if (drawable != null) {
                        // 使用drawable
                        binding.containerMeeting.setBackground(drawable);
                        binding.tvShowTime.setVisibility(View.VISIBLE);
                        binding.tvMeetingTime.setVisibility(View.VISIBLE);
                        binding.tvStatus.setText("使用中");
                        if(rowsBean.getStartTime()!=null&&rowsBean.getEndTime()!=null){
                            binding.tvMeetingTime.setText(rowsBean.getStartTime() + "~" + rowsBean.getEndTime());
                        }
                    }
                }
                if (status.equals("已预约")) {
                    Drawable drawable = ContextCompat.getDrawable(context, R.drawable.busy);
                    if (drawable != null) {
                        // 使用drawable
                        binding.containerMeeting.setBackground(drawable);
                        binding.tvShowTime.setVisibility(View.VISIBLE);
                        binding.tvMeetingTime.setVisibility(View.VISIBLE);
                        binding.tvStatus.setText("已预约");
                        if(rowsBean.getStartTime()!=null&&rowsBean.getEndTime()!=null){
                            binding.tvMeetingTime.setText(rowsBean.getStartTime() + "~" + rowsBean.getEndTime());
                        }
                    }
                }
            }
        }

        @Override
        public void onFailed(int what, Response<String> response) {
        }
    };


}