package com.fxy.helper;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.widget.Toast;

import com.elvishew.xlog.XLog;
import com.lzy.okgo.OkGo;

import com.fxy.baselibrary.util.JsonUtil;
import com.fxy.R;
import com.fxy.base.ScanBaseActivity;
import com.fxy.bean.ScanBean;
import com.fxy.net.MyDialogCallback;
import com.fxy.net.Urls;


import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.UUID;

import es.dmoral.toasty.Toasty;
import sto.android.app.StoJNI;
import sto.android.app.StoTongJNI;


public class ScanHelper  implements StoJNI.ScanCallBack{
    private Context mContext;
    //获取厂商code
    private String manufacturer = "";
    //设备型号
    private String device_model = "";

    private JSONArray scanList;
    private Handler scanHandler;

    //扫码接口
    private ScanBaseActivity scanBaseActivity;
    //当前模式
    private int currentMode=-1;

    public ScanHelper(Context context){
        mContext = context;
        iniScanSetting();
    }


    //设置模式
    public void setCurrentMode(int mode){
        currentMode = mode;
    }

    public String getManufacturer(){
        return Build.MANUFACTURER;
    }

    public String getDeviceModel(){
        return Build.MODEL;
    }


    /**
     * 获取缓存的扫码设置
     * @return
     */
    private SharedPreferences getCacheScanSetting(){
        return   mContext.getSharedPreferences("scanSetting", Context.MODE_PRIVATE);
    }

    //初始化数据
    public void iniScanSetting(){
        manufacturer = getManufacturer();
        device_model = getDeviceModel();
        SharedPreferences scanSetting = getCacheScanSetting();
        if (scanSetting==null || scanSetting.getString("base","").isEmpty()){
            autoSelectSetting();
        }
    }


    /**
     * 获取扫码配置信息
     * @return
     */
    public String getScanSetTing(){
        SharedPreferences scanSetting = getCacheScanSetting();
        String initStr = "{\"scan_id\":1,\"is_api\":1,\"manufacturer\":\"Newland\",\"device_model\":\"\",\"action\":\"ACTION_BAR_SCAN\",\"is_broadcast\":1,\"data_name\":\"EXTRA_SCAN_DATA\",\"status_name\":\"EXTRA_SCAN_STATE\",\"device_name\":\"默认巴枪\"}";
        return scanSetting.getString("base", initStr);


    }

    //自动选择设置
    private void autoSelectSetting(){

        OkGo.<String>get(Urls.getScanSetting(mContext) + "?v=" + UUID.randomUUID().toString())
                .execute(new MyDialogCallback(mContext, false, false) {
                    @Override
                    public void onSuccess(com.lzy.okgo.model.Response<String> response) {
                        try {
                            scanList = new JSONArray(response.body().toString());
                            ScanBean scanBean = null;
                            for (int i = 0;i < scanList.length(); i++){
                                JSONObject jsonObject =scanList.getJSONObject(i);
                                String tmpManufacturer = jsonObject.has("manufacturer")?jsonObject.getString("manufacturer"):"";
                                String tmpModel = jsonObject.has("device_model")?jsonObject.getString("device_model"):"";
                                //没有选中设置时，默认选中统一厂商的配置
                                if (scanBean==null && tmpManufacturer.equals(manufacturer)){
                                    scanBean = JsonUtil.getObject(scanList.getString(i), ScanBean.class);
                                }
                                //匹配到厂商跟设备型号一致的 并且结束
                                if (tmpManufacturer.equals(manufacturer) && tmpModel.contains(device_model)){
                                    scanBean = JsonUtil.getObject(scanList.getString(i), ScanBean.class);
                                    break;
                                }
                            }

                            boolean res = saveData(scanBean);

                        } catch (JSONException e) {
                            Toasty.error(mContext, "获取扫码设置错误").show();
                            e.printStackTrace();
                        }
                    }
                });
    }

