package com.rehome.sgbaxj.activity.sbxdj;

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.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.Toast;
import com.rehome.sgbaxj.DBModel.QYDDATABean;
import com.rehome.sgbaxj.R;
import com.rehome.sgbaxj.adapter.MyFragmentAdapter;
import com.rehome.sgbaxj.base.BaseActivity3;
import com.rehome.sgbaxj.bean.SetSbModel;
import com.rehome.sgbaxj.bleUtil.BluetoothLeService;
import com.rehome.sgbaxj.contans.Contans;
import com.rehome.sgbaxj.weight.AutoRadioGroup;
import com.rehome.sgbaxj.weight.NoscrollViewPager;
import com.rehome.sgbaxj.weight.toastviewbymyself;

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 SbxdjcjsbActivity extends BaseActivity3 {

    //录入和选择
    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 CJFragment cj;
    private FfFragment ff;
    private BzFragment bz;
    private int item = 0;//当前的item
    private boolean isEdit = true;
    private int index = 0;
    private int itemposition;
    private String LX, LXResult;
    private ArrayList<QYDDATABean> qyddataBeanArrayList;
    private SimpleDateFormat sdf;
    private ArrayList<SetSbModel> setSbModelList;

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

    @Override
    public void initView() {
        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 {
                    cj.updata(qyddataBeanArrayList.get(item - 1), item, qyddataBeanArrayList.size());
                    bz.updata(qyddataBeanArrayList.get(item - 1).getBZZ());
                    ff.update(qyddataBeanArrayList.get(item - 1).getJCFS());
                }
            }
        });
        btnNext.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                next();
            }
        });
    }

    @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 < qyddataBeanArrayList.size(); j++) {
                        if (qyddataBeanArrayList.get(j).getSBID().equals(setSbModelList.get(i).getSbId())) {
                            qyddataBeanArrayList.get(j).setCJJG(setSbModelList.get(i).getValue());
                            qyddataBeanArrayList.get(j).setChecked(setSbModelList.get(i).getStatu());
                        }
                    }
                }
                if (cj != null) {
                    cj.updateState(qyddataBeanArrayList.get(index).getCJJG());
                    cj.updateFXNR(qyddataBeanArrayList.get(index).getFXNR());
                    cj.updatecheck(qyddataBeanArrayList.get(index).isChecked());
                }
            }
        }
    }

    public void initData() {

        initToolbar("设备点检信息", "", new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        });

        registerReceiver(mGattUpdateReceiver, makeGattUpdateIntentFilter());
        sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Bundle bundle = SbxdjcjsbActivity.this.getIntent().getExtras();
        if (bundle != null) {
            isEdit = bundle.getBoolean("edit");
            qyddataBeanArrayList = bundle.getParcelableArrayList(Contans.KEY_DJJHRWQY);
            index = bundle.getInt(Contans.KEY_ITEM);
            item = bundle.getInt(Contans.KEY_ITEM) + 1;
            itemposition = bundle.getInt("itemposition");
            LX = bundle.getString("LX");
            LXResult = bundle.getString("LXResult");
        }

        if (!isEdit) {
            btnSaveNext.setVisibility(View.GONE);
        }
        list = new ArrayList<>();
        if (qyddataBeanArrayList.size() != 0) {
            cj = CJFragment.newInstance(isEdit, qyddataBeanArrayList.get(index), qyddataBeanArrayList.size(), index + 1);
            ff = FfFragment.newInstance(isEdit, qyddataBeanArrayList.get(index).getJCFS());
            bz = BzFragment.newInstance(isEdit, qyddataBeanArrayList.get(index).getBZZ());
        } else {
            cj = CJFragment.newInstance(isEdit, new QYDDATABean(), 0, 0);
            ff = FfFragment.newInstance(isEdit, "");
            bz = BzFragment.newInstance(isEdit, "");
        }
        list.add(cj);
        list.add(ff);
        list.add(bz);
        adapter = new MyFragmentAdapter(getSupportFragmentManager(), list);
        vp.setAdapter(adapter);
        vp.setOffscreenPageLimit(3);
        rg.setOnCheckedChangeListener((radioGroup, i) -> {
            if(i==R.id.rb1){
                rb1.setTextColor(Color.WHITE);
                rb2.setTextColor(Color.GRAY);
                rb3.setTextColor(Color.GRAY);
                vp.setCurrentItem(0, false);
            }else if(i==R.id.rb2){
                rb1.setTextColor(Color.GRAY);
                rb2.setTextColor(Color.WHITE);
                rb3.setTextColor(Color.GRAY);
                vp.setCurrentItem(1, false);
            }else if(i==R.id.rb3){
                rb1.setTextColor(Color.GRAY);
                rb2.setTextColor(Color.GRAY);
                rb3.setTextColor(Color.WHITE);
                vp.setCurrentItem(2, false);
            }
        });
    }

    public void next() {
        if (qyddataBeanArrayList.size() != 0) {
            btnNext.setEnabled(false);//避免“点击下一条”操作过快
            if (isEdit) {
                if (TextUtils.isEmpty(cj.getCJJG())) {
                    toastviewbymyself.makeText(context, "你没有数据采集结果!", Toast.LENGTH_SHORT).show();
                } else {
                    ContentValues values = new ContentValues();
                    values.put("checked", true);
                    values.put("CJJG", cj.getCJJG());
                    values.put("FXNR", cj.getYc_Fxnr());
                    values.put("DATE", sdf.format(new Date()));
                    int i = DataSupport.updateAll(QYDDATABean.class, values, "SCID = ?", qyddataBeanArrayList.get(item - 1).getSCID());
                    if (i != 0) {
                        qyddataBeanArrayList.get(item - 1).setChecked(true);
                        qyddataBeanArrayList.get(item - 1).setCJJG(cj.getCJJG());
                        showToast("保存数据成功!!");
                        updateItem(cj.getCJJG(), item - 1);
                    } else {
                        showToast("保存数据失败!!");
                    }
                    item++;
                    if (item > qyddataBeanArrayList.size()) {
                        item--;
                        cj.updata(qyddataBeanArrayList.get(item - 1), item, qyddataBeanArrayList.size());
                        showToast("最后一条数据了");
                        setResult(RESULT_OK, new Intent(SbxdjcjsbActivity.this, Yul_SBActivity.class));
                        finish();
                    } else {
                        cj.updata(qyddataBeanArrayList.get(item - 1), item, qyddataBeanArrayList.size());
                        bz.updata(qyddataBeanArrayList.get(item - 1).getBZZ());
                        ff.update(qyddataBeanArrayList.get(item - 1).getJCFS());
                    }
                }
            } else {
                item++;
                if (item > qyddataBeanArrayList.size()) {
                    item--;
                    showToast("最后一条数据了");
                } else {
                    cj.updata(qyddataBeanArrayList.get(item - 1), item, qyddataBeanArrayList.size());
                    bz.updata(qyddataBeanArrayList.get(item - 1).getBZZ());
                    ff.update(qyddataBeanArrayList.get(item - 1).getJCFS());
                }
            }
            btnNext.setEnabled(true);
            if (!btnLast.isEnabled()) {
                btnLast.setEnabled(true);
            }
        }
    }

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

    private void updateItem(String name, int position) {
        Intent intent = new Intent(Contans.ACTION_YULONE);
        intent.putExtra(Contans.KEY_POSITION, position);
        intent.putExtra(Contans.KEY_NAME, name);
        sendBroadcast(intent);

    }


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