package com.bjzc.zjyxdxj.activity.regular;


import android.annotation.SuppressLint;
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.TextView;

import com.bjzc.zjyxdxj.DBModel.Dqgz;
import com.bjzc.zjyxdxj.R;
import com.bjzc.zjyxdxj.contans.Contans;
import com.bjzc.zjyxdxj.utils.SPUtils;
import com.bjzc.zjyxdxj.weight.AuditDialog;
import com.bjzc.zjyxdxj.weight.EditDialog;
import com.rinsun.mtdriver.MTnativeInterface;
import com.bjzc.zjyxdxj.base.BaseActivity3;

import org.litepal.crud.DataSupport;

import java.text.SimpleDateFormat;
import java.util.Date;


public class CheckTemperatureDqgzActivity extends BaseActivity3 implements View.OnClickListener {

    EditText etRealValue;
    EditText noticeValue;
    Button btnSubmit;
    TextView checkTip;
    TextView standerTip;


    private String temperatureValue;
    //public static final int RESULT_SUCCESS = 1;
    //private String checkType;
    //是否可编辑
    private boolean isEdit = false;
    private String username;

    //频谱用到的变量/////////////////////////////
    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;
    //页面传过来的数据
    Dqgz dqgz;

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

    @Override
    public void initView() {
        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);

        etRealValue.setEnabled(true);
        username = (String) SPUtils.get(context, Contans.USERID, "");
        Bundle bundle = CheckTemperatureDqgzActivity.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);

                //收到普通测量值
                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) {
                temperatureValue = etRealValue.getText().toString();
                if(temperatureValue.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", temperatureValue);
                                    values.put("DATE", dateNow);
                                    DataSupport.updateAll(Dqgz.class, values, "rwid = ? and username = ? ",dqgz.getRWID(),username);
                                    dqgz.setWorkChecked(true);
                                    dqgz.setDATE(dateNow);
                                    dqgz.setSCNR(temperatureValue);
                                    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", temperatureValue);
                            //intent.putExtra("checkType", checkType);
                            setResult(RESULT_OK, intent);
                            finish();
                        }

                        @Override
                        public void cancel() {

                        }
                    });
                    auditDialog.show();
                }
            }
        });
        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;
            }
        });
    }

    @SuppressLint("SetTextI18n")
    @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() {
        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.RFIDopen(MTnativeInterface.CARD_14443);//开启电源。(不可与振动同时打开,它们共用硬件资源)
        //mt.RFIDread(-1,"");


        /*======转速示例============================================================================================*/
        //mt.RPMopen();//开启电源。

        /*=====测温示例，参数说明见“说明文档.txt”=================================================================*/
        mt.IRTopen(MTnativeInterface.TEMP_25);//开启电源。
        mt.IRTread(95);

        /*=======测振示例，参数说明见“说明文档.txt”================================================================*/
//        mt.VIBopen();//开启电源。
//        //振动值测量。（振动值测量和频谱采集同时只能使用其中一个）
//        mt.VIBread(MTnativeInterface.CMD_VIBD_R,0);

        //频谱采集测量。
        // mt.VIBset(MTnativeInterface.CMD_ALL_W,"RK");//频谱采集前，必须读取一次"频谱参数"，频谱计算过程要用到
//        Button but = (Button) findViewById(R.id.button1);
//        but.setText("频谱采集");
//        but.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View view) {
//                ppfreq=1280;//可选频率 1280 5120 12800
//                pplen=1024;//对应返回数据长度1024, 4096, 8192
//                ppsour = new double[pplen];
//                //开始频谱采集，参数CMDtype采样类型有三个可选CMD_VIBA_P加速度、CMD_VIBD_P位移、CMD_VIBV_P速度。参数level采样频率有三个可选 1280 5120 12800
//                //mt.VIBread(MTnativeInterface.CMD_VIBA_P,ppfreq);
//                //执行下面代码可停止频谱采集
//                //mt.VIBread(0,0);
//            }
//        });
//        Button btnSecond = (Button) findViewById(R.id.button2);
//        btnSecond.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View view) {
//
//            }
//        });
    }

    private double  getRK(int type){
        double res=0.0;
        switch(type) {
            case MTnativeInterface.CMD_VIBA_P:
                res = edit16LA;
            case MTnativeInterface.CMD_VIBV_P:
                res=edit16LV;
            case MTnativeInterface.CMD_VIBD_P:
                res=edit16LD;
        }
        return res;
    }

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

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