    //保存扫码设置
    public boolean saveData(ScanBean scanBean){
        if (scanBean==null){
            return  false;
        }
        try {
            SharedPreferences sharedPreferences =  getCacheScanSetting();;
            SharedPreferences.Editor editor = sharedPreferences.edit();
            editor.putString("base",scanBean.toJsonString());
            editor.apply();
            return true ;
        }catch (Exception e){
            Toast.makeText(mContext, "保存数据失败", Toast.LENGTH_LONG).show();
            XLog.e("保存数据失败:",e.getMessage());
            return false ;
        }
    }

    // 获取扫描结果
    public String getScanResult(ScanBean scanBean ,Intent intent){
        try {
            String scanResult = intent.getStringExtra(scanBean.getDataName());
            if (scanResult == null) {
                return null;
            }
            String scanStatus;
            if (!scanBean.getStatusName().isEmpty()) {
                scanStatus = intent.getStringExtra(scanBean.getStatusName());
            } else {
                scanStatus = scanResult.isEmpty() ? "" : "ok"; //有值 默认是扫码成功;
            }

            //新大陆(MT65,MT90) 需要手动关闭
            if (!scanBean.getActionStop().isEmpty()) {
                Intent stopIntent = new Intent(scanBean.getActionStop());
                mContext.sendBroadcast(stopIntent);
            }

            if ("ok".equals(scanStatus)) {
                return scanResult;
            }
            Toast.makeText(mContext, R.string.scan_failed, Toast.LENGTH_LONG).show();
            return "";
        } catch (Resources.NotFoundException e) {
            XLog.e("获取扫描结果");
            e.printStackTrace();
            return "";
        }
    }

    //初始化广播
    public void initReceiver(BroadcastReceiver mReceiver, Handler handler){
        String scanStr = getScanSetTing();
        initReceiver(mReceiver,handler,scanStr);
    }

    /**
     * 注册广播
     */
    public void initReceiver(BroadcastReceiver mReceiver, Handler handler,String scanStr){
        try {
            scanHandler = handler;
            ScanBean scanBean = JsonUtil.getObject(scanStr, ScanBean.class);
            if (currentMode==-1){
                currentMode = scanBean.getIsBroadcast();//是否广播
            }

            if (currentMode ==1){
                //广播模式
                IntentFilter mFilter = new IntentFilter(scanBean.getAction());
                mContext.registerReceiver(mReceiver, mFilter);
            }else{
                if (scanBean.getManufacturer().equals("kaicom") && !manufacturer.equals("kaicom")){
                    //当不是凯立巴枪，又使用巴枪模式
                    Toast.makeText(mContext, "请重新设置巴枪模式", Toast.LENGTH_LONG).show();
                }else{
                    //接口模式
                    StoTongJNI.getIns(mContext).setmScanCB(this);
                    StoTongJNI.getIns(mContext).SetScannerOn();
                }
            }
        }catch (Exception e) {
            Toast.makeText(mContext, "获取扫码配置失败"+e.getMessage(), Toast.LENGTH_LONG).show();
            XLog.e("获取扫码配置失败:" + e.getMessage());
        }
    }


    /**
     *
     * @param mReceiver
     *
     */
    public void scanStop(BroadcastReceiver mReceiver) {
        try {
            if (currentMode==1){
                mContext.unregisterReceiver(mReceiver);
            }else{
                StoTongJNI.getIns(mContext).SetScannerStop();
                StoTongJNI.getIns(mContext).SetScannerOff();
            }
        } catch (Exception e) {
            XLog.e("停止广播事件");
            e.printStackTrace();
        }
    }
    @Override
    public void onScanResults(String str) {
        Message msg = new Message();
        msg.obj = str;
        scanHandler.sendMessage(msg);
    }

    @Override
    public void onScanResults(String str, int type) {
        Message msg = new Message();
        msg.obj = str;
        scanHandler.sendMessage(msg);
    }
}
