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.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import com.rehome.sgbaxj.DBModel.QYDDATABean;
import com.rehome.sgbaxj.R;
import com.rehome.sgbaxj.adapter.DlbAdapter;
import com.rehome.sgbaxj.base.BaseActivity;
import com.rehome.sgbaxj.bean.DlbInfo;
import com.rehome.sgbaxj.bean.sbInfo;
import com.rehome.sgbaxj.contans.Contans;

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

import static org.litepal.crud.DataSupport.where;

public class Yul_SBActivity extends BaseActivity {

    private static final int Req = 101;

    ListView lv;
    TextView txSetsbmc;
    Button btTY;
    Button btYC;
    Button btBY;

    private boolean isEdit = true;
    private int item;
    private SimpleDateFormat sdf;
    private String GWID, QYBH;
    private ArrayList<QYDDATABean> qyddataBeanArrayList_SB = new ArrayList<>();//点检记录列表
    private List<DlbInfo> infos = new ArrayList<>();
    private View headView;
    private DlbAdapter adapter;
    private int itemposition;
    private String LX, LXResult, SBID;
    private long xdjjhxzDataBean_id;
    private List<sbInfo> sbInfoList;//当前设备页列表
    private int itemIndex;//被点击的item索引


    private BroadcastReceiver myReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            switch (action) {
                case Contans.ACTION_YULONE: //更新设备点检页面返回时编辑的item内容
                    int position = intent.getIntExtra(Contans.KEY_POSITION, -1);
                    String name = intent.getStringExtra(Contans.KEY_NAME);
                    DlbInfo dlbInfo = infos.get(position);
                    dlbInfo.setCjjg(name);
                    dlbInfo.setStatu(true);
                    infos.set(position, dlbInfo);
                    QYDDATABean qyddataBean = qyddataBeanArrayList_SB.get(position);
                    qyddataBean.setChecked(true);
                    qyddataBean.setCJJG(name);
                    qyddataBeanArrayList_SB.set(position, qyddataBean);
                    break;
                default:
                    break;
            }

        }
    };

    @Override
    public int getContentViewID() {
        return R.layout.activity_yul_sb;
    }

    @Override
    protected void initView() {
        lv = findViewById(R.id.lv);
        txSetsbmc = findViewById(R.id.tx_setsbmc);
        btTY = findViewById(R.id.bt_TY);
        btYC = findViewById(R.id.bt_YC);
        btBY = findViewById(R.id.bt_BY);

        setBack();
        setTitle("浏览点检数据");
        headView = View.inflate(context, R.layout.dlb_item, null);
        headView.findViewById(R.id.head).setVisibility(View.VISIBLE);
    }

    @Override
    public void initData() {
        sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Bundle bundle = getIntent().getExtras();
        isEdit = bundle.getBoolean("edit");
        item = bundle.getInt(Contans.KEY_ITEM);
        itemposition = bundle.getInt("itemposition");
        GWID = bundle.getString("GWID");
        LX = bundle.getString("LX");
        LXResult = bundle.getString("LXResult");
        xdjjhxzDataBean_id = bundle.getLong("xdjjhxzDataBean_id");
        sbInfoList = bundle.getParcelableArrayList("infos");
        itemIndex = bundle.getInt("itemIndex");
        SBID = sbInfoList.get(itemIndex).getSbid();
        QYBH = sbInfoList.get(itemIndex).getQybh();
        qyddataBeanArrayList_SB = (ArrayList<QYDDATABean>) where("SBID = ? and GWID = ? and QYBH = ?", SBID, GWID, QYBH).find(QYDDATABean.class);
        if (qyddataBeanArrayList_SB.size() > 0) {
            txSetsbmc.setText(qyddataBeanArrayList_SB.get(0).getSBMC());
        }
        setListAdapter();
        TYOnclick();
        IntentFilter filter = new IntentFilter();
        filter.addAction(Contans.ACTION_YULONE);
        registerReceiver(myReceiver, filter);
    }

    private void TYOnclick() {

        btTY.setOnClickListener(v -> {
            ContentValues values = new ContentValues();
            values.put("CJJG", "已停用");
            values.put("SBMCSTATE", "已停用");
            values.put("checked", true);
            values.put("SBMCSTATEVALUE", "3");
            values.put("DATE", sdf.format(new Date()));
            int i = DataSupport.updateAll(QYDDATABean.class, values, "SBID = ? and GWID = ? and QYBH = ?", SBID, GWID, QYBH);
            if (i != 0) {
                showToast("设置设备状态为已停用成功");
            } else {
                showToast("设置设备状态为已停用失败");
            }
            //点击停用时，根据itemIndex+1查找下一条数据，并更新界面
            itemIndex++;
            getDataList(itemIndex);
        });
        btBY.setOnClickListener(v -> {
            ContentValues values = new ContentValues();
            values.put("CJJG", "备用");
            values.put("SBMCSTATE", "备用");
            values.put("checked", true);
            values.put("SBMCSTATEVALUE", "5");
            values.put("DATE", sdf.format(new Date()));
            int i = DataSupport.updateAll(QYDDATABean.class, values, "SBID = ? and GWID = ? and QYBH = ?", SBID, GWID, QYBH);
            if (i != 0) {
                showToast("该设备改为备用状态成功");
            } else {
                showToast("该设备改为备用状态成功");
            }
            //点击停用时，根据itemIndex+1查找下一条数据，并更新界面
            itemIndex++;
            getDataList(itemIndex);
        });
        btYC.setOnClickListener(v -> {
            ContentValues values = new ContentValues();
//            values.put("CJJG", "");
            values.put("SBMCSTATE", "已运行");
            values.put("checked", false);
            values.put("SBMCSTATEVALUE", "2");
            int i = DataSupport.updateAll(QYDDATABean.class, values, "SBID = ? and GWID = ? and QYBH = ?", SBID, GWID, QYBH);
            if (i != 0) {
                showToast("设置设备状态为已运行成功");
            } else {
                showToast("设置设备状态为已运行失败");
            }
            qyddataBeanArrayList_SB = (ArrayList<QYDDATABean>) where("SBID = ? and GWID = ? and QYBH = ?", SBID, GWID, QYBH).find(QYDDATABean.class);
            Intent intent = new Intent(Yul_SBActivity.this, SbxdjcjsbActivity.class);
            Bundle bundle = new Bundle();
            bundle.putParcelableArrayList(Contans.KEY_DJJHRWQY, qyddataBeanArrayList_SB);
            bundle.putBoolean("edit", isEdit);
            bundle.putInt(Contans.KEY_ITEM, 0);
            bundle.putInt("itemposition", itemposition);
            bundle.putString("LX", LX);
            bundle.putString("LXResult", LXResult);
            intent.putExtras(bundle);
            startActivityForResult(intent, Req);
        });
    }

    /**
     * 获取更新数据列表,并更新页面
     */
    private void getDataList(int index) {
        if (sbInfoList != null) {
            if (index < sbInfoList.size()) {
                SBID = sbInfoList.get(index).getSbid();
                qyddataBeanArrayList_SB = (ArrayList<QYDDATABean>) where("SBID = ? and GWID = ? and QYBH = ?", SBID, GWID, QYBH).find(QYDDATABean.class);
                infos.clear();
                infos.addAll(filterCheckedData(qyddataBeanArrayList_SB));
                txSetsbmc.setText(qyddataBeanArrayList_SB.get(0).getSBMC());
                adapter.notifyDataSetChanged();
            } else {
                finish();
            }
        }
    }


    private void setListAdapter() {
        infos.clear();
        infos.addAll(filterCheckedData(qyddataBeanArrayList_SB));
        adapter = new DlbAdapter(context, infos);
        lv.addHeaderView(headView, null, false);
        lv.setAdapter(adapter);
        lv.setOnItemClickListener((parent, view, position, id) -> {

                if (qyddataBeanArrayList_SB != null) {
//                    if (qyddataBeanArrayList_SB.get(0).getSecond().equals("YES")) {
//                        qyddataBeanArrayList_SB = (ArrayList<QYDDATABean>) where("SBID = ?", SBID + "").find(QYDDATABean.class);

                        Intent intent = new Intent(Yul_SBActivity.this, SbxdjcjsbActivity.class);
                        Bundle bundle = new Bundle();
                        bundle.putParcelableArrayList(Contans.KEY_DJJHRWQY, qyddataBeanArrayList_SB);
                        bundle.putBoolean("edit", isEdit);
                        bundle.putInt(Contans.KEY_ITEM, position - 1);
                        bundle.putInt("itemposition", itemposition);
                        bundle.putString("LX", LX);
                        bundle.putString("LXResult", LXResult);
                        intent.putExtras(bundle);
                        startActivityForResult(intent, Req);
//                    } else {
//
//                    }
                }
        });
    }

    private List<DlbInfo> filterCheckedData(ArrayList<QYDDATABean> qyddataBeanArrayList) {
        List<DlbInfo> dlbInfos = new ArrayList<>();
        for (QYDDATABean rw : qyddataBeanArrayList) {   //这里进行了数据的一些获取 把必要的拿出来显示
            DlbInfo info = new DlbInfo();
            info.setSbid(rw.getSBID());
            info.setCjjg(rw.getCJJG());//采集结果
            info.setDian(rw.getSBMC() + " - " + rw.getBJMC());//项目名称
            info.setStatu(rw.isChecked());//状态
            dlbInfos.add(info);
        }
        return dlbInfos;
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != RESULT_OK) return;
        if (requestCode == Req) {
            itemIndex++;
            getDataList(itemIndex);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        adapter.notifyDataSetChanged();
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        adapter.notifyDataSetChanged();
    }

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