package com.seuic.uhfdemo;
import android.Manifest;
import android.app.Fragment;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.media.AudioManager;
import android.media.SoundPool;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Vibrator;
import android.provider.Settings;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import com.seuic.sleduhf.DecodeInfo;
import com.seuic.sleduhf.EPC;
import com.seuic.sleduhf.UhfCallback;
import com.seuic.sleduhf.UhfDevice;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import static android.media.AudioManager.STREAM_MUSIC;
import static com.seuic.sleduhf.UhfDevice.PARAM_MAIN_SCANKEY_FUNCTION;
import static com.seuic.sleduhf.UhfDevice.PARAM_SCANKEY_FUNCTION;
import static com.seuic.sleduhf.UhfDevice.PARAM_SOUND;
import static com.seuic.sleduhf.UhfDevice.PARAM_SOUND_VOLUME;

public class InventoryUm3 extends Fragment {

	public static final int ItemSelectColor = 0x44000000;
	AudioManager audiomanage ;
	Vibrator vibrator;
	public boolean mInventoryStart = false;
	private int mSelectedIndex = -1;
	private Button btn_init;
	private Button btn_Open;
	private Button btn_stop;
	private Button bt_Clear;
	private TextView tv_total;
	private ListView lv_id;
	private TextView tv_tip;
	private List<EPC> mEPCList;
	private InventoryAdapter mAdapter;

	private String btMc;
	private UhfDevice uhfDevice;
	private CallbackListener callbackListener;
	View currentView;
	static int m_count = 0;
	private static InventoryUm3 inventoryUm3;
	public static InventoryUm3 getInstance() {
		if (inventoryUm3 == null)
			inventoryUm3 = new InventoryUm3();
		return inventoryUm3;
	}

