package com.bjzc.bhzhgd.activity.regular;


import android.content.BroadcastReceiver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.localbroadcastmanager.content.LocalBroadcastManager;

import com.bjzc.bhzhgd.DBModel.Dqgz;
import com.bjzc.bhzhgd.R;
import com.bjzc.bhzhgd.base.BaseActivity3;
import com.bjzc.bhzhgd.bleUtil.BluetoothLeService;
import com.bjzc.bhzhgd.contans.Contans;
import com.bjzc.bhzhgd.utils.SPUtils;
import com.bjzc.bhzhgd.weight.AuditDialog;
import com.bjzc.bhzhgd.weight.ListDialog;
import org.litepal.crud.DataSupport;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * Created by ruihong on 2017/11/30.
 */
public class DqgzCheckActivity extends BaseActivity3 {

    public static int Req = 101;
    TextView tvBjmc;
    TextView tvSbmc;
    EditText etJg;
    Button xjetButton;
    LinearLayout ycmsLl;
    EditText etYcFxnr;
    Button btnNext;
    TextView tvZt;

    //private MyFragmentAdapter adapter;
    //private List<Fragment> list;
    //private XJCJFragment xjcjFragment;
    //private int item = 0;
    private boolean isEdit = false;
    //    private int index = 0;
    //private int itemposition;
    //private String LX, LXResult;
    private String username;

    //新数据
    private Dqgz dqgz;
    private String MRNR;
    //private ArrayList<SetxjSbModel> setSbModelList;


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

