package com.bjzc.bhzhgd.activity.sbxj;

import static com.bjzc.bhzhgd.activity.sbxj.SbxjcjsbActivity.Req;

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.util.Log;
import android.view.View;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.bjzc.bhzhgd.DBModel.XSJJHDataBean;
import com.bjzc.bhzhgd.R;
import com.bjzc.bhzhgd.adapter.DlbAdapter;
import com.bjzc.bhzhgd.base.BaseActivity3;
import com.bjzc.bhzhgd.bean.DlbInfo;
import com.bjzc.bhzhgd.bean.SetxjSbModel;
import com.bjzc.bhzhgd.contans.Contans;
import com.bjzc.bhzhgd.utils.RSAUtils;
import com.bjzc.bhzhgd.utils.SPUtils;
import com.google.gson.Gson;

import org.litepal.crud.DataSupport;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import static org.litepal.crud.DataSupport.where;

import androidx.localbroadcastmanager.content.LocalBroadcastManager;

public class XjYulActivity extends BaseActivity3 {

    ListView lv;
    TextView tvNodata;
    private boolean isEdit = false;
    private int item;
    private String qybh;
    private ArrayList<XSJJHDataBean> xsjjhDataBeanArrayList = new ArrayList<>();
    private List<DlbInfo> infos = new ArrayList<>();
    private View headView;
    private DlbAdapter adapter;
    private String LX, LXResult;
    private ArrayList<SetxjSbModel> setxjSbModelArrayList;
    //测温
    public static final int REQUEST_CHECK_TEMPERATURE = 1;
    //测振
    public static final int REQUEST_CHECK_VIBRATION = 2;
    private String type = null;
    private String username;
    private String smfs;
    private Timer timer;

