package com.sipai.jspatrol.Equ;

import android.annotation.SuppressLint;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.nfc.NdefMessage;
import android.nfc.NdefRecord;
import android.nfc.NfcAdapter;
import android.nfc.tech.MifareClassic;
import android.nfc.tech.NfcA;
import android.os.Bundle;
import android.os.Parcelable;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.sipai.jspatrol.Bean.EquList;
import com.sipai.jspatrol.Bean.Measuringpoint;
import com.sipai.jspatrol.Fault.EquSingleChoiceAdapter;
import com.sipai.jspatrol.R;
import com.sipai.jspatrol.URL.MethodURL;
import com.sipai.jspatrol.utils.OKHttpUtils;
import com.yzq.zxinglibrary.android.CaptureActivity;
import com.yzq.zxinglibrary.bean.ZxingConfig;
import com.yzq.zxinglibrary.common.Constant;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class EquSearchActivity extends AppCompatActivity implements View.OnClickListener {
    private ImageView iv_back;
    private EditText edt_name;
    private TextView tv_search;
    private String mServer;
    private String mUsername;
    private String mPassword;
    private String mUserid;
    private String mCaption;
    private String mBizid, mBizName;
    private String name = "";
    private String sel_ps_id = "";
    private RecyclerView rc_list;
    private SwipeRefreshLayout refreshLayout;
    private List<EquList> equLists = new ArrayList<>();
    private EquSingleChoiceAdapter equAdapter;
    private LinearLayoutManager manager;
    private ImageView civ;
    private ImageView iv_add;
    private NfcAdapter nfcAdapter;
    // 是否支持NFC功能的标签
    private boolean isNFC_support = false;
    private PendingIntent pendingIntent;
    private IntentFilter[] mFilters;
    private String[][] mTechLists;
    private static final int REQUEST_CODE_SCAN = 23;

    public static void actionStart(Context context){
        Intent intent = new Intent(context, EquSearchActivity.class);
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_equ_search);
        init();
        initView();
        checkNFC();
        startSearch();
    }

    private void checkNFC() {
        // 获取nfc适配器，判断设备是否支持NFC功能
        nfcAdapter = NfcAdapter.getDefaultAdapter(this);
        if (nfcAdapter == null) {
            Toast.makeText(this, getResources().getString(R.string.no_nfc),
                    Toast.LENGTH_SHORT).show();
        } else if (!nfcAdapter.isEnabled()) {
            Toast.makeText(this, getResources().getString(R.string.open_nfc),
                    Toast.LENGTH_SHORT).show();
        }
        pendingIntent = PendingIntent.getActivity(this, 0, new Intent(this,
                getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
        IntentFilter ndef = new IntentFilter(NfcAdapter.ACTION_TECH_DISCOVERED);
        ndef.addCategory("*/*");
        mFilters = new IntentFilter[]{ndef};// 过滤器
        mTechLists = new String[][]{
                new String[]{MifareClassic.class.getName()},
                new String[]{NfcA.class.getName()}};// 允许扫描的标签类型
    }

    @Override
    protected void onResume() {
        super.onResume();
        nfcAdapter = NfcAdapter.getDefaultAdapter(this);
        isNFC_support = !(nfcAdapter == null || !nfcAdapter.isEnabled());
        if (isNFC_support) {
            nfcAdapter.enableForegroundDispatch(this, pendingIntent, mFilters,
                    mTechLists);
            if (NfcAdapter.ACTION_TECH_DISCOVERED.equals(getIntent().getAction())) {
                // 注意这个if中的代码几乎不会进来，因为刚刚在上一行代码开启了监听NFC连接，下一行代码马上就收到了NFC连接的intent，这种几率很小
                // 处理该intent
                String result = processIntent(getIntent());
                searchSingleEqu(result);
            }
        }
    }

    private void initView() {
        civ = findViewById(R.id.moudle_equ_search_civ);
        civ.setOnClickListener(this);
        iv_back = findViewById(R.id.moudle_equ_search_iv_back);
        iv_back.setOnClickListener(this);
        edt_name = findViewById(R.id.moudle_equ_search_edt_equname);
        tv_search = findViewById(R.id.moudle_equ_search_tv_search);
        tv_search.setOnClickListener(this);
        rc_list = findViewById(R.id.moudle_equ_search_rc);
        refreshLayout = findViewById(R.id.moudle_equ_search_refresh);
        refreshLayout.setColorSchemeResources(R.color.blue);
        refreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                startSearch();
            }
        });
    }

    private void init() {
        SharedPreferences sharedPre = this.getSharedPreferences("config", 0);
        mServer = sharedPre.getString("server", "");
        mUsername = sharedPre.getString("username", "");
        mPassword = sharedPre.getString("password", "");
        mUserid = sharedPre.getString("userid", "");
        mCaption = sharedPre.getString("caption", "");
        mBizid = sharedPre.getString("bizid", "");
        mBizName = sharedPre.getString("bizname", "");
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.moudle_equ_search_iv_back:
                finish();
                break;
            case R.id.moudle_equ_search_tv_search:
                startSearch();
                break;
            case R.id.moudle_equ_search_civ:
                Intent intent = new Intent(EquSearchActivity.this, CaptureActivity.class);
                /*ZxingConfig是配置类
                 *可以设置是否显示底部布局，闪光灯，相册，
                 * 是否播放提示音  震动
                 * 设置扫描框颜色等
                 * 也可以不传这个参数
                 * */
                ZxingConfig config = new ZxingConfig();
                config.setPlayBeep(true);//是否播放扫描声音 默认为true
                config.setShake(true);//是否震动  默认为true
                config.setDecodeBarCode(true);//是否扫描条形码 默认为true
                config.setFullScreenScan(false);//是否全屏扫描  默认为true  设为false则只会在扫描框中扫描
                intent.putExtra(Constant.INTENT_ZXING_CONFIG, config);
                startActivityForResult(intent, REQUEST_CODE_SCAN);
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        // 扫描二维码/条码回传
        if (requestCode == REQUEST_CODE_SCAN && resultCode == RESULT_OK) {
            if (data != null) {
                String content = data.getStringExtra(Constant.CODED_CONTENT);
                searchSingleEqu(content);
            }
        }
    }

    /**
     * 获取tab标签中的内容
     *
     * @param intent
     * @return
     */
    @SuppressLint("NewApi")
    private String processIntent(Intent intent) {
        Parcelable[] rawmsgs = intent
                .getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
        if (rawmsgs != null) {
            NdefMessage msg = (NdefMessage) rawmsgs[0];
            NdefRecord[] records = msg.getRecords();
            String resultStr = new String(records[0].getPayload());
            return resultStr;
        } else {
            return "error";
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (nfcAdapter != null && nfcAdapter.isEnabled()) {
            // 当前Activity如果不在手机的最前端，就停止NFC设备连接的监听
            stopNFC_Listener();
        }
    }

    private void stopNFC_Listener() {
        // 停止监听NFC设备是否连接
        nfcAdapter.disableForegroundDispatch(this);
    }

    @Override
    protected void onNewIntent(Intent intent) {
        // TODO Auto-generated method stub
        // 当前app正在前端界面运行，这个时候有intent发送过来，那么系统就会调用onNewIntent回调方法，将intent传送过来
        // 我们只需要在这里检验这个intent是否是NFC相关的intent，如果是，就调用处理方法
        super.onNewIntent(intent);
        if (NfcAdapter.ACTION_TECH_DISCOVERED.equals(intent.getAction())) {
            String result = processIntent(intent);
            searchSingleEqu(result);
        }
    }

    private void startSearch() {
        if (edt_name.getText()!=null&&!edt_name.getText().toString().isEmpty()){
            name = edt_name.getText().toString();
        }
        judgeRefresh();
        searchEqu(name);
    }

    private void judgeRefresh() {
        if (!EquSearchActivity.this.isFinishing()){
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    if (!refreshLayout.isRefreshing()){
                        refreshLayout.setRefreshing(true);
                    }
                }
            });
        }
    }

    /**
     * 搜索设备
     * @param name
     */
    private void searchEqu(String name) {
        HashMap<String,String> map = new HashMap<>();
        map.put("companyId",mBizid);
        map.put("search_name",name);
        map.put("processSectionId",sel_ps_id);
        map.put("rows","50");
        map.put("page","1");
        OKHttpUtils.getClient().newCall(OKHttpUtils.OKHttpRequest(map, mServer, MethodURL.GETEQULISt_Method)).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                if (!EquSearchActivity.this.isFinishing()){
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            refreshLayout.setRefreshing(false);
                            Toast.makeText(EquSearchActivity.this, "失败：" + e.toString(), Toast.LENGTH_SHORT).show();
                        }
                    });
                }
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String res = response.body().string();
                if (res.contains("total")&&res.contains("rows")) {
                    equLists = parseEqu(res);
                }
                updateEquList();
            }
        });
    }


    /**
     * 搜索单个设备
     * @param id
     */
    private void searchSingleEqu(String id) {
        HashMap<String,String> map = new HashMap<>();
        map.put("id",id);
        OKHttpUtils.getClient().newCall(OKHttpUtils.OKHttpRequest(map, mServer, MethodURL.GETSINGLEEQU_Method)).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                if (!EquSearchActivity.this.isFinishing()){
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            refreshLayout.setRefreshing(false);
                            Toast.makeText(EquSearchActivity.this, "失败：" + e.toString(), Toast.LENGTH_SHORT).show();
                        }
                    });
                }
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String res = response.body().string();
                if (res.contains("total")&&res.contains("rows")) {
                    equLists = parseEqu(res);
                    if (equLists.size()>0){
                        EquCardActivity.actionStart(EquSearchActivity.this,equLists.get(0));
//                        EquDetailActivity.actionStart(EquSearchActivity.this,equLists.get(0));
                    }else {
                        showToast("未搜到该设备！");
                    }
                }
            }
        });
    }

    private void showToast(String s) {
        if (!EquSearchActivity.this.isFinishing()){
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(EquSearchActivity.this, s, Toast.LENGTH_SHORT).show();
                }
            });
        }
    }

    private void updateEquList() {
        if (!EquSearchActivity.this.isFinishing()){
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    refreshLayout.setRefreshing(false);
                    equAdapter = new EquSingleChoiceAdapter(EquSearchActivity.this, equLists, new EquSingleChoiceAdapter.onRecyclerViewItemClick() {
                        @Override
                        public void onItemClick(View v, int position) {
                            EquCardActivity.actionStart(EquSearchActivity.this,equLists.get(position));
//                            EquDetailActivity.actionStart(EquSearchActivity.this,equLists.get(position));
                        }
                    });
                    rc_list.setAdapter(equAdapter);
                    manager = new LinearLayoutManager(EquSearchActivity.this);
                    rc_list.setLayoutManager(manager);
                }
            });
        }
    }

    private List<EquList> parseEqu(String res) {
        List<EquList> list = new ArrayList<>();
        try {
            JSONObject jsonObject = new JSONObject(res);
            JSONArray array = jsonObject.getJSONArray("rows");
            for (int i=0;i<array.length();i++){
                EquList item = new EquList();
                item.setId(array.getJSONObject(i).optString("id"));
                item.setEquipmentmanufacturer(array.getJSONObject(i).optString("equipmentmanufacturer"));
                item.setEquipmentname(array.getJSONObject(i).optString("equipmentname"));
                item.setEquipmentcardid(array.getJSONObject(i).optString("equipmentcardid"));
                item.setEquipmentmodel(array.getJSONObject(i).optString("equipmentmodelname"));
                item.setAssetnumber(array.getJSONObject(i).optString("assetnumber"));
                if (!array.getJSONObject(i).optString("processSection").equals("null")&&!array.getJSONObject(i).optString("processSection").isEmpty()){
                    JSONObject js = new JSONObject(array.getJSONObject(i).optString("processSection"));
                    item.setProcessSection(js.optString("name"));
                    item.setProcesssectionid(js.optString("id"));
                }else {
                    item.setProcessSection("暂未配置");
                }
                if (!array.getJSONObject(i).optString("equipmentStatusManagement").equals("null")&&!array.getJSONObject(i).optString("equipmentStatusManagement").isEmpty()){
                    JSONObject js = new JSONObject(array.getJSONObject(i).optString("equipmentStatusManagement"));
                    item.setEquipmentStatusManagement(js.optString("name"));
                }else {
                    item.setEquipmentStatusManagement("未知");
                }
                if (!array.getJSONObject(i).optString("equipmentLevel").equals("null")&&!array.getJSONObject(i).optString("equipmentLevel").isEmpty()){
                    JSONObject js = new JSONObject(array.getJSONObject(i).optString("equipmentLevel"));
                    item.setEquipmentLevel(js.optString("levelname")+"类");
                }else {
                    item.setEquipmentLevel("未知");
                }
                item.setAreaid(array.getJSONObject(i).optString("areaid"));
                if (!array.getJSONObject(i).optString("company").equals("null")&&!array.getJSONObject(i).optString("company").isEmpty()){
                    JSONObject js = new JSONObject(array.getJSONObject(i).optString("company"));
                    item.setCompany(js.optString("name"));
                }else {
                    item.setCompany("暂未配置");
                }
                if (!array.getJSONObject(i).optString("equipmentTypeNumber").equals("null")&&!array.getJSONObject(i).optString("equipmentTypeNumber").isEmpty()){
                    JSONObject js = new JSONObject(array.getJSONObject(i).optString("equipmentTypeNumber"));
                    item.setEquipmentTypeNumber(js.optString("name"));
                }else {
                    item.setEquipmentTypeNumber("暂未配置");
                }
                if (!array.getJSONObject(i).optString("equipmentClass").equals("null")&&!array.getJSONObject(i).optString("equipmentClass").isEmpty()){
                    JSONObject js = new JSONObject(array.getJSONObject(i).optString("equipmentClass"));
                    item.setEquipmentClass(js.optString("name"));
                }else {
                    item.setEquipmentClass("暂未配置");
                }
                if (!array.getJSONObject(i).optString("mPoint4APP").equals("null")&&!array.getJSONObject(i).optString("mPoint4APP").isEmpty()){
                    JSONArray arrayPoint = array.getJSONObject(i).getJSONArray("mPoint4APP");
                    List<Measuringpoint> points = new ArrayList<>();
                    for (int a=0;a<arrayPoint.length();a++){
                        Measuringpoint point = new Measuringpoint();
                        point.setSid(arrayPoint.getJSONObject(a).opt("id").toString());
                        point.setName(arrayPoint.getJSONObject(a).opt("parmname").toString());
                        point.setUnit(arrayPoint.getJSONObject(a).opt("unit").toString());
                        point.setCvalue(arrayPoint.getJSONObject(a).opt("parmvalue").toString());
                        point.setType(arrayPoint.getJSONObject(a).opt("signalType").toString());
                        point.setScadacode(arrayPoint.getJSONObject(a).opt("id").toString());
                        point.setAlarmmax(arrayPoint.getJSONObject(a).opt("alarmmax").toString());
                        point.setAlarmmin(arrayPoint.getJSONObject(a).opt("alarmmin").toString());
                        points.add(point);
                    }
                    item.setMeasuringpoints(points);
                }
                list.add(item);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return list;
    }
}
