package aicare.net.cn.sdk.ailinksdkdemoandroid.home;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.elinkthings.httplibrary.OnHttpListener;
import com.elinkthings.httplibrary.license.LicenseHttpBean;
import com.elinkthings.httplibrary.license.LicenseHttpUtils;
import com.pingwang.bluetoothlib.AILinkBleManager;
import com.pingwang.bluetoothlib.AILinkSDK;
import com.pingwang.bluetoothlib.bean.AilinkLicenseBean;
import com.pingwang.bluetoothlib.bean.BleValueBean;
import com.pingwang.bluetoothlib.device.AiLinkBleCheckUtil;
import com.pingwang.bluetoothlib.listener.OnCallbackBle;
import com.pingwang.bluetoothlib.utils.BleLog;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import aicare.net.cn.sdk.ailinksdkdemoandroid.AboutActivity;
import aicare.net.cn.sdk.ailinksdkdemoandroid.BuildConfig;
import aicare.net.cn.sdk.ailinksdkdemoandroid.R;
import aicare.net.cn.sdk.ailinksdkdemoandroid.ShowBleActivity;
import aicare.net.cn.sdk.ailinksdkdemoandroid.dialog.HintDataDialogFragment;
import aicare.net.cn.sdk.ailinksdkdemoandroid.utils.AppStart;
import aicare.net.cn.sdk.ailinksdkdemoandroid.utils.L;
import aicare.net.cn.sdk.ailinksdkdemoandroid.utils.SP;


public class MainActivity extends AppCompatActivity {


    private Context mContext;
    private RecyclerView rvList;
    private TextView tvLog;
    private ArrayList<JumpBean> mList = new ArrayList<>();
    private ArrayList<JumpBean> homeDataList = HomeDataManager.getHomeDataList();
    private CharSequence inputData = "";
    private HomeListAdapter mHomeListAdapter;

