package com.sunzee.ui.fragment;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.IntentFilter;
import android.media.AudioManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.AppCompatCheckBox;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RelativeLayout;
import android.widget.SeekBar;

import com.orhanobut.hawk.Hawk;
import com.sunzee.R;
import com.sunzee.base.BaseApplication;
import com.sunzee.base.MvpFragment;
import com.sunzee.model.domain.Name;
import com.sunzee.model.message.NetMessageEvent;
import com.sunzee.mvp.other.OtherPresenter;
import com.sunzee.mvp.other.OtherView;
import com.sunzee.receiver.NetworkConnectChangedReceiver;
import com.sunzee.service.MyService;
import com.sunzee.ui.dialog.WifiDialog;
import com.sunzee.utils.ToastUtil;
import com.sunzee.utils.UiUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.CharArrayWriter;

/**
 * 其他页界面 fragment
 * 1.4G和wifi的切换的功能
 * 2.亮度
 * 3.音量
 * 4.机器联系人
 * 5.长按退出程序
 * 6.长按重启触摸屏。
 */
public class OtherFragment extends MvpFragment<OtherPresenter> implements OtherView, SeekBar.OnSeekBarChangeListener, View.OnClickListener {

    private SeekBar mSbLight;
    private SeekBar mSbVoice;
    private AudioManager am;
    private static final String TAG = "OtherFragment";
    private RadioButton mRbMobileNetWork;
    private RadioButton mRbWifi;
    private NetworkConnectChangedReceiver receiver;
    private RelativeLayout rlOther;
    private Button btnPlcContentUdate;
    private Button btnSquattingContentUdate;
    private EditText etPlcContent;
    private EditText etSquattingContent;
    private LinearLayout llCheckBox;
    private AppCompatCheckBox[] appCompatCheckBoxes;//存储动态创建的check，监听厕所
    private AppCompatCheckBox[] appCompatPeopleCheckBoxes;//存储动态创建的check，监听人体传感器
    private Button btnCheckUpdate;
    private boolean[] isSelectCheckBox;//厕所是否选中
    private boolean[] isSelectPeopleCheckbox;//人体传感器是否选中
    private LinearLayout llPeopleCheckBox;
    private Button btnPCheckUpdate;
    private EditText etCleanCountContent;
    private Button btnCleanCount;
    private EditText etRestorationcontract;
    private EditText etRestorationwayContacts;
    private Button btRrestorationcontractUpdate;
    private Button btnContractUpdate;
    private EditText etWayContacts;
    private EditText etContract;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View inflate = inflater.inflate(R.layout.fragment_other, container, false);
        initView(inflate);
        initEvent();
        return inflate;
    }

    private void initEvent() {
        //如果进度条发生改变
        mSbLight.setOnSeekBarChangeListener(this);
        //如果进度条发生改变
        mSbVoice.setOnSeekBarChangeListener(this);
        mRbMobileNetWork.setOnClickListener(this);
        btnPCheckUpdate.setOnClickListener(this);
        mRbWifi.setOnClickListener(this);
        btnCleanCount.setOnClickListener(this);
        rlOther.setOnTouchListener(new View.OnTouchListener() {
            @SuppressLint("ClickableViewAccessibility")
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                Log.d(TAG, "onClick: ");
                //隐藏键盘
                @SuppressLint("WrongConstant") InputMethodManager imm = (InputMethodManager)
                        mActivity.getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
                return false;
            }
        });
        btnPlcContentUdate.setOnClickListener(this);
        btnSquattingContentUdate.setOnClickListener(this);
        btnCheckUpdate.setOnClickListener(this);
        btRrestorationcontractUpdate.setOnClickListener(this);
        btnContractUpdate.setOnClickListener(this);
    }

    private void initView(View inflate) {
        mSbLight = inflate.findViewById(R.id.sb_light);
        mSbVoice = inflate.findViewById(R.id.sb_voice);
        mRbMobileNetWork = inflate.findViewById(R.id.rb_4g);
        mRbWifi = inflate.findViewById(R.id.rb_wifi);
        rlOther = inflate.findViewById(R.id.rl_other);
        btnPlcContentUdate = inflate.findViewById(R.id.btn_plc_content_udate);
        btnSquattingContentUdate = inflate.findViewById(R.id.btn_squatting_content_udate);
        etPlcContent = inflate.findViewById(R.id.et_plc_content);
        etSquattingContent = inflate.findViewById(R.id.et_squatting_content);
        etCleanCountContent = inflate.findViewById(R.id.et_cleancount_content);
        btnCleanCount = inflate.findViewById(R.id.btn_cleancount);
        etRestorationcontract = inflate.findViewById(R.id.et_restorationway_contacts);
        etRestorationwayContacts = inflate.findViewById(R.id.et_restorationcontract);
        btRrestorationcontractUpdate = inflate.findViewById(R.id.btn_restorationcontract_update);
        llCheckBox = inflate.findViewById(R.id.ll_toiletcheckBox);
        btnPCheckUpdate = inflate.findViewById(R.id.btn_pcheckupdate);
        llPeopleCheckBox = inflate.findViewById(R.id.ll_peoplecheckBox);
        btnContractUpdate = inflate.findViewById(R.id.btn_contract_update);
        etWayContacts = inflate.findViewById(R.id.et_way_contacts);
        etContract = inflate.findViewById(R.id.et_contract);


        appCompatCheckBoxes = new AppCompatCheckBox[MyService.TOTAL_SUM];
        appCompatPeopleCheckBoxes = new AppCompatCheckBox[MyService.TOTAL_SUM];
        etPlcContent.setText(Hawk.get(Name.SERIALNUMBER, "4"));
        etSquattingContent.setText(Hawk.get(Name.TOILETSNUMBER, 2) + "");
        etCleanCountContent.setText(Hawk.get(Name.CLEANCOUNT, 10) + "");
        etRestorationcontract.setText(Hawk.get(Name.NEXTTIME, "456"));
        etRestorationwayContacts.setText(Hawk.get(Name.LASTTIME, "123"));
        //如果没有监听，那么我们默认赋值为true
        isSelectCheckBox = Hawk.get(Name.ISSELECTCHECKBOX, null);
        isSelectPeopleCheckbox = Hawk.get(Name.ISSELECTPEOPLECHECKBOX, null);
        etContract.setText(Hawk.get(Name.COMPANY,""));
        etWayContacts.setText(Hawk.get(Name.WAYCONTACTS,""));
        if (isSelectPeopleCheckbox == null) {//如果之前没有存储，那么我们重新创建，并初始化值。
            isSelectPeopleCheckbox = initTotileCheckBox();
        } else {
            if (isSelectPeopleCheckbox.length != MyService.TOTAL_SUM) {
                isSelectPeopleCheckbox = initTotileCheckBox();
            }
        }
        for (int i = 0; i < MyService.TOTAL_SUM; i++) {
            //生成一个厕所状态checkbox按钮
            AppCompatCheckBox aCheckBox = getAppCompatCheckBox(i, isSelectPeopleCheckbox[i]);
            //生成一个人体感应的checkbox按钮

            appCompatPeopleCheckBoxes[i] = aCheckBox;
            llPeopleCheckBox.addView(aCheckBox);
        }


        if (isSelectCheckBox == null) {//如果之前没有存储，那么我们重新创建，并初始化值。
            isSelectCheckBox = initTotileCheckBox();
        } else {
            if (isSelectCheckBox.length != MyService.TOTAL_SUM) {
                isSelectCheckBox = initTotileCheckBox();
            }
        }
        for (int i = 0; i < MyService.TOTAL_SUM; i++) {
            //生成一个厕所状态checkbox按钮
            AppCompatCheckBox aCheckBox = getAppCompatCheckBox(i, isSelectCheckBox[i]);
            //生成一个人体感应的checkbox按钮

            appCompatCheckBoxes[i] = aCheckBox;
            llCheckBox.addView(aCheckBox);
        }

        btnCheckUpdate = inflate.findViewById(R.id.btn_tcheckupdate);

    }

    private AppCompatCheckBox getAppCompatCheckBox(int i, boolean isSelectCheckBox) {
        AppCompatCheckBox aCheckBox = new AppCompatCheckBox(getContext());
        aCheckBox.setText(i + 1 + "号");
        aCheckBox.setChecked(isSelectCheckBox);
        aCheckBox.setTextColor(UiUtil.getColorRes(R.color.logo_blue));
        aCheckBox.setTextSize(UiUtil.getDimensionRes(R.dimen.sp_8));//不能直接写R.dimen.sp_7，否则直接获取60000多，而不是7sp
        aCheckBox.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
        return aCheckBox;
    }

    /**
     * 初始化厕所
     */
    private boolean[] initTotileCheckBox() {
        boolean[] totalSum = new boolean[MyService.TOTAL_SUM];
        for (int i = 0; i < totalSum.length; i++) {
            totalSum[i] = true;
        }
        return totalSum;
    }

    @Override
    public void onStart() {
        super.onStart();
        EventBus.getDefault().register(this);
        //每次界面刷新都需要重新获取音量和亮度
        initSeekBar();
        //初始化选择的网络：wifi还是移动4g
        initNetwork();
    }

    @Override
    public void onStop() {
        super.onStop();
        EventBus.getDefault().unregister(this);
        getActivity().unregisterReceiver(receiver);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();

    }

    /**
     * 初始化网络类型
     * 1.开启广播监听当前网络类型时
     */
    private void initNetwork() {
        IntentFilter filter = new IntentFilter();
        filter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
        filter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
        filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
        receiver = new NetworkConnectChangedReceiver();
        getActivity().registerReceiver(receiver, filter);
        int netType = Hawk.get(Name.NET_TYPE, -1);
        if (netType == 0) {
            mRbMobileNetWork.setChecked(true);
        } else if (netType == 1) {
            mRbWifi.setChecked(true);
        }
    }


    //如果网络类型发生改变，那么就会到这里设置选中的一个方式。
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void event(NetMessageEvent messageEvent) {
        switch (messageEvent.getType()) {
            case wifi:
                mRbWifi.setChecked(true);
                break;
            case mobile:
                mRbMobileNetWork.setChecked(true);
                break;
        }
    }

    private WifiDialog wifiDialog;
    //避免重复触发点击事件
    private boolean isCanClick = true;

    private void showWifiDialog() {
        if (wifiDialog == null) {
            wifiDialog = new WifiDialog(this.getContext());
        }
        wifiDialog.setCanceledOnTouchOutside(true);
        wifiDialog.setListener(new WifiDialog.DialogClickListener() {
            @Override
            public void onClickListener(int type, String text) {
                int apnType = getAPNType(BaseApplication.getContext());
                Log.d(TAG, "onClickListener: apnType " + apnType);
                if (apnType == 1) {
                    Log.d(TAG, "onClickListener: wifi");
                    isCanClick = true;
                    mRbWifi.setChecked(true);

                } else if (apnType == 2 || apnType == 3) {
                    Log.d(TAG, "onClickListener: dismiss 4g");
                    isCanClick = false;
                    mRbMobileNetWork.setChecked(true);


                }
            }
        });
        wifiDialog.show();
    }

    /**
     * 获取网络状态 没有网络0：WIFI网络1：3G网络2：2G网络3
     *
     * @param context
     * @return
     */
    public int getAPNType(Context context) {
        int netType = 0;
        ConnectivityManager connMgr = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
        if (networkInfo == null) {
            return netType;
        }
        int nType = networkInfo.getType();
        if (nType == ConnectivityManager.TYPE_WIFI) {
            netType = 1;// wifi
        } else if (nType == ConnectivityManager.TYPE_MOBILE) {
            int nSubType = networkInfo.getSubtype();
            TelephonyManager mTelephony = (TelephonyManager) context
                    .getSystemService(Context.TELEPHONY_SERVICE);
            if (nSubType == TelephonyManager.NETWORK_TYPE_UMTS
                    && !mTelephony.isNetworkRoaming()) {
                netType = 2;// 3G
            } else {
                netType = 3;// 2G
            }
        }
        return netType;
    }

    @Override
    protected OtherPresenter createPresenter() {
        return new OtherPresenter(this);
    }

    @Override
    public void showLoading() {

    }

    @Override
    public void hideLoading() {

    }

    //------------------------------------------------ seekbar 数值改变的方法重写
    @Override
    public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
        switch (seekBar.getId()) {
            case R.id.sb_light:
                //todo 测试不了，因为没有设备亮度可调。
                int seekBarProgress = seekBar.getProgress();
                changeAppBrightness(seekBarProgress);
                break;
            case R.id.sb_voice:
                am.setStreamVolume(AudioManager.STREAM_MUSIC, progress, 0);
                int currentVolume = am.getStreamVolume(AudioManager.STREAM_MUSIC);
                seekBar.setProgress(currentVolume);
                break;
        }
    }

    @Override
    public void onStartTrackingTouch(SeekBar seekBar) {
    }

    @Override
    public void onStopTrackingTouch(SeekBar seekBar) {
    }

    //------------------------------------------------ seekbar 数值改变的方法重写

    /**
     * 获取系统亮度和音量，初始化。
     */
    private void initSeekBar() {
        //设置最大值音量
        am = (AudioManager) getContext().getSystemService(Context.AUDIO_SERVICE);
        int maxVolume = am.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
        mSbVoice.setMax(maxVolume);
        //设置当前音量
        int currentVolume = am.getStreamVolume(AudioManager.STREAM_MUSIC);
        mSbVoice.setProgress(currentVolume);
        //亮度
        mSbLight.setMax(255);
        try {
            int anInt = Settings.System.getInt(getContext().getContentResolver(), Settings.System.SCREEN_BRIGHTNESS);
            mSbLight.setProgress(anInt);
        } catch (Settings.SettingNotFoundException e) {
            Log.d(TAG, "initSeekBar: 获取系统亮度失败");
            e.printStackTrace();
        }
    }

    /**
     * 设置系统亮度
     *
     * @param brightness
     */
    public void changeAppBrightness(int brightness) {
        Window window = getActivity().getWindow();
        WindowManager.LayoutParams lp = window.getAttributes();
        if (brightness == -1) {
            lp.screenBrightness = WindowManager.LayoutParams.BRIGHTNESS_OVERRIDE_NONE;
        } else {
            lp.screenBrightness = (brightness <= 0 ? 1 : brightness) / 255f;
        }
        window.setAttributes(lp);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.rb_4g:
                mvpPresenter.toggleWiFi(BaseApplication.getContext(), false);
                mvpPresenter.toggleMobileData(BaseApplication.getContext(), true);
                break;
            case R.id.rb_wifi:
                mvpPresenter.toggleMobileData(BaseApplication.getContext(), false);
                mvpPresenter.toggleWiFi(BaseApplication.getContext(), true);
                showWifiDialog();
                break;
            case R.id.btn_plc_content_udate:
                String plcContent = etPlcContent.getText().toString().trim();
                if ("".equals(plcContent)) {
                    ToastUtil.showToast("请输入串口号");
                    break;
                }
                Hawk.put(Name.SERIALNUMBER, plcContent);
                ToastUtil.showToast(UiUtil.getStringRes(R.string.update_success));
                break;
            case R.id.btn_squatting_content_udate:
                String squattingContent = etSquattingContent.getText().toString().trim();
                if ("".equals(squattingContent)) {
                    ToastUtil.showToast("请输入个数");
                    break;
                }
                MyService.TOTAL_SUM = Integer.valueOf(squattingContent);
                Hawk.put(Name.TOILETSNUMBER, Integer.valueOf(squattingContent));
                ToastUtil.showToast(UiUtil.getStringRes(R.string.update_success) + "，重启触摸屏后生效");
                break;
            case R.id.btn_tcheckupdate:
                for (int i = 0; i < appCompatCheckBoxes.length; i++) {
                    //我们需要将状态存储起来，进来的时候需要读取，清洗的时候需要读取。
                    isSelectCheckBox[i] = appCompatCheckBoxes[i].isChecked();
                }
                Hawk.put(Name.ISSELECTCHECKBOX, isSelectCheckBox);
                ToastUtil.showToast(UiUtil.getStringRes(R.string.update_success) + "，重启触摸屏后生效");
                break;
            case R.id.btn_pcheckupdate:
                for (int i = 0; i < appCompatPeopleCheckBoxes.length; i++) {
                    //我们需要将状态存储起来，进来的时候需要读取，清洗的时候需要读取。
                    isSelectPeopleCheckbox[i] = appCompatPeopleCheckBoxes[i].isChecked();
                }
                Hawk.put(Name.ISSELECTPEOPLECHECKBOX, isSelectPeopleCheckbox);
                ToastUtil.showToast(UiUtil.getStringRes(R.string.update_success) + "，重启触摸屏后生效");
                break;
            case R.id.btn_cleancount:
                String trim = etCleanCountContent.getText().toString().trim();
                if (trim != null && !("".equals(trim))) {
                    Hawk.put(Name.CLEANCOUNT, Integer.valueOf(trim));
                }
                ToastUtil.showToast(UiUtil.getStringRes(R.string.update_success));
                break;
            case R.id.btn_restorationcontract_update:
                //123
                String lastTime = etRestorationwayContacts.getText().toString().trim();//右边
                //456
                String nextTime = etRestorationcontract.getText().toString().trim();//左边
                if ("".equals(lastTime) && "".equals(nextTime)) {
                    ToastUtil.showToast("修改失败");
                    return;
                }
                Hawk.put(Name.LASTTIME, lastTime);
                Hawk.put(Name.NEXTTIME, nextTime);
                ToastUtil.showToast(UiUtil.getStringRes(R.string.update_success) + "，重启触摸屏后生效");
                break;
            case R.id.btn_contract_update:
                String contract = etContract.getText().toString().trim();
                String wayContacts = etWayContacts.getText().toString().trim();
                Hawk.put(Name.COMPANY, contract);
                Hawk.put(Name.WAYCONTACTS, wayContacts);
                Log.d(TAG, "btn_contract_updateonClick: " + contract + ":" + wayContacts);
                ToastUtil.showToast(UiUtil.getStringRes(R.string.update_success));
                break;
        }
    }


}
