package com.rehome.sgbaxj.activity.sbxj;

import android.content.BroadcastReceiver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import com.rehome.sgbaxj.DBModel.XSJJHDataBean;
import com.rehome.sgbaxj.R;
import com.rehome.sgbaxj.adapter.MyFragmentAdapter;
import com.rehome.sgbaxj.base.BaseActivity3;
import com.rehome.sgbaxj.bean.SetxjSbModel;
import com.rehome.sgbaxj.bleUtil.BluetoothLeService;
import com.rehome.sgbaxj.contans.Contans;
import com.rehome.sgbaxj.utils.SPUtils;
import com.rehome.sgbaxj.weight.AutoRadioGroup;
import com.rehome.sgbaxj.weight.NoscrollViewPager;

import org.litepal.crud.DataSupport;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import androidx.fragment.app.Fragment;


/**
 * Created by ruihong on 2017/11/30.
 */

public class SbxjcjsbActivity extends BaseActivity3 implements View.OnClickListener {

    public static int Req = 101;

    NoscrollViewPager vp;
    RadioButton rb1;
    RadioButton rb2;
    RadioButton rb3;
    AutoRadioGroup rg;
    Button btnSaveNext;
    Button btnNext;
    Button btnLast;

    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 String smfs;
    private String type = null;

    //新数据
    private ArrayList<XSJJHDataBean> xsjjhDataBeanArrayList;
    private ArrayList<SetxjSbModel> setSbModelList;


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

    @Override
    public void initView() {
        username = (String) SPUtils.get(context, Contans.USERID, "");
        vp = findViewById(R.id.vp);
        rb1 = findViewById(R.id.rb1);
        rb2 = findViewById(R.id.rb2);
        rb3 = findViewById(R.id.rb3);
        rg = findViewById(R.id.rg);
        btnSaveNext = findViewById(R.id.btn_save_next);
        btnNext = findViewById(R.id.btn_next);
        btnLast = findViewById(R.id.btn_last);
        btnLast.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                --item;
                if (item == 0) {
                    btnLast.setEnabled(false);
                    item++;
                    showToast("当前为第一条");
                } else {
                    xjcjFragment.updata(xsjjhDataBeanArrayList.get(item - 1), item, xsjjhDataBeanArrayList.size());
                }
            }
        });
        btnNext.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                next();
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_left:

                Intent intent2 = new Intent(SbxjcjsbActivity.this, SbxjcjsbActivity.class);
                intent2.putParcelableArrayListExtra("setSbModelList", setSbModelList);
                setResult(RESULT_OK, intent2);
                finish();

                break;
            case R.id.tv_right://这里

                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode != RESULT_OK) return;

        if (requestCode == Req) {

            if (data != null) {

                setSbModelList = data.getParcelableArrayListExtra("setSbModelList");

                //更新数据源
                for (int i = 0; i < setSbModelList.size(); i++) {
                    for (int j = 0; j < xsjjhDataBeanArrayList.size(); j++) {
                        if (xsjjhDataBeanArrayList.get(j).getSbid().equals(setSbModelList.get(i).getSbId())) {
                            xsjjhDataBeanArrayList.get(j).setCJJG(setSbModelList.get(i).getValue());
                            xsjjhDataBeanArrayList.get(j).setChecked(setSbModelList.get(i).getStatu());
                        }
                    }
                }

                //更新当前的检查配件状态
                if (xjcjFragment != null) {
                    xjcjFragment.updateState(xsjjhDataBeanArrayList.get(index).getCJJG());
                    xjcjFragment.updatecheck(xsjjhDataBeanArrayList.get(index).isChecked());
                    xjcjFragment.updateFXNR(xsjjhDataBeanArrayList.get(index).getFxnr());
                }
            }
        }


    }

    public void initData() {
        initToolbar("设备巡检详情", "", this);
        registerReceiver(mGattUpdateReceiver, makeGattUpdateIntentFilter());
        Bundle bundle = SbxjcjsbActivity.this.getIntent().getExtras();
        if (bundle != null) {
            isEdit = bundle.getBoolean("edit");
            smfs = bundle.getString("smfs");
            xsjjhDataBeanArrayList = bundle.getParcelableArrayList("xsjjhDataBeanArrayList");
            index = bundle.getInt(Contans.KEY_ITEM);
            item = bundle.getInt(Contans.KEY_ITEM) + 1;
            //itemposition = bundle.getInt("itemposition");
            LX = bundle.getString("LX");
            type = bundle.getString("type");
            LXResult = bundle.getString("LXResult");
        }

        if (!isEdit) {
            btnSaveNext.setVisibility(View.GONE);
        }
        list = new ArrayList<>();
        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 (xsjjhDataBeanArrayList.size() != 0) {
            if (!btnLast.isEnabled()) {
                btnLast.setEnabled(true);
            }
            if (isEdit) {

                if (!xjcjFragment.getCJJG().equals("")) {
                    ContentValues values = new ContentValues();
                    values.put("smfs", smfs);
                    values.put("checked", true);
                    values.put("CJJG", xjcjFragment.getCJJG());
                    if(xjcjFragment.getYc_Fxnr()!=null){
                        values.put("fxnr", xjcjFragment.getYc_Fxnr());
                    }
                    values.put("DATE", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
                    int i = DataSupport.updateAll(XSJJHDataBean.class, values, "scid = ? and mk = ? and username = ? ", xsjjhDataBeanArrayList.get(item - 1).getScid(),type,username);
                    if (i != 0) {
                        xsjjhDataBeanArrayList.get(item - 1).setChecked(true);
                        xsjjhDataBeanArrayList.get(item - 1).setCJJG(xjcjFragment.getCJJG());
                        xsjjhDataBeanArrayList.get(item - 1).setFxnr(xjcjFragment.getYc_Fxnr());
                        showToast("保存成功");
                        updateItem(xjcjFragment.getCJJG(), item - 1,xsjjhDataBeanArrayList.get(item - 1).getScid());
                    }
                } else {
                    showToast("没有采集结果");
                }

                if (!xjcjFragment.getCJJG().equals("")) {
                    ++item;
                    if (item > xsjjhDataBeanArrayList.size()) {
                        item--;
                        xjcjFragment.updata(xsjjhDataBeanArrayList.get(item - 1), item, xsjjhDataBeanArrayList.size());
                        finish();
                        //showToast("到底了");
                    } else {
                        xjcjFragment.updata(xsjjhDataBeanArrayList.get(item - 1), item, xsjjhDataBeanArrayList.size());
                    }
                } else {
                    showToast("没有采集结果");
                }


            } else {
                if (xsjjhDataBeanArrayList.size() != 0) {
                    ++item;
                    if (!btnLast.isEnabled()) {
                        btnLast.setEnabled(true);
                    }
                    if (item > xsjjhDataBeanArrayList.size()) {
                        item--;
//                        finish();

                    } else {
                        xjcjFragment.updata(xsjjhDataBeanArrayList.get(item - 1), item, xsjjhDataBeanArrayList.size());

                    }
                }
            }
        }
    }

    public int getItem() {
        return item - 1;
    }


    private void updateItem(String name, int position,String scid) {
        Intent intent = new Intent(Contans.ACTION_YULONE);
        //intent.putExtra(Contans.KEY_POSITION, position);
        intent.putExtra(Contans.KEY_NAME, name);
        intent.putExtra(Contans.SCID, scid);
        //发送广播
        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();
    }
}
