package com.rehome.sgbaxj.activity.regular;


import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioGroup;
import android.widget.TextView;
import com.rehome.sgbaxj.DBModel.Dqgz;
import com.rehome.sgbaxj.R;
import com.rehome.sgbaxj.base.BaseActivity3;
import com.rehome.sgbaxj.contans.Contans;
import com.rehome.sgbaxj.utils.SPUtils;
import com.rehome.sgbaxj.weight.AuditDialog;
import com.rehome.sgbaxj.weight.EditDialog;
import com.rinsun.mtdriver.MTnativeInterface;
import org.litepal.crud.DataSupport;
import java.text.SimpleDateFormat;
import java.util.Date;

public class CheckVibrationDqgzActivity extends BaseActivity3 implements View.OnClickListener  {

    TextView etRealTitle;
    EditText etRealValue;
    EditText noticeValue;
    Button btnSubmit;
    TextView checkTip;
    TextView standerTip;
    RadioGroup rgLevel;
    RadioGroup rgType;



    private String vibrationValue;
    public static final int RESULT_SUCCESS = 1;
    //private String checkType;
    int checkVibrationType = MTnativeInterface.CMD_VIBD_R;
    int level = 0;
    // 振动位移单位   mm
    //振动速度单位    mm/s
    //振动加速度单位    mm/(s^2)
    //String measure = "mm";
    //是否可编辑
    private boolean isEdit = false;
    //页面传过来的数据
    Dqgz dqgz;

    //频谱用到的变量/////////////////////////////
    private double edit16LA;
    private double edit16LV;
    private double edit16LD;
    private double edit16HA;
    private double edit16HV;
    private double edit16HD;

    private double[] ppsour;
    private int ppfreq;  // <1280,5120,12800>
    private int pplen;   // 1024, 4096, 8192
    ///////////////////////////////////////////////

    MTnativeInterface mt= MTnativeInterface.getInstance();//获取传感器调用接口
    Intent intentTemplate;
    private String username;


    @Override
    public int getLayoutId() {
        return R.layout.activity_check_vibration;
    }