    @Override
    public void initView() {
        username = (String) SPUtils.get(context, Contans.USERID, "");

        tvBjmc = findViewById(R.id.tv_bjmc);
        tvSbmc = findViewById(R.id.tv_sbmc);
        etJg = findViewById(R.id.et_jg);
        xjetButton = findViewById(R.id.xjet_button);
        ycmsLl = findViewById(R.id.ycms_ll);
        etYcFxnr = findViewById(R.id.et_yc_fxnr);
        btnNext = findViewById(R.id.btn_next);
        tvZt = findViewById(R.id.tv_zt);



        ycmsLl.setVisibility(View.GONE);
        initToolbar("设备巡检详情", "", new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                AuditDialog auditDialog = new AuditDialog(context, "确定要保存数据吗？", new AuditDialog.AuditDialogListener() {
                    @Override
                    public void confirm() {
                        next();
                    }

                    @Override
                    public void cancel() {

                    }
                });
                auditDialog.show();
            }
        });

        btnNext.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        });
        registerReceiver(mGattUpdateReceiver, makeGattUpdateIntentFilter());
        Bundle bundle = DqgzCheckActivity.this.getIntent().getExtras();
        if (bundle != null) {
            isEdit = bundle.getBoolean("edit");
            dqgz = bundle.getParcelable("bean");
        }
        if(dqgz!=null) {
            if (dqgz.getZX_LRNR() != null) {
                MRNR = dqgz.getZX_LRNR();
                if(MRNR!=null){
                    xjetButton.setOnClickListener(v -> {
                        ListDialog dialog = new ListDialog(context, stringToList(MRNR), (text, position) -> {
                            xjetButton.setText(text);
                            etJg.setText(text);
                            if (text.equals("正常")){
                                ycmsLl.setVisibility(View.GONE);
                            }else if (text.equals("异常")){
                                ycmsLl.setVisibility(View.VISIBLE);
                            }
                        });
                        dialog.show();
                    });
                }
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
    }

    public void initData() {

        if(dqgz!=null){
            if(dqgz.getZX_MC()!=null){
                tvSbmc.setText(dqgz.getZX_MC());
            }
            if(dqgz.getZX_NR()!=null){
                tvBjmc.setText(dqgz.getZX_NR());
            }
            if(dqgz.getSCBZ()!=null){
                etYcFxnr.setText(dqgz.getSCBZ());
            }
            if(dqgz.isWorkChecked()){
                tvZt.setText("已检");
            }
            if(dqgz.getZX_LRFS().equals("1")){
                etJg.setVisibility(View.GONE);
                //ycmsLl.setVisibility(View.GONE);
                xjetButton.setVisibility(View.VISIBLE);
                etYcFxnr.setText("");
                if (dqgz.getSCNR() == null) {
                    xjetButton.setText("正常");
                    etJg.setText("正常");
                    ycmsLl.setVisibility(View.GONE);
                } else {
                    switch (dqgz.getSCNR()) {
                        case "已运行":
                            xjetButton.setText("正常");
                            etJg.setText("正常");
                            ycmsLl.setVisibility(View.GONE);
                            break;
                        case "大小修":
                            xjetButton.setText("大小修");
                            etJg.setText("大小修");
                            ycmsLl.setVisibility(View.GONE);
                            break;
                        case "已停用":
                            xjetButton.setText("已停用");
                            etJg.setText("已停用");
                            ycmsLl.setVisibility(View.GONE);
                            break;
                        case "异常":
                            ycmsLl.setVisibility(View.VISIBLE);
                            xjetButton.setText("异常");
                            etJg.setText("异常");
                            if(dqgz.getSCBZ()!=null){
                                etYcFxnr.setText(dqgz.getSCBZ());
                            }
                            break;
                        case "":
                            xjetButton.setText("正常");
                            etJg.setText("正常");
                            ycmsLl.setVisibility(View.GONE);
                            break;
                        default:
                            xjetButton.setText(dqgz.getSCNR());
                            etJg.setText(dqgz.getSCNR());
                            ycmsLl.setVisibility(View.GONE);
                            break;
                    }
                }
            }
            if(dqgz.getZX_LRFS().equals("0")){
                etJg.setVisibility(View.VISIBLE);
                //ycmsLl.setVisibility(View.GONE);
                xjetButton.setVisibility(View.GONE);
                etYcFxnr.setText("");
                if (dqgz.getSCNR() == null) {
                    etJg.setText("");
                } else {
                    switch (dqgz.getSCNR()) {
                        case "已运行":
                            etJg.setText("");
                            break;
                        case "大小修":
                            etJg.setText("大小修");
                            break;
                        case "已停用":
                            etJg.setText("已停用");
                            break;
                        case "":
                            etJg.setText("");
                            break;
                        default:
                            etJg.setText(dqgz.getSCNR());
                            break;
                    }
                }
            }
        }


//        if (xsjjhDataBeanArrayList.size() != 0) {
//            xjcjFragment = XJCJFragment.newInstance(isEdit, xsjjhDataBeanArrayList.get(index), xsjjhDataBeanArrayList.size(), index + 1);
//        } else {
//            xjcjFragment = XJCJFragment.newInstance(isEdit, new XSJJHDataBean(), 0, 0);
//        }
//        list.add(xjcjFragment);

//        adapter = new MyFragmentAdapter(getSupportFragmentManager(), list);
//        vp.setAdapter(adapter);
//        vp.setOffscreenPageLimit(3);
//        rg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
//            @Override
//            public void onCheckedChanged(RadioGroup radioGroup, int i) {
//
//                switch (i) {
//                    case R.id.rb1:
//                        rb1.setTextColor(Color.WHITE);
//                        rb2.setTextColor(Color.GRAY);
//                        rb3.setTextColor(Color.GRAY);
//                        vp.setCurrentItem(0, false);
//                        break;
//                    case R.id.rb2:
//                        rb1.setTextColor(Color.GRAY);
//                        rb2.setTextColor(Color.WHITE);
//                        rb3.setTextColor(Color.GRAY);
//                        vp.setCurrentItem(1, false);
//                        break;
//                    case R.id.rb3:
//                        rb1.setTextColor(Color.GRAY);
//                        rb2.setTextColor(Color.GRAY);
//                        rb3.setTextColor(Color.WHITE);
//                        vp.setCurrentItem(2, false);
//                        break;
//                }
//            }
//        });

    }

    public void next() {
        if(etJg.getText().toString().trim().equals("")){
            showToast("没有采集结果");
        }else{
            ContentValues values = new ContentValues();
            values.put("isWorkChecked", true);
            values.put("SCNR", etJg.getText().toString().trim());
            values.put("SCBZ", etYcFxnr.getText().toString().trim());
            String dateNow = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
            values.put("DATE",dateNow);
            int i = DataSupport.updateAll(Dqgz.class, values, "rwid = ? and username = ? ", dqgz.getRWID(),username);
            if (i != 0) {
                dqgz.setWorkChecked(true);
                dqgz.setDATE(dateNow);
                dqgz.setSCNR(etJg.getText().toString().trim());
                dqgz.setSCBZ(etYcFxnr.getText().toString().trim());
                showToast("保存成功");
                updatecheck(true);
                updateItem(dqgz);
                finish();
            }
        }
    }

    private void updateItem(Dqgz dqgzTemp) {
        Intent intent = new Intent(Contans.ACTION_YULTWO);
        Bundle bundle = new Bundle();
        bundle.putParcelable("bean", dqgzTemp);
        intent.putExtras(bundle);
        //发送广播
        LocalBroadcastManager.getInstance(context).sendBroadcast(intent);;
    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
            finish();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    private final BroadcastReceiver mGattUpdateReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            final String action = intent.getAction();
            String Data = "";
            if (BluetoothLeService.ACTION_DATA_AVAILABLE.equals(action)) {
                String BleData = intent.getStringExtra(BluetoothLeService.EXTRA_DATA);
                String type = BleData.substring(0, 1);
                if (type.equals("T")) {
                    Data = "温度:" + BleData.substring(2, 6);
                } else {
                    Data = "震动:" + BleData.substring(2, 6);
                }
                //xjcjFragment.getBlueToothData(Data);
            }
        }
    };

    static IntentFilter makeGattUpdateIntentFilter() {
        final IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(BluetoothLeService.ACTION_GATT_CONNECTED);
        intentFilter.addAction(BluetoothLeService.ACTION_GATT_DISCONNECTED);
        intentFilter.addAction(BluetoothLeService.ACTION_GATT_SERVICES_DISCOVERED);
        intentFilter.addAction(BluetoothLeService.ACTION_DATA_AVAILABLE);
        return intentFilter;
    }

    @Override
    protected void onDestroy() {
        unregisterReceiver(mGattUpdateReceiver);
        super.onDestroy();
    }

    public void updatecheck(Boolean value) {
        if (value) {
            tvZt.setText("已检");
        } else {
            tvZt.setText("未检");
        }
    }

    private List<String> stringToList(String strs) {
        String[] str = strs.split(";");
        return Arrays.asList(str);
    }
}