    private BroadcastReceiver myReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (Contans.ACTION_YULONE.equals(action)) { //更新设备点检页面返回时编辑的item内容
                String name = intent.getStringExtra(Contans.KEY_NAME);
                String scid = intent.getStringExtra(Contans.SCID);
                if (infos.size() > 0) {
                    for (int i = 0; i < infos.size(); i++) {
                        DlbInfo dlbInfo = infos.get(i);
                        if (dlbInfo.getScid().equals(scid)) {
                            dlbInfo.setCjjg(name);
                            dlbInfo.setStatu(true);
                        }
                    }
                }
                if (xsjjhDataBeanArrayList.size() > 0) {
                    for (int i = 0; i < xsjjhDataBeanArrayList.size(); i++) {
                        XSJJHDataBean xsjjhDataBean = xsjjhDataBeanArrayList.get(i);
                        if (xsjjhDataBean.getScid().equals(scid)) {
                            xsjjhDataBean.setChecked(true);
                            xsjjhDataBean.setCJJG(name);
                        }
                    }
                }
            }
        }
    };

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

    @Override
    public void initView() {
        lv = findViewById(R.id.lv);
        tvNodata = findViewById(R.id.tv_nodata);
        lv.setEmptyView(tvNodata);
        headView = View.inflate(context, R.layout.dlb_item, null);
        headView.findViewById(R.id.head).setVisibility(View.VISIBLE);
    }

    @Override
    public void initData() {
        Bundle bundle = getIntent().getExtras();
        isEdit = bundle.getBoolean("edit");
        item = bundle.getInt(Contans.KEY_ITEM);
        smfs = bundle.getString("smfs");
        type = bundle.getString("type");
        LX = bundle.getString("LX");
        LXResult = bundle.getString("LXResult");
        qybh = bundle.getString("qybh");

        String UserIDTemp = (String) SPUtils.get(context, Contans.USERID, "");
        username = RSAUtils.decryptBASE64StrLocal(UserIDTemp);

        searchdata();
        setListAdapter();
        IntentFilter filter = new IntentFilter();
        filter.addAction(Contans.ACTION_YULONE);
        //registerReceiver(myReceiver, filter);
        LocalBroadcastManager.getInstance(this).registerReceiver(myReceiver, filter);

        if (isEdit) {
            initToolbar("浏览巡检记录", "记录缺陷", new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                }
            });
            allCheckNow();
        } else {
            initToolbar("浏览巡检记录", "", new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                }
            });
        }
    }

    private void searchdata() {
        switch (LX) {
            case "Click":
                Log.i("app", String.valueOf(qybh == null));
                xsjjhDataBeanArrayList.clear();
                xsjjhDataBeanArrayList.addAll(where("qybh = ?  and mk = ? and username = ?", qybh, type, username).find(XSJJHDataBean.class));    //获取当前点击的工作栏对应的点检记录列表
                break;
            case "NFC": {
                List<XSJJHDataBean> xsjjhDataBeen = DataSupport.where("nfcbm = ? and mk = ? and username = ?", LXResult, type, username).find(XSJJHDataBean.class);
                xsjjhDataBeanArrayList.clear();
                xsjjhDataBeanArrayList.addAll(xsjjhDataBeen);
                break;
            }
            case "EWM": {
                List<XSJJHDataBean> xsjjhDataBeen = DataSupport.where("qybh = ? and mk = ? and username = ?", LXResult, type, username).find(XSJJHDataBean.class);
                xsjjhDataBeanArrayList.clear();
                xsjjhDataBeanArrayList.addAll(xsjjhDataBeen);
                break;
            }
        }
    }

    private void setListAdapter() {
        for (XSJJHDataBean rw : xsjjhDataBeanArrayList) {
            DlbInfo info = new DlbInfo();
            info.setScid(rw.getScid());
            info.setSbid(rw.getSbid());
            info.setCjjg(rw.getCJJG());
            info.setDian(rw.getJhmc() + "--" + rw.getSb() + "--" + rw.getBJMC());
            info.setStatu(rw.isChecked());
            infos.add(info);
        }
        Gson gson1 = new Gson();
        Log.i("app", gson1.toJson(infos));
        Log.i("app", gson1.toJson(xsjjhDataBeanArrayList));
        adapter = new DlbAdapter(context, infos);
        lv.addHeaderView(headView, null, false);
        lv.setAdapter(adapter);
        lv.setOnItemClickListener((parent, view, position, id) -> {
            Log.i("app", String.valueOf(position));
            Gson gson = new Gson();
            XSJJHDataBean xSJJHDataBean = xsjjhDataBeanArrayList.get(position - 1);
            Log.i("app", String.valueOf(xSJJHDataBean.getLRFS()));
            Log.i("app", String.valueOf(xSJJHDataBean.getCBLX()));
            Log.i("app", gson.toJson(xSJJHDataBean));
            ArrayList<XSJJHDataBean> xsjjhDataBeanArrayListTran = new ArrayList<>();

            for (int i = 0; i < xsjjhDataBeanArrayList.size(); i++) {
                XSJJHDataBean xSJJHDataBeanTemp = xsjjhDataBeanArrayList.get(i);
                if (xSJJHDataBeanTemp.getLRFS().equals("1")) {
                    xsjjhDataBeanArrayListTran.add(xSJJHDataBeanTemp);
                } else {
                    if (xSJJHDataBeanTemp.getCBLX().equals("")) {
                        xsjjhDataBeanArrayListTran.add(xSJJHDataBeanTemp);
                    }
                }
            }
            int positionTemp = 0;
            for (int i = 0; i < xsjjhDataBeanArrayListTran.size(); i++) {
                XSJJHDataBean xSJJHDataBeanTemp = xsjjhDataBeanArrayListTran.get(i);
                if (xSJJHDataBean.getScid().equals(xSJJHDataBeanTemp.getScid())) {
                    positionTemp = i;
                }
            }

            Log.i("app", String.valueOf(xsjjhDataBeanArrayListTran.size()));
            if (xSJJHDataBean.getLRFS().equals("1")) {
                Intent intent = new Intent(XjYulActivity.this, SbxjcjsbActivity.class);
                Bundle bundle = new Bundle();
                bundle.putParcelableArrayList("xsjjhDataBeanArrayList", xsjjhDataBeanArrayListTran);
                bundle.putBoolean("edit", isEdit);
                bundle.putString("smfs", smfs);
                bundle.putString("type", type);
                bundle.putInt(Contans.KEY_ITEM, positionTemp);
                bundle.putString("LX", LX);
                bundle.putString("LXResult", LXResult);
                intent.putExtras(bundle);
                startActivityForResult(intent, Req);
            } else {
                if (xSJJHDataBean.getLRFS().equals("0") && xSJJHDataBean.getCBLX().equals("W")) {
//                    Intent intentTemplate = new Intent(XjYulActivity.this, CheckTemperatureActivity.class);
//                    Bundle bundle = new Bundle();
//                    bundle.putParcelable("xSJJHDataBean", xSJJHDataBean);
//                    bundle.putString("checkTip", "日检破碎机，驱动部电机驱动端温度");
//                    bundle.putString("standerTip", "≤40℃");
//                    bundle.putString("checkType", "234233");
//                    bundle.putBoolean("edit", isEdit);
//                    bundle.putString("smfs", smfs);
//                    intentTemplate.putExtras(bundle);
//                    startActivityForResult(intentTemplate, REQUEST_CHECK_TEMPERATURE);
                } else if (xSJJHDataBean.getLRFS().equals("0") && xSJJHDataBean.getCBLX().equals("Z")) {
//                    Intent intentTemplate = new Intent(XjYulActivity.this, CheckVibrationActivity.class);
//                    Bundle bundle = new Bundle();
//                    bundle.putParcelable("xSJJHDataBean", xSJJHDataBean);
//                    bundle.putString("checkTip", "日检破碎机，驱动部电机振动");
//                    bundle.putString("standerTip", "≤11.2mm/s");
//                    bundle.putString("checkType", "234235");
//                    bundle.putBoolean("edit", isEdit);
//                    bundle.putString("smfs", smfs);
//                    intentTemplate.putExtras(bundle);
//                    startActivityForResult(intentTemplate, REQUEST_CHECK_VIBRATION);
                } else {
                    Intent intent = new Intent(XjYulActivity.this, SbxjcjsbActivity.class);
                    Bundle bundle = new Bundle();
                    bundle.putParcelableArrayList("xsjjhDataBeanArrayList", xsjjhDataBeanArrayListTran);
                    bundle.putBoolean("edit", isEdit);
                    bundle.putString("smfs", smfs);
                    bundle.putString("type", type);
                    bundle.putInt(Contans.KEY_ITEM, positionTemp);
                    bundle.putString("LX", LX);
                    bundle.putString("LXResult", LXResult);
                    intent.putExtras(bundle);
                    startActivityForResult(intent, Req);
                }
            }
        });
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != RESULT_OK) return;
        if (data != null) {
            if (Req == requestCode) {
                setxjSbModelArrayList = data.getParcelableArrayListExtra("setSbModelList");
                if (setxjSbModelArrayList == null) {

                } else {
                    for (int i = 0; i < setxjSbModelArrayList.size(); i++) {
                        for (int j = 0; j < infos.size(); j++) {
                            if (infos.get(j).getSbid().equals(setxjSbModelArrayList.get(i).getSbId()))
                                infos.get(j).setCjjg(setxjSbModelArrayList.get(i).getValue());
                        }
                    }
                    adapter.notifyDataSetChanged();
                }
                adapter.notifyDataSetChanged();
            } else {
                String temperatureValue = data.getStringExtra("value");
                if (temperatureValue != null) {
                    //先判断是哪个页面返回过来的
                    switch (requestCode) {
                        case REQUEST_CHECK_TEMPERATURE:
                            //测温
                            //成功了
                            Toast.makeText(XjYulActivity.this, temperatureValue, Toast.LENGTH_SHORT).show();
                            break;
                        case REQUEST_CHECK_VIBRATION:
                            //测振
                            //成功了
                            Toast.makeText(XjYulActivity.this, temperatureValue, Toast.LENGTH_SHORT).show();
                            break;
                    }
                }
            }
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        searchdata();
        adapter.notifyDataSetChanged();
        timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                XjYulActivity.this.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        finish();
                    }
                });
            }
        }, 10 * 1000, 10 * 1000);
    }

    @Override
    protected void onPause() {
        super.onPause();
        timer.cancel();
    }


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

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //unregisterReceiver(myReceiver);
        // 注销广播接收器
        LocalBroadcastManager.getInstance(this).unregisterReceiver(myReceiver);
    }

    private void allCheckNow() {

        ArrayList<XSJJHDataBean> xsjjhDataBeanArrayListTran = new ArrayList<>();
        if (xsjjhDataBeanArrayList.size() > 0) {
            for (int i = 0; i < xsjjhDataBeanArrayList.size(); i++) {
                XSJJHDataBean xSJJHDataBeanTemp = xsjjhDataBeanArrayList.get(i);
                if (xSJJHDataBeanTemp.getLRFS().equals("1")) {
                    xSJJHDataBeanTemp.setChecked(true);
                    xSJJHDataBeanTemp.setCJJG("正常");
                    xsjjhDataBeanArrayListTran.add(xSJJHDataBeanTemp);
                }
            }
        }
        if (infos.size() > 0 && xsjjhDataBeanArrayListTran.size() > 0) {
            for (int i = 0; i < infos.size(); i++) {
                DlbInfo dlbInfo = infos.get(i);
                for (int j = 0; j < xsjjhDataBeanArrayListTran.size(); j++) {
                    XSJJHDataBean xSJJHDataBeanTemp = xsjjhDataBeanArrayListTran.get(j);
                    if (dlbInfo.getScid().equals(xSJJHDataBeanTemp.getScid())) {
                        dlbInfo.setCjjg("正常");
                        dlbInfo.setStatu(true);
                        ContentValues values = new ContentValues();
                        values.put("checked", true);
                        values.put("smfs", smfs);
                        values.put("CJJG", dlbInfo.getCjjg());
                        values.put("DATE", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
                        DataSupport.updateAll(XSJJHDataBean.class, values, "scid = ? and mk = ? and username = ? ", dlbInfo.getScid(), type, username);
                    }
                }
            }
        }
        adapter.notifyDataSetChanged();
    }
}