    @Override
    public void initView() {
        etRealTitle = findViewById(R.id.tv_realTitle);
        etRealValue = findViewById(R.id.et_realValue);
        noticeValue = findViewById(R.id.et_noticeValue);
        btnSubmit = findViewById(R.id.btn_submit);
        checkTip = findViewById(R.id.tv_checkTip);
        standerTip = findViewById(R.id.tv_standerTip);
        rgLevel = findViewById(R.id.rgLevel);
        rgType = findViewById(R.id.rgType);

        etRealValue.setEnabled(true);
        username = (String) SPUtils.get(context, Contans.USERID, "");
        Bundle bundle = CheckVibrationDqgzActivity.this.getIntent().getExtras();
        if (bundle != null) {
            isEdit = bundle.getBoolean("edit");
            if(isEdit){
                initToolbar("测振", "开始测量", this);
            }else{
                initToolbar("测振", "", this);
                btnSubmit.setVisibility(View.GONE);
            }
        }

        noticeValue.setKeyListener(null);

        //回调函数（自动返回数据）。CMDtype:数据类型，参数说明见“说明文档.txt”
        mt.setOnReceiveListener(new MTnativeInterface.OnReceiveListener() {
            @Override
            public void onShowMessage(byte[] recBuff,int CMDtype, int tag) {
                /* 根据CMDtype区分数据类型，普通测量值/频谱数据/配置数据。如果10秒没读到数据会返回超时提示并关闭电源 */
                System.out.println("-------------");
                System.out.println(new String(recBuff)+"/"+CMDtype+"/"+tag);

                if(CMDtype==MTnativeInterface.CMD_VIBA_R){
                    if(recBuff!=null){
                        String recv = new String(recBuff);
                        String cut = " ";
                        String[] newStr = recv.split(cut);	// 分割成数组
                        updateUI(newStr[0]);//可直接显示数据
                    }
                }else{
                    //收到普通测量值
                    updateUI(new String(recBuff));//可直接显示数据
                }

                //收到频谱采集部分
                //recBuff 原始数据数组，CMDtype 返回数据类型，tag 数据长度
                System.out.println((recBuff.length)+"/"+CMDtype+"/"+tag);
            }
        });
        btnSubmit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                vibrationValue = etRealValue.getText().toString().trim();
                if(vibrationValue.equals("")){
                    showToast("实际值不能为空");
                }else{
                    AuditDialog auditDialog = new AuditDialog(context, "确定要保存数据吗？", new AuditDialog.AuditDialogListener() {
                        @Override
                        public void confirm() {
                            if (isEdit) {
                                if(!etRealValue.getText().toString().trim().equals("")){
                                    String dateNow = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
                                    ContentValues values = new ContentValues();
                                    values.put("isWorkChecked", true);
                                    values.put("SCNR", vibrationValue);
                                    values.put("DATE", dateNow);
                                    DataSupport.updateAll(Dqgz.class, values, "rwid = ? and username = ? ",dqgz.getRWID(),username);
                                    dqgz.setWorkChecked(true);
                                    dqgz.setDATE(dateNow);
                                    dqgz.setSCNR(vibrationValue);
                                    dqgz.setSCBZ("");
                                    Intent intent = new Intent(Contans.ACTION_YULTWO);
                                    Bundle bundle = new Bundle();
                                    bundle.putParcelable("bean", dqgz);
                                    intent.putExtras(bundle);
                                    //发送广播
                                    sendBroadcast(intent);
                                }
                            }
                            Intent intent = new Intent();
                            intent.putExtra("value", vibrationValue);
                            setResult(RESULT_OK, intent);
                            finish();
                        }

                        @Override
                        public void cancel() {

                        }
                    });
                    auditDialog.show();
                }
            }
        });
        rgLevel.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup radioGroup, int i) {
                switch (i){
                    case R.id.rb1:
                        level = 0;
                        demo();//测量
                        break;
                    case R.id.rb2:
                        level = 1;
                        demo();//测量
                        break;
                }
            }
        });
        rgType.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup radioGroup, int i) {
                switch (i){
                    case R.id.rb3:
                        checkVibrationType = MTnativeInterface.CMD_VIBD_R;
                        etRealTitle.setText("实际值(mm):");
                        demo();//测量
                        break;
                    case R.id.rb4:
                        checkVibrationType = MTnativeInterface.CMD_VIBV_R;
                        etRealTitle.setText("实际值(mm/s):");
                        demo();//测量
                        break;
                    case R.id.rb5:
                        checkVibrationType = MTnativeInterface.CMD_VIBA_R;
                        etRealTitle.setText("实际值(mm/(s^2)):");
                        demo();//测量
                        break;
                }
            }
        });
        noticeValue.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View view) {
                //Toast.makeText(context, "onLongClick", Toast.LENGTH_SHORT).show();
                EditDialog editDialog = new EditDialog(context);
                editDialog.setMessage(noticeValue.getText().toString().trim());
                editDialog.setYesOnclickListener("确定", new EditDialog.onYesOnclickListener() {
                    @Override
                    public void onYesClick(String phone) {
                        if (!TextUtils.isEmpty(phone)) {
                            noticeValue.setText(phone);
                        }
                        //让软键盘隐藏
                        InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
                        if (imm.isActive()) {
                            imm.toggleSoftInput(InputMethodManager.HIDE_IMPLICIT_ONLY, 0); // 隐藏
                        }
                        editDialog.dismiss();
                    }
                });
                editDialog.setNoOnclickListener("取消", new EditDialog.onNoOnclickListener() {
                    @Override
                    public void onNoClick() {
                        //让软键盘隐藏
                        InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
                        if (imm.isActive()) {
                            imm.toggleSoftInput(InputMethodManager.HIDE_IMPLICIT_ONLY, 0); // 隐藏
                        }
                        editDialog.dismiss();
                    }
                });
                editDialog.show();
                return false;
            }
        });
    }

    @Override
    public void initData() {
        intentTemplate = getIntent();
        dqgz = intentTemplate.getParcelableExtra("bean");
        if (dqgz != null) {
            if(dqgz.getZX_MC()!=null){
                standerTip.setText(dqgz.getZX_MC());
            }
            if(dqgz.getZX_NR()!=null){
                checkTip.setText(dqgz.getZX_NR());
            }
            if(dqgz.getSCNR()!=null){
                etRealValue.setText(dqgz.getSCNR());
            }
        }
    }

    @Override
    protected void onResume() {
        //demo();//测量
        super.onResume();
    }

    @Override
    protected void onPause() {
        //使用完一定记得关闭电源
        mt.RFIDclose();
        mt.IRTclose();
        mt.VIBclose();
        mt.RPMclose();
        super.onPause();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_left:
                finish();
                break;
            case R.id.tv_right:
                if(isEdit){
                    //测量
                    demo();
                }
                break;
        }
    }

    public void demo(){
        /*=======测振示例，参数说明见“说明文档.txt”================================================================*/
        mt.VIBopen();//开启电源。
        //振动值测量。（振动值测量和频谱采集同时只能使用其中一个）
        //读振动加速度（加速度回传了2个值，取第一个就可以）
        //CMD_VIBA_R  振动加速度（加速度回传了2个值，取第一个就可以）
        //CMD_VIBD_R  振动位移
        //CMD_VIBA_R  振动速度
        mt.VIBread(checkVibrationType,level);
    }

    public void updateUI(final String info) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if(info!=null){
                    if(etRealValue!=null){
                        etRealValue.setText(info);
                    }
                }
            }
        });
    }

    @Override
    protected void onDestroy() {
        //使用完一定记得关闭电源
        mt.RFIDclose();
        mt.IRTclose();
        mt.VIBclose();
        mt.RPMclose();
        super.onDestroy();
    }

}