	private static SoundPool mSoundPool;
	private static int soundID;
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		View view = initUI(inflater);
		checkLocationEnable();
		openJurisdiction();
		mEPCList = new ArrayList<EPC>();
		mAdapter = new InventoryAdapter();
		lv_id.setAdapter(mAdapter);
		lv_id.setOnItemClickListener(new MyItemClickListener());
		return view;
	}
	private String TAG="zy";

	@Override
	public void onResume() {
		super.onResume();
		audiomanage= (AudioManager)getActivity().getSystemService(Context.AUDIO_SERVICE);
		vibrator = (Vibrator)this.getActivity().getSystemService(Context.VIBRATOR_SERVICE);
		Log.i(TAG,"最大音量"+audiomanage.getStreamMaxVolume(STREAM_MUSIC ));
	}

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


	// init UI
	private View initUI(LayoutInflater inflater) {
		currentView = inflater.inflate(R.layout.fragment_um3, null);
		tv_total = (TextView) currentView.findViewById(R.id.tv_total);
		tv_tip=(TextView)currentView.findViewById(R.id.tv_tip);
		lv_id = (ListView) currentView.findViewById(R.id.lv_id);
		btn_init = (Button) currentView.findViewById(R.id.btn_init);
		btn_init.setOnClickListener(new MyClickListener());
		btn_Open = (Button) currentView.findViewById(R.id.btn_Open);
		btn_Open.setOnClickListener(new MyClickListener());
		btn_stop = (Button) currentView.findViewById(R.id.bt_stop);
		btn_stop.setOnClickListener(new MyClickListener());
		bt_Clear=(Button) currentView.findViewById(R.id.bt_Clear);
		bt_Clear.setOnClickListener(new MyClickListener());
		mSoundPool = new SoundPool(3, STREAM_MUSIC, 20);
		soundID = mSoundPool.load(currentView.getContext(), R.raw.scan, 1);
		return currentView;
	}

	private void refreshData() {
		if (mEPCList != null) {
			int count = 0;
			for (EPC item : mEPCList) {
				count += item.count;
			}
			if (count > m_count) {

			}
			mAdapter.notifyDataSetChanged();
			tv_total.setText(getString(R.string.id_pc_epc)+getString(R.string.total) + mEPCList.size());
			m_count = count;
		}
	}

	private class MyItemClickListener implements OnItemClickListener {
		public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
			mSelectedIndex = position;
			mAdapter.notifyDataSetInvalidated();
		}
	}

	private class MyClickListener implements View.OnClickListener {
		public void onClick(View v) {
			switch (v.getId()) {
				case R.id.btn_init:
					init(getActivity().getApplication(), "", new CallbackListener() {
						@Override
						public void callback(boolean success, String msg) {
							Message message = Message.obtain();
							message.what = 2;
							message.obj=msg;
							handler.sendMessage(message);
						}
					});
					break;
				case R.id.btn_Open:
					open(new CallbackListener() {
						@Override
						public void callback(boolean success, String msg) {
							Log.i("zy","open:"+msg);
							Message message = Message.obtain();
							message.what = 2;
							message.obj=msg;
							handler.sendMessage(message);
						}
					});
					break;
				case R.id.bt_stop:
					close();
					break;
				case R.id.bt_Clear:
					clearList();
					break;
				default:
					break;
			}
		}
	}

	private void clearList() {
		tv_total.setText("ID(PC+EPC)总数：");
		mSelectedIndex = -1;
		if (mEPCList != null) {
			mEPCList.clear();
			mAdapter.notifyDataSetChanged();
			m_count = 0;
		}
	}

	private void playSound() {
		if (mSoundPool == null) {
			mSoundPool = new SoundPool(3, STREAM_MUSIC, 20);
			soundID = mSoundPool.load(currentView.getContext(), R.raw.scan, 1);// "/system/media/audio/notifications/Antimony.ogg"
		}
		mSoundPool.play(soundID, 1, 1, 0, 0, 1);
	}

	private class InventoryAdapter extends BaseAdapter {
		@Override
		public int getCount() {
			// return 0;
			if (mEPCList != null) {
				return mEPCList.size();
			}
			return 0;
		}

		@Override
		public Object getItem(int position) {
			// return null;
			return mEPCList.get(position);
		}

		@Override
		public long getItemId(int position) {
			// return 0;
			return position;
		}

		@Override
		public void notifyDataSetChanged() {
			super.notifyDataSetChanged();
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			View item_view = View.inflate(currentView.getContext(), R.layout.item_epc, null);
			EPC epc = mEPCList.get(position);
			TextView tv_id = (TextView) item_view.findViewById(R.id.tv_epc);
			TextView tv_nums = (TextView) item_view.findViewById(R.id.tv_nums);
			TextView tv_rssi = (TextView) item_view.findViewById(R.id.tv_rssi);
			tv_id.setText(epc.getId());
			tv_nums.setText(epc.count + "");
			tv_rssi.setText(epc.rssi + "");
			if (position == mSelectedIndex) {
				item_view.setBackgroundColor(ItemSelectColor);
			}
			return item_view;
		}

	}

	UhfCallback uhfCallback= new UhfCallback() {
		@Override
		public void onGetBtInfo(BluetoothDevice bluetoothDevice) {
		}
		@Override
		public void onGetConnectStatus(int i) {
			switch (i)
			{
				case 0:
					callbackListener.callback(true,"设备连接成功！");
					break;
				case -1:
					callbackListener.callback(false,"断开连接！");
					break;
				case -2:
					callbackListener.callback(false,"连接超时！");
					break;
			}
		}

		@Override
		public void onGetTagsId(List<EPC> list) {
			if (mSelectedIndex >= 0) {
				/*Message message = Message.obtain();
				message.what = 3;
				message.obj = list;
				handler.sendMessage(message);*/
				FindRFID2(list);
			} else {
				Message message = Message.obtain();
				message.what = 1;
				message.obj = list;
				handler.sendMessage(message);
			}
		}

		@Override
		public void onGetScanKeyMode(int i) {

		}
		@Override
		public void onDecodeComplete(DecodeInfo decodeInfo) {
		}
	};
	/*初始化模块*/
	public void init(Context context,String soLibPath, CallbackListener listener){
		if (uhfDevice==null)
			uhfDevice=UhfDevice.getInstance(context);
		uhfDevice.registerUhfCallback(uhfCallback);
		callbackListener=listener;
		BluetoothAdapter btAdapter=BluetoothAdapter.getDefaultAdapter();
		if (!btAdapter.isEnabled())
			listener.callback(false,"蓝牙不可用！");
		Set<BluetoothDevice> devices=btAdapter.getBondedDevices();
		if (devices.size()>0){
			for (BluetoothDevice dev:devices) {
				if (dev.getAddress().startsWith("00:15")){
					btMc=dev.getAddress();
					uhfDevice.connect(btMc,5000);
					break;
				}
			}
		}else {
			listener.callback(false,"未找到已连接配对设备！");
		}
	}

	/*开启模块*/
	public void open(CallbackListener listener){
		try{
			String mc="";
			for (int i = 0; i <3; i++) {
				Thread.sleep(800);
				mc=uhfDevice.getSledAddress();
				if (!TextUtils.isEmpty(mc))
					break;
			}
			if (!TextUtils.isEmpty(mc)) {
				btMc=mc;
				listener.callback(true,"设备打开成功！");
				uhfDevice.setSledParam(PARAM_MAIN_SCANKEY_FUNCTION,0);/*UHF模式*/
				uhfDevice.setSledParam(PARAM_SCANKEY_FUNCTION,0);/*扫描键连续寻卡*/
				uhfDevice.setSledParam(PARAM_SOUND,0);/*关闭寻卡声音*/
				uhfDevice.setPower(33);/*设置功率为33*/
			}
			else
				listener.callback(false, "设备打开失败！");
		}catch (Exception ex){
			listener.callback(false, "设备打开失败！");
		}
	}

	/*关闭模块*/
	public void close(){
		try {
			uhfDevice.setSledParam(PARAM_SCANKEY_FUNCTION,1);/*扫描键连续寻卡*/
			uhfDevice.setSledParam(PARAM_SOUND,1);/*关闭寻卡声音*/
			if (uhfDevice != null) {
				uhfDevice.unregisterUhfCallback(uhfCallback);
				uhfDevice.disconnect();
			}
			Message message = Message.obtain();
			message.what = 2;
			message.obj="设备关闭成功";
			handler.sendMessage(message);
			Log.i("zy","设备关闭成功");
		}catch (Exception ex){
			Log.i("zy","设备关闭失败");
			Message message = Message.obtain();
			message.what = 2;
			message.obj="设备关闭失败";
			handler.sendMessage(message);
		}
	}

	List<EPC> epcnew=new ArrayList<EPC>();;
	private Handler handler = new Handler() {

		public void handleMessage(final Message msg) {
			switch (msg.what) {
				case 1:
					synchronized (currentView.getContext()) {
						List<EPC> epcs= (List<EPC>) msg.obj;
						for (int i=0;i<epcs.size();i++){
							playSound();
							if(!mEPCList.contains(epcs.get(i))) {
								mEPCList.add(epcs.get(i));
							}
							else{
								mEPCList.remove(epcs.get(i));
								mEPCList.add(epcs.get(i));
							}
						}
						Log.i(TAG,"mEPCList.size="+mEPCList.size());
					}
					refreshData();
					break;
				case 2:
					getActivity().runOnUiThread(new Runnable() {
						@Override
						public void run() {
							tv_tip.setText(msg.obj.toString());
						}
					});
					break;
				case 3:
					synchronized (currentView.getContext()) {
						/*List<EPC> epcs= (List<EPC>) msg.obj;
						for (int i=0;i<epcs.size();i++){
							playSound();
							if(!epcnew.contains(epcs.get(i))) {
								epcnew.add(epcs.get(i));
							}
							else{
								epcnew.remove(epcs.get(i));
								epcnew.add(epcs.get(i));
							}
						}*/
						epcnew=(List<EPC>) msg.obj;
					}
					FindRFID();
					break;
				default:
					break;
			}
		};
	};

	/*寻卡*/
	/*UM3和A9U获取的信号强度不一样，A9U的设备获取的信号强度在20以上，UM3 基本在-40以上*/
	private void FindRFID() {
		if (epcnew != null) {
			try {
				for (int i = 0; i < epcnew.size(); i++) {
					if (mEPCList.get(mSelectedIndex).getId().equals(epcnew.get(i).getId())) {
						int rssi = epcnew.get(i).rssi;
						Log.i(TAG, epcnew.get(i).getId() + "的信号强度：" + rssi);
						/*信号强度在-100- -75：响1声*/
						if (rssi < -75) {
							audiomanage.setStreamVolume(STREAM_MUSIC, 1, 0);
							playSound();
							vibrator.vibrate(20);
							Thread.sleep(800);
						}
						/*信号强度在-70- -65：响1声*/
						if (rssi >= -70 && rssi <= -65) {
							audiomanage.setStreamVolume(STREAM_MUSIC, 3, 0);
							playSound();
							vibrator.vibrate(20);
							Thread.sleep(600);
						}
						/*信号强度在-60到-55之间：响2声*/
						if (rssi > -60 && rssi <= -55) {
							audiomanage.setStreamVolume(STREAM_MUSIC, 6, 0);
							playSound();
							vibrator.vibrate(20);
							Thread.sleep(400);
						}
						/*信号强度在-55到-50之间：响2声*/
						if (rssi > -55 && rssi <= -50) {
							audiomanage.setStreamVolume(STREAM_MUSIC, 9, 0);
							playSound();
							vibrator.vibrate(20);
							Thread.sleep(200);
						}
						/*信号强度在-0到-50之间：*/
						if (rssi > -50) {
							audiomanage.setStreamVolume(STREAM_MUSIC, 15, 0);
							playSound();
							vibrator.vibrate(20);
							Thread.sleep(20);
						}
					}
				}
			} catch (Exception ex) {
				Log.i(TAG,"e.error:"+ex.toString());
			}
		}
	}

	/*我只细分了 5个区间，客户实际开发时，可以根据自己的需求，去增加区间，信号强度一般在-19~-80之间*/
	/*视觉显示可以参考 InventoryFragement 中 HorizontalProgressBar 类，可参考使用*/
	private void FindRFID2(List<EPC> epcList ) {
		if (epcList != null) {
			try {
				Log.i(TAG,"epcList.size:"+epcList.size());
				for (int i = 0; i < epcList.size(); i++) {
					if (mEPCList.get(mSelectedIndex).getId().equals(epcList.get(i).getId())) {
						int rssi = epcList.get(i).rssi;
						Log.i(TAG, epcList.get(i).getId() + "的信号强度：" + rssi);
						/*信号强度在-100到-70：响1声*/
						if (rssi < -70) {
							audiomanage.setStreamVolume(STREAM_MUSIC, 1, 0);
							playSound();
							vibrator.vibrate(20);
							//Thread.sleep(200);
						}
						/*信号强度在-70到-65：响1声*/
						if (rssi >= -70 && rssi <= -65) {
							audiomanage.setStreamVolume(STREAM_MUSIC, 3, 0);
							playSound();
							vibrator.vibrate(20);
							//Thread.sleep(150);
						}
						/*信号强度在-60到-55之间：响2声*/
						if (rssi > -60 && rssi <= -55) {
							audiomanage.setStreamVolume(STREAM_MUSIC, 6, 0);
							playSound();
							vibrator.vibrate(20);
							//Thread.sleep(100);
						}
						/*信号强度在-55到-50之间：响2声*/
						if (rssi > -55 && rssi <= -50) {
							audiomanage.setStreamVolume(STREAM_MUSIC, 9, 0);
							playSound();
							vibrator.vibrate(20);
							//Thread.sleep(50);
						}
						/*信号强度在-0到-50之间：*/
						if (rssi > -50) {
							audiomanage.setStreamVolume(STREAM_MUSIC, 15, 0);
							playSound();
							vibrator.vibrate(20);
							//Thread.sleep(20);
						}
					}
				}
			} catch (Exception ex) {
				Log.i(TAG,"e.error:"+ex.toString());
			}
		}
	}

	//------------------获取定位权限--------------------------------
	private static final int ACCESS_FINE_LOCATION_PERMISSION_REQUEST = 100;
	private static final int REQUEST_ACTION_LOCATION_SETTINGS = 3;

	private void checkLocationEnable() {
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
			if (getActivity().checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
				requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, ACCESS_FINE_LOCATION_PERMISSION_REQUEST);
			}
		}
		if (!isLocationEnabled()) {
			Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
			startActivityForResult(intent, REQUEST_ACTION_LOCATION_SETTINGS);
		}
	}

	private boolean isLocationEnabled() {
		int locationMode = 0;
		String locationProviders;
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
			try {
				locationMode = Settings.Secure.getInt(getActivity().getContentResolver(), Settings.Secure.LOCATION_MODE);
			} catch (Settings.SettingNotFoundException e) {
				e.printStackTrace();
				return false;
			}
			return locationMode != Settings.Secure.LOCATION_MODE_OFF;
		} else {
			locationProviders = Settings.Secure.getString(getActivity().getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
			return !TextUtils.isEmpty(locationProviders);
		}
	}


	private void openJurisdiction() {
		if (Build.VERSION.SDK_INT >= 23) {
			if (ContextCompat.checkSelfPermission(getActivity(),
					Manifest.permission.BLUETOOTH)
					!= PackageManager.PERMISSION_GRANTED) {

				ActivityCompat.requestPermissions(getActivity(),
						new String[]{Manifest.permission.BLUETOOTH},
						1);
			}
		}
	}

}