    private Handler mHandler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(@NonNull Message msg) {
            if (mHomeListAdapter != null) {
                mHomeListAdapter.notifyDataSetChanged();
            }
        }
    };

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mContext = this;
        initView();
        initData();
        initListener();
        EditText etSearch = findViewById(R.id.etSearch);

        etSearch.addTextChangedListener(new TextWatcher() {
            /**
             * @param s     年代
             * @param start 开始
             * @param count 数
             * @param after
             */
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            /**
             * 文本更改
             *
             * @param s      年代
             * @param start  开始
             * @param before 之前
             * @param count  数
             */
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                inputData = s;
            }

            /**
             * 文本更改后
             *
             * @param s 年代
             */
            @Override
            public void afterTextChanged(Editable s) {
                String data = inputData.toString().trim();
                if (TextUtils.isEmpty(data)) {
                    //未输入内容,显示全部
                    mList.clear();
                    mList.addAll(homeDataList);
                    mHandler.sendEmptyMessage(1);
                } else {
                    refreshList(data);
                }
            }
        });

        findViewById(R.id.ivClear).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                etSearch.setText("");
            }
        });


    }


    private void refreshList(String data) {
        ArrayList<JumpBean> list = new ArrayList<>();
        for (JumpBean jumpBean : homeDataList) {
            String name = mContext.getString(jumpBean.getItemNameResId()).toUpperCase();
            if (name.contains(data.toUpperCase())) {
                list.add(jumpBean);
            }
        }
        mList.clear();
        mList.addAll(list);
        mHandler.sendEmptyMessage(1);
    }


    protected void initListener() {
        ActionBar supportActionBar = getSupportActionBar();
        if (supportActionBar != null) {
            supportActionBar.setTitle(getString(R.string.app_name) + BuildConfig.VERSION_NAME);
        }
    }

    protected void initData() {
        initPermissions();
        refreshLicenseData();
        byte[] data = {0x01, 0x02, 0x03, 0x04, 0x05, 0x06};
        int crc16 = AiLinkBleCheckUtil.getCrc16(data);
        L.i("crc16:" + crc16);
//        AiLinkPwdUtil

//        List<AilinkLicenseBean> list = new ArrayList<>();
//        list.add(new AilinkLicenseBean(0x2F, 0x03, 0x09));
//        list.add(new AilinkLicenseBean(0x2F, 0x03, 0x01));
//        list.add(new AilinkLicenseBean(65544, 103, 0));
//        list.add(new AilinkLicenseBean(65544, 21, 0));
//        list.add(new AilinkLicenseBean(0x02, 0x99, 0x01));
//
//        AILinkSDK.getInstance().initLicense(list);
    }


    private List<AilinkLicenseBean> mLicenseBeans;

    /**
     * 刷新许可数据
     */
    private void refreshLicenseData() {
        if (mLicenseBeans == null) {
            mLicenseBeans = new ArrayList<>();
        }
        new LicenseHttpUtils().getLicenseList(new OnHttpListener<List<LicenseHttpBean>>() {
            @Override
            public void onSuccess(List<LicenseHttpBean> data) {
                if (data != null) {
                    L.iw("License:" + Arrays.toString(data.toArray()));
//                    tvLog.setText("License成功:" + data.size());
                    for (LicenseHttpBean datum : data) {
                        //最好做一下判断，免得后端抽风改了就寄了
                        if (datum != null) {
                            AilinkLicenseBean ailinkLicenseBean = new AilinkLicenseBean();
                            ailinkLicenseBean.setCid(datum.getCid());
                            ailinkLicenseBean.setVid(datum.getVid());
                            ailinkLicenseBean.setPid(datum.getPid());
                            mLicenseBeans.add(ailinkLicenseBean);
                        }
                    }
                    //还是判断一下初始化有没有完成吧
                    if (AILinkSDK.getInstance().isInitOk() && mLicenseBeans != null && !mLicenseBeans.isEmpty()) {
                        AILinkSDK.getInstance().initLicense(mLicenseBeans);
                    }
                } else {
                    tvLog.setText("License失败:null");
                }
            }

            @Override
            public void onFailed(List<LicenseHttpBean> data) {
                tvLog.setText("License失败:网络问题");
            }
        });
    }


    private int count = 0;
    private OnCallbackBle mOnCallbackBle = new OnCallbackBle() {
        @Override
        public void onStartScan() {
            OnCallbackBle.super.onStartScan();
        }

        @Override
        public void onScanning(BleValueBean data) {
//            AILinkBleManager.getInstance().removeOnCallbackBle(mOnCallbackBle);
        }
    };


    protected void initView() {
        //connectDevice(BleValueBean bleValueBean);连接的时候需要传广播对象,否则返回的cid,vid,pid始终都是0
        //sdk
        AILinkSDK.getInstance().init(mContext);
        AILinkBleManager.getInstance().init(mContext, new AILinkBleManager.onInitListener() {
            @Override
            public void onInitSuccess() {
                L.i("初始化成功");
//                AILinkBleManager.getInstance().setOnCallbackBle(mOnCallbackBle);
            }

            @Override
            public void onInitFailure() {
                L.e("初始化失败");

            }
        });
        SP.init(this);

        rvList = findViewById(R.id.rv_list);
        tvLog = findViewById(R.id.tvLog);
        rvList.setLayoutManager(new LinearLayoutManager(this));
        mList.clear();
        mList.addAll(homeDataList);
        mHomeListAdapter = new HomeListAdapter(this, mList);
        rvList.setAdapter(mHomeListAdapter);
        mHomeListAdapter.setItemClickListener(new HomeListAdapter.ItemClickListener() {
            @Override
            public void onItemClick(JumpBean bean) {
                count = 0;
                if (bean.getJumpActivityClass() != null) {
                    startActivity(bean.getItemType(), bean.getCid(), bean.getJumpActivityClass());
                } else if (bean.getTargetActivityClass() != null) {
                    startActivity(bean.getTargetActivityClass());
                } else {
                    startActivity(bean.getItemType(), bean.getCid(), ShowBleActivity.class);
                }
            }
        });
        rvList.addItemDecoration(new RecyclerView.ItemDecoration() {
            @Override
            public void getItemOffsets(@NonNull Rect outRect, @NonNull View view, @NonNull RecyclerView parent, @NonNull RecyclerView.State state) {
                super.getItemOffsets(outRect, view, parent, state);
                if (parent.getChildAdapterPosition(view) == 0) {
                    outRect.set(0, 30, 0, 0);
                }
            }

            @Override
            public void onDraw(@NonNull Canvas c, @NonNull RecyclerView parent, @NonNull RecyclerView.State state) {
                super.onDraw(c, parent, state);
            }
        });
    }

    private void startActivity(int type, int cid, Class<?> activityClass) {
        Intent intent = new Intent(this, activityClass);
        intent.putExtra("type", type);
        intent.putExtra("cid", cid);
        startActivity(intent);
    }

    private void startActivity(Class<?> activityClass) {
        Intent intent = new Intent(this, activityClass);
        startActivity(intent);
    }

    @Override
    protected void onResume() {
        super.onResume();

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        BleLog.quit();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.toolbar_menu, menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        if (item.getItemId() == R.id.toolbar_right_menu) {
            startActivity(new Intent(mContext, AboutActivity.class));
            return true;
        }
        return super.onOptionsItemSelected(item);
    }


    //-----------------------权限----------------------------------------
    /**
     * 需要申请的权限
     */
    private String[] LOCATION_PERMISSION = new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.WRITE_EXTERNAL_STORAGE};
    private final static String[] BLUETOOTH_PERMISSION = new String[]{Manifest.permission.BLUETOOTH_SCAN, Manifest.permission.BLUETOOTH_ADVERTISE, Manifest.permission.BLUETOOTH_CONNECT};
    /**
     * 权限请求返回
     */
    private final int PERMISSION = 101;
    /**
     * 定位服务返回
     */
    protected final int LOCATION_SERVER = 102;
    private HintDataDialogFragment mHintDataDialog = null;

    protected void initPermissions() {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
            onPermissionsOk();
            return;
        }

        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.S) {
            if (ContextCompat.checkSelfPermission(this, LOCATION_PERMISSION[0]) != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(this, LOCATION_PERMISSION, PERMISSION);
            } else {
                boolean bleStatus = AppStart.isLocServiceEnable(mContext);
                if (!bleStatus) {
                    //没有开启定位服务
                    mHintDataDialog = HintDataDialogFragment.newInstance()
                            .setTitle("提示", 0)
                            .setCancel("取消", 0)
                            .setOk("确定", 0)
                            .setContent("请求开启定位服务", true)
                            .setOnDialogListener(new HintDataDialogFragment.onDialogListener() {
                                @Override
                                public void onSucceedListener(View v) {
                                    startLocationActivity();
                                }
                            });
                    mHintDataDialog.show(getSupportFragmentManager());


                } else {
                    onPermissionsOk();
                }
            }
        } else {
            if (ContextCompat.checkSelfPermission(this, BLUETOOTH_PERMISSION[0]) != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(this, BLUETOOTH_PERMISSION, PERMISSION);
            }
        }


    }


    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        //请求权限被拒绝
        if (requestCode != PERMISSION) {
            return;
        }

        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.S) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                initPermissions();
            } else {
                if (ActivityCompat.shouldShowRequestPermissionRationale(this, LOCATION_PERMISSION[0])) {
                    //权限请求失败，但未选中“不再提示”选项,再次请求
                    ActivityCompat.requestPermissions(this, LOCATION_PERMISSION, PERMISSION);
                } else {
                    //权限请求失败，选中“不再提示”选项
                    mHintDataDialog = HintDataDialogFragment.newInstance()
                            .setTitle("提示", 0)
                            .setCancel("取消", 0)
                            .setOk("确定", 0)
                            .setContent("请求开启定位权限", true)
                            .setOnDialogListener(new HintDataDialogFragment.onDialogListener() {
                                @Override
                                public void onSucceedListener(View v) {
                                    AppStart.startUseSetActivity(mContext);
                                }
                            });
                    mHintDataDialog.show(getSupportFragmentManager());

                }

            }
        } else {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                initPermissions();
            }
        }


    }


    /**
     * 启动去设置定位服务
     */
    protected void startLocationActivity() {

        AppStart.startLocationActivity(this, LOCATION_SERVER);

    }


    /**
     * 权限ok
     */
    protected void onPermissionsOk() {

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == LOCATION_SERVER) {
            //定位服务页面返回
            initPermissions();
        }
    }

}
