package com.sipai.jspatrol.Fault;

import android.app.Dialog;
import android.app.PendingIntent;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.net.Uri;
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.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.os.Parcelable;
import android.provider.MediaStore;
import android.provider.Settings;
import android.util.Log;
import android.view.Display;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.FileProvider;

import com.sipai.jspatrol.Bean.EquList;
import com.sipai.jspatrol.Bean.ProcessSection;
import com.sipai.jspatrol.Bean.User;
import com.sipai.jspatrol.BuildConfig;
import com.sipai.jspatrol.R;
import com.sipai.jspatrol.URL.MethodURL;
import com.sipai.jspatrol.utils.Global.GlobalVal;
import com.sipai.jspatrol.utils.OKHttpUtils;
import com.sipai.jspatrol.utils.RandomStringUtils;
import com.sipai.jspatrol.utils.okHttpCookie.CookiesManager;

import net.bither.util.NativeUtil;

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

import java.io.File;
import java.io.IOException;
import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.pedant.SweetAlert.SweetAlertDialog;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

import static com.sipai.jspatrol.utils.Global.GlobalVal.Type_Equipment;
import static com.sipai.jspatrol.utils.Global.GlobalVal.Type_Facilities;
import static com.sipai.jspatrol.utils.Global.GlobalVal.Type_Run;

public class NewFaultActivity extends AppCompatActivity implements View.OnClickListener {
    private String mServer;
    private String mUsername;
    private String mPwd;
    private String androidId = "";
    private String mUserid;
    private String mCaption;
    private String mBizid, mBizName;
    private NfcAdapter nfcAdapter;
    private PendingIntent pendingIntent;
    private IntentFilter[] mFilters;
    private String[][] mTechLists;
    private boolean isFirst = true;
    private String mark = "";
    private String equid = "";
    // 是否支持NFC功能的标签
    private boolean isNFC_support = false;
    private Boolean isbox = false;
    private final static int SCANNIN_GREQUEST_CODE = 1;
    private final static int FAILESUB = 101;
    private final static int SUCCESSSUB = 102;
    private static final int FAILE_RECEIVERS = 11;
    private static final int SUCCESS_RECEIVERS = 12;
    private static final int SEND_RECEIVERS = 13;
    private static final int SELCONTENT = 14;
    private List<ProcessSection> processSections = new ArrayList<>();
    private static List<Map<String, Object>> mData;
    private TextView tv_equ_name, tv_equ_cardno;
    private TextView tv_factory, tv_sub_man, tv_receiver;
    private EditText edt_fault_description;
    private String alarm_description = "";
    private Button btn_sub;
    private List<User> receivers = new ArrayList<>();
    private List<User> sel_receivers = new ArrayList<>();
    private String st_sel_receiver_id = "";
    private TextView tv_sel_equ;
    private static final int SELEQU = 104;
    private static final int SELPS = 8;//选择工艺段
    private GridView gv_pic;
    // 获取sd卡根目录地址,并创建图片父目录文件对象和文件的对象;
    String file_str = Environment.getExternalStorageDirectory().getPath();
    File mars_file = new File(file_str + "/my_camera");
    File file_go = new File(file_str + "/my_camera/" + System.currentTimeMillis() + ".jpg");
    private List<Map<String, Object>> datas;
    private GridViewAddImgesAdpter gridViewAddImgesAdpter;
    private final int PHOTO_REQUEST_CAREMA = 111;// 拍照
    private final int PHOTO_REQUEST_GALLERY = 222;// 从相册中选择private static final String PHOTO_FILE_NAME = "temp_photo.jpg";
    private final String IMAGE_DIR = Environment.getExternalStorageDirectory() + "/gridview/";
    private static final int UPIMG = 1;
    private String type = "reportEqu";//设备通知单
    private String formId = "";//异常通知单id
    private Dialog ddialog;
    private String planid = "";
    private String pointid = "";
    private String pid = "";
    private TextView tv_fault_description;
    private List<String> contents = new ArrayList<>();
    private String st_fault_content;
    private String token;
    private String id;
    private TextView tv_ps;//工艺段
    private EquList sel_equ;
    private ProcessSection sel_ps;
    private List<EquList> equLists = new ArrayList<>();
    private EditText edt_remark;
    private String remark = "";
    private Spinner sp_type;
    private String sel_type = Type_Run;;
    private ArrayAdapter<String> typeAdapter;
    private List<String> st_type = new ArrayList<>();
    private LinearLayout ll_equ;

    public static void actionStart(Context context, String pointid, String planid, String pointTaskid) {
        Intent intent = new Intent(context, NewFaultActivity.class);
        intent.putExtra("pointid", pointid);
        intent.putExtra("planid", planid);
        intent.putExtra("pointTaskid", pointTaskid);
        context.startActivity(intent);
    }

    public static void alarmStart(Context context, String des) {
        Intent intent = new Intent(context, NewFaultActivity.class);
        intent.putExtra("alarm", des);
        context.startActivity(intent);
    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case UPIMG:
                    photoPath(msg.obj.toString());
                    break;
                case SUCCESSSUB:
                    if (!NewFaultActivity.this.isFinishing()) {
                        new SweetAlertDialog(NewFaultActivity.this, SweetAlertDialog.SUCCESS_TYPE)
                                .setTitleText("上传成功")
                                .setConfirmText("确定")
                                .setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                                    @Override
                                    public void onClick(SweetAlertDialog sweetAlertDialog) {
                                        sweetAlertDialog.dismissWithAnimation();
                                        finish();
                                    }
                                }).show();
                    }
                    break;
                case FAILESUB:
                    if (!NewFaultActivity.this.isFinishing()) {
                        new SweetAlertDialog(NewFaultActivity.this, SweetAlertDialog.ERROR_TYPE)
                                .setTitleText("失败")
                                .setContentText("异常上传失败，请重试！")
                                .setConfirmText("重试")
                                .setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                                    @Override
                                    public void onClick(SweetAlertDialog sweetAlertDialog) {
                                        sweetAlertDialog.dismissWithAnimation();
                                        SubContent();
                                    }
                                }).setCancelText("取消")
                                .setCancelClickListener(new SweetAlertDialog.OnSweetClickListener() {
                                    @Override
                                    public void onClick(SweetAlertDialog sweetAlertDialog) {
                                        sweetAlertDialog.dismissWithAnimation();
                                    }
                                }).show();
                    }
                    break;
                case SUCCESS_RECEIVERS:

                    break;
                case FAILE_RECEIVERS:
                    if (!NewFaultActivity.this.isFinishing()) {
//                        showFailureReceiver();
                    }
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_new_fault);
        init();
        initView();
        initNFC();
        getReceivers();
    }

    /**
     * 获取厂区人员
     */
    private void getReceivers() {
        HashMap<String,String> map = new HashMap<>();
        map.put("unitId",mBizid);
        map.put("search_name","");
        map.put("sort","id");
        map.put("type",sel_type);
        OKHttpUtils.OKCall(map, mServer, MethodURL.GETPartUserList_Method).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                String a = e.toString();
                if (!NewFaultActivity.this.isFinishing()){
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            new SweetAlertDialog(NewFaultActivity.this, SweetAlertDialog.WARNING_TYPE)
                                    .setTitleText("提示")
                                    .setContentText("人员列表获取失败，请重试！")
                                    .setConfirmText("重试")
                                    .setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                                        @Override
                                        public void onClick(SweetAlertDialog sweetAlertDialog) {
                                            sweetAlertDialog.dismissWithAnimation();
                                            getReceivers();
                                        }
                                    }).show();
                        }
                    });
                }
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String res = response.body().string();
                if (res.contains("html")){
                    login("receiver");
                }else {
                    receivers = parseReceiver(res);
                }
            }
        });
    }

    private List<User> parseReceiver(String response) {
        List<User> list = new ArrayList<>();
        try {
            JSONObject jsonObject = new JSONObject(response);
            JSONArray aNews = new JSONArray(jsonObject.getString("rows"));
            for (int i=0;i<aNews.length();i++){
                User item = new User();
                item.setId(aNews.getJSONObject(i).get("id").toString());
                item.setCaption(aNews.getJSONObject(i).get("caption").toString());
                item.setName(aNews.getJSONObject(i).get("name").toString());
                list.add(item);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return list;
    }

    private void login(String mark) {
        CookiesManager.clearCookie(getApplicationContext());
        HashMap<String,String> map = new HashMap<>();
        map.put("j_username",mUsername);
        map.put("j_password",mPwd);
        map.put("androidId",androidId);
        map.put("verCode","64368180");
        OKHttpUtils.OKCall(map,mServer,MethodURL.Login_Method).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                String result = GlobalVal.NET_ERROR;
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String result = response.body().string();
                Log.i("IPatrolService", "onResponse: "+result);
                if (mark.equals("receiver")){
                    getReceivers();
                }
            }
        });
    }

    private void initNFC() {
        //nfc初始化
        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()}};// 允许扫描的标签类型
    }

    private void initView() {
        TextView tv_title = (TextView) findViewById(R.id.moudle_back_title_tv_title);
        tv_title.setText("异常上报");
        ImageView btn_back = (ImageView) findViewById(R.id.moudle_back_title_iv_back);
        btn_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        tv_factory = findViewById(R.id.moudle_new_fault_tv_biz);
        tv_factory.setText(mBizName);
        ll_equ = findViewById(R.id.moudle_new_fault_ll_equ);
        ll_equ.setVisibility(View.GONE);
        sp_type = findViewById(R.id.moudle_new_fault_sp_type);
        typeAdapter = new ArrayAdapter<String>(NewFaultActivity.this,R.layout.item_spin,R.id.tv_sp,st_type);
        sp_type.setAdapter(typeAdapter);
        sp_type.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                if (position==0){
                    sel_type = Type_Run;
                    ll_equ.setVisibility(View.GONE);
                }else if(position==1){
                    sel_type = Type_Equipment;
                    ll_equ.setVisibility(View.VISIBLE);
                }else if(position==2){
                    sel_type = Type_Facilities;
                }
                getReceivers();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
        tv_sub_man = findViewById(R.id.moudle_new_fault_tv_sub_man);
        tv_sub_man.setText(mCaption);
        tv_ps = findViewById(R.id.moudle_new_fault_tv_ps);
        tv_ps.setOnClickListener(this);
        tv_receiver = findViewById(R.id.moudle_new_fault_tv_receiver);
        tv_receiver.setOnClickListener(this);
        edt_fault_description = findViewById(R.id.moudle_new_fault_edt_fault_description);
        if (alarm_description!=null&&alarm_description.length()>0){
            edt_fault_description.setText(alarm_description);
        }
        tv_equ_name = findViewById(R.id.moudle_new_fault_tv_equ_name);
        tv_equ_cardno = findViewById(R.id.moudle_new_fault_tv_equ_cardno);
        btn_sub = findViewById(R.id.moudle_new_fault_btn_sub);
        btn_sub.setOnClickListener(this);
        tv_sel_equ = findViewById(R.id.moudle_new_fault_tv_sel_equ);
        tv_sel_equ.setOnClickListener(this);
        edt_remark = findViewById(R.id.moudle_new_fault_edt_fault_remark);
        gv_pic = findViewById(R.id.moudle_new_fault_gv_pic);
        datas = new ArrayList<>();
        gridViewAddImgesAdpter = new GridViewAddImgesAdpter(datas, this);
        gv_pic.setAdapter(gridViewAddImgesAdpter);
        gv_pic.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
                showdialog();
            }
        });
        tv_fault_description = findViewById(R.id.moudle_new_fault_tv_fault_description);
//        tv_fault_description.setOnClickListener(this);
    }

    private ProgressDialog myProgressDialog = null;//进度条

    //显示进度提示
    public void showProgress(final String title, final String msg) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                try {
                    if (myProgressDialog != null) {
                        myProgressDialog.cancel();
                    }
                    myProgressDialog = ProgressDialog.show(NewFaultActivity.this, title, msg);
                    myProgressDialog.setCancelable(true);
                } catch (Exception e) {
                } finally {
                }
            }
        });
    }

    //取消进度提示
    public void cancelProgress() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                try {
                    if (myProgressDialog != null) {
                        myProgressDialog.dismiss();
                        myProgressDialog.cancel();
                    }
                } catch (Exception e) {
                } finally {
                }
            }
        });
    }

    private void init() {
        st_type = new ArrayList<>();
        st_type.add("运行异常");
        st_type.add("设备异常");
        st_type.add("设施异常");
        sel_type = Type_Run;
        SharedPreferences sharedPre = this.getSharedPreferences("config", 0);
        mServer = sharedPre.getString("server", "");
        mUsername = sharedPre.getString("username", "");
        mPwd=sharedPre.getString("password", "");
        androidId = Settings.System.getString(
                getContentResolver(), Settings.Secure.ANDROID_ID);//10.0以后获取不到UUID，用androidId来代表唯一性
        mUserid = sharedPre.getString("userid", "");
        mCaption = sharedPre.getString("caption", "");
        mBizid = sharedPre.getString("bizid", "");
        mBizName = sharedPre.getString("bizname", "");
        token = sharedPre.getString("token", "");
        id = RandomStringUtils.getStrNumRandom(16);
        if (getIntent().getStringExtra("planid") != null) {
            planid = getIntent().getStringExtra("planid");
        }
        if (getIntent().getStringExtra("pointid") != null) {
            pointid = getIntent().getStringExtra("pointid");
        }
        if (getIntent().getStringExtra("pointTaskid") != null) {
            pid = getIntent().getStringExtra("pointTaskid");
        }
        if (getIntent().getStringExtra("alarm") != null) {
            alarm_description = getIntent().getStringExtra("alarm");
        }
    }

    public void photoPath(String path) {
        Map<String, Object> map = new HashMap<>();
        map.put("path", path);
        datas.add(map);
        gridViewAddImgesAdpter.notifyDataSetChanged();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case SEND_RECEIVERS:
                if (resultCode == RESULT_OK) {
                    sel_receivers = (List<User>) data.getSerializableExtra("sel");
                    String suser = "";
                    st_sel_receiver_id = "";
                    if (sel_receivers.size() > 0) {
                        for (int i = 0; i < sel_receivers.size(); i++) {
                            if (i == 0) {
                                suser = sel_receivers.get(i).getCaption();
                                st_sel_receiver_id = sel_receivers.get(i).getId();
                            } else if (0<i &&i < sel_receivers.size()) {
                                suser = suser + "," + sel_receivers.get(i).getCaption();
                                st_sel_receiver_id = st_sel_receiver_id + "," + sel_receivers.get(i).getId();
                            }
                        }
                    }
                    final String st = suser;
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            if (sel_receivers.size() > 0) {
                                showText(st,tv_receiver);
                            }
                        }
                    });
                }
                break;
            case SELCONTENT:
                if (resultCode == RESULT_OK){
                    String result = data.getStringExtra("sel");
                    st_fault_content = st_fault_content+"  "+result;
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            edt_fault_description.setText(st_fault_content);
                        }
                    });
                }
                break;
            case PHOTO_REQUEST_GALLERY:
                if (resultCode == RESULT_OK) {
                    // 从相册返回的数据
                    if (data != null) {
                        // 得到图片的全路径
                        Uri uri = data.getData();
                        String[] proj = {MediaStore.Images.Media.DATA};
                        //好像是android多媒体数据库的封装接口，具体的看Android文档
                        Cursor cursor = managedQuery(uri, proj, null, null, null);
                        //按我个人理解 这个是获得用户选择的图片的索引值
                        int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                        //将光标移至开头 ，这个很重要，不小心很容易引起越界
                        cursor.moveToFirst();
                        //最后根据索引值获取图片路径
                        String path = cursor.getString(column_index);
                        uploadImage(path);
                    }
                }
                break;
            case PHOTO_REQUEST_CAREMA:
                if (resultCode != RESULT_CANCELED) {
                    // 从相机返回的数据
                    if (hasSdcard()) {
                        if (file_go != null) {
                            uploadImage(file_go.getPath());
                        } else {
                            Toast.makeText(this, "相机异常请稍后再试！", Toast.LENGTH_SHORT).show();
                        }
                    } else {
                        Toast.makeText(this, "未找到存储卡，无法存储照片！", Toast.LENGTH_SHORT).show();
                    }
                }

                break;
            case SELEQU:
                if (resultCode == RESULT_OK) {
                    sel_equ = (EquList) data.getSerializableExtra("equ");
                    updateEquInfo();
                }
                break;
            case SELPS:
                if (resultCode == RESULT_OK) {
                    sel_ps = (ProcessSection) data.getSerializableExtra("ps");
                    updatePsInfo();
                }
                break;
            case SCANNIN_GREQUEST_CODE:
                if (resultCode == RESULT_OK) {
                    Bundle bundle = data.getExtras();
                    String result = bundle.getString("result");
                    if (result != null && !result.isEmpty()) {
                        showinfobyNFC(result);
                    } else {
                        ErrorMessage();
                    }
                }
                break;
        }
    }

    private void updatePsInfo() {
        if (!NewFaultActivity.this.isFinishing()){
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    tv_ps.setText(sel_ps.getName());
                }
            });
        }
    }

    private void updateEquInfo() {
        if (!NewFaultActivity.this.isFinishing()){
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    tv_equ_cardno.setText(sel_equ.getEquipmentcardid());
                    tv_equ_name.setText(sel_equ.getEquipmentname());
                }
            });
        }
    }

    /**
     * 压缩图片
     *
     * @param path
     */
    private void uploadImage(final String path) {
        new Thread() {
            @Override
            public void run() {
                if (new File(path).exists()) {
                    Log.d("images", "源文件存在" + path);
                } else {
                    Log.d("images", "源文件不存在" + path);
                }

                File dir = new File(IMAGE_DIR);
                if (!dir.exists()) {
                    dir.mkdir();
                }
                final File file = new File(dir + "/temp_photo" + System.currentTimeMillis() + ".jpg");
                NativeUtil.compressBitmap(path, file.getAbsolutePath(), 50);
                if (file.exists()) {
                    Log.d("images", "压缩后的文件存在" + file.getAbsolutePath());
                } else {
                    Log.d("images", "压缩后的不存在" + file.getAbsolutePath());
                }
                Message message = new Message();
                message.what = UPIMG;
                message.obj = file.getAbsolutePath();
                handler.sendMessage(message);

            }
        }.start();

    }

    private void showText(final String st, final TextView tv) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                tv.setText(st);
            }
        });
    }

    private void ErrorMessage() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                new SweetAlertDialog(NewFaultActivity.this, SweetAlertDialog.WARNING_TYPE)
                        .setTitleText("二维码信息错误")
                        .setConfirmText("确定")
                        .setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                            @Override
                            public void onClick(SweetAlertDialog sweetAlertDialog) {
                                sweetAlertDialog.dismissWithAnimation();
                            }
                        }).show();
            }
        });
    }

    @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());
                if (result != null && !result.equals("error")) {
                    showinfobyNFC(result);
                }
            }
        }

    }

    private Boolean isLongPressKey = false;

    public boolean onKeyDown(int keyCode, KeyEvent event) {
        switch (keyCode) {
            case KeyEvent.KEYCODE_VOLUME_UP:
                if (event.getRepeatCount() == 0) {
                    event.startTracking();
                    isLongPressKey = false;
                } else {
                    isLongPressKey = true;
                }
                return true;
            case KeyEvent.KEYCODE_VOLUME_DOWN:
                Toast.makeText(this, "减小音量", Toast.LENGTH_SHORT).show();
                return false;
        }
        return super.onKeyDown(keyCode, event);
    }

    @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) {
        // 当前app正在前端界面运行，这个时候有intent发送过来，那么系统就会调用onNewIntent回调方法，将intent传送过来
        // 我们只需要在这里检验这个intent是否是NFC相关的intent，如果是，就调用处理方法
        super.onNewIntent(intent);
        if (NfcAdapter.ACTION_TECH_DISCOVERED.equals(intent.getAction())) {
            String result = processIntent(intent);
            if (result != null && !result.equals("error")) {
                showinfobyNFC(result);
            }
        }
    }

    private void showinfobyNFC(String id) {
        searchEqu(id);
    }

    /**
     * 搜索设备
     * @param name
     */
    private void searchEqu(String name) {
        if (!NewFaultActivity.this.isFinishing()){
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(NewFaultActivity.this, "设备查询中...", Toast.LENGTH_LONG).show();
                }
            });
        }
        HashMap<String,String> map = new HashMap<>();
        map.put("unitId",mBizid);
        map.put("equipmentId",name);
        map.put("search_name","");
        map.put("processSectionId","");
        map.put("rows","30");
        map.put("page","1");
        map.put("sort","id");
        map.put("order","desc");
        OKHttpUtils.getClient().newCall(OKHttpUtils.OKHttpRequest(map, mServer, MethodURL.GETEQULISt_Method)).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                if (!NewFaultActivity.this.isFinishing()){
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(NewFaultActivity.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){
                    sel_equ = equLists.get(0);
                    updateEquInfo();
                }else {
                    if (!NewFaultActivity.this.isFinishing()){
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(NewFaultActivity.this, "失败：系统中暂未找到该设备！", Toast.LENGTH_LONG).show();
                            }
                        });
                    }
                }
            }
        });
    }


    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"));
                list.add(item);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return list;
    }



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


    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            //切换用户
            case android.R.id.home:
                finish();
                return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.moudle_new_fault_tv_ps:
                Intent intent_sel_ps = new Intent(NewFaultActivity.this, SingleChoiceActivity.class);
                intent_sel_ps.putExtra("mark","ps");
                startActivityForResult(intent_sel_ps,SELPS);
                break;
            case R.id.moudle_new_fault_btn_sub:
                if (edt_fault_description.getText() != null && !edt_fault_description.getText().toString().isEmpty()) {
                    if(sel_receivers.size()>0) {
                        if (sel_type==Type_Equipment){
                            if (sel_equ!=null&&!sel_equ.getId().isEmpty()){
                                SubContent();
                            }else {
                                showToast("设备不能为空");
                            }
                        }else {
                            SubContent();
                        }

                    }else {
                        showToast("接收人不能为空");
                    }
                } else {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            edt_fault_description.setError("不可为空");
                        }
                    });
                }
                break;
            case R.id.moudle_new_fault_tv_receiver:
                if (receivers.size() > 0) {
                    Intent intent_man = new Intent(NewFaultActivity.this, PersonSelectorActivity.class);
                    intent_man.putExtra("users", (Serializable) receivers);
                    startActivityForResult(intent_man, SEND_RECEIVERS);
                } else {
                    if (!NewFaultActivity.this.isFinishing()) {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                new SweetAlertDialog(NewFaultActivity.this, SweetAlertDialog.WARNING_TYPE)
                                        .setTitleText("提示")
                                        .setContentText("暂未配置接收人")
                                        .show();
                            }
                        });
                    }
                }
                break;
            case R.id.moudle_new_fault_tv_sel_equ:
                Intent intent_sel_equ = new Intent(NewFaultActivity.this, SingleChoiceActivity.class);
                intent_sel_equ.putExtra("mark","equ");
                if (sel_ps!=null) {
                    intent_sel_equ.putExtra("psId", sel_ps.getSid());
                }
                startActivityForResult(intent_sel_equ, SELEQU);
                break;
        }
    }

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

    private void noSetContent() {
        if (!NewFaultActivity.this.isFinishing()){
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    new SweetAlertDialog(NewFaultActivity.this, SweetAlertDialog.WARNING_TYPE)
                            .setTitleText("提示")
                            .setContentText("暂未配置异常内容列表，请配置后再选择！")
                            .setConfirmText("确定")
                            .setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                                @Override
                                public void onClick(SweetAlertDialog sweetAlertDialog) {
                                    sweetAlertDialog.dismissWithAnimation();
                                }
                            }).show();
                }
            });
        }
    }


    private void SubContent() {
        showProgress("", "数据上传中...");
        if (edt_remark.getText()!=null&&!edt_remark.getText().toString().isEmpty()){
            remark = edt_remark.getText().toString();
        }
        HashMap<String,String> map = new HashMap<>();
        map.put("id",id);
        map.put("status", "");
        map.put("bizId",mBizid);
        if (sel_ps!=null&&sel_ps.getSid()!=null) {
            map.put("processSectionId", sel_ps.getSid());
        }
        map.put("type", sel_type);
        if (sel_equ!=null&&sel_equ.getId()!=null){
            map.put("equipmentIds", sel_equ.getId());
            map.put("equipname", sel_equ.getEquipmentname());
        }
        map.put("libraryId", "");
        map.put("abnormityDescription", edt_fault_description.getText().toString());
        map.put("remark", remark);
        map.put("solvername", sel_receivers.get(0).getCaption());
        map.put("receiveUserId", sel_receivers.get(0).getId());
        OKHttpUtils.getClient().newCall(OKHttpUtils.OKHttpRequest(map, mServer, MethodURL.SubFault_Method)).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                cancelProgress();
                Message message = new Message();
                message.what = FAILESUB;
                handler.sendMessage(message);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String res = response.body().string();
                try {
                    JSONObject jsonObject = new JSONObject(res);
                    if (jsonObject.optString("res").toString().equals("1")){
                        if (datas.size()>0) {
                            SubPic();
                        }else {
                            cancelProgress();
                            successSub();
                        }
                    }else {
                        cancelProgress();
                        Message message = new Message();
                        message.what = FAILESUB;
                        handler.sendMessage(message);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                    Message message = new Message();
                    message.what = FAILESUB;
                    handler.sendMessage(message);
                }
            }
        });
    }

    private void SubPic() {
        HashMap<String,String> map = new HashMap<>();
//        map.put("file_id",String.valueOf(datas.size()));
        map.put("masterId",id);
        map.put("tbName","tb_maintenance_problem_fille");
        map.put("nameSpace","maintenance");
        String picMark = "filelist";
        OKHttpUtils.getClient().newCall(OKHttpUtils.OKHttpSubPics(map,mServer, MethodURL.SubPic_Method,picMark,datas)).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                cancelProgress();
                picSubFail();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String res = response.body().string();
                cancelProgress();
                if (res.contains("suc")){
                    successSub();
                }else {
                    picSubFail();
                }
            }
        });
    }

    private void picSubFail() {
        if (!NewFaultActivity.this.isFinishing()){
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    new SweetAlertDialog(NewFaultActivity.this, SweetAlertDialog.ERROR_TYPE)
                            .setTitleText("失败")
                            .setContentText("图片上传失败")
                            .setConfirmText("重新上传")
                            .setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                                @Override
                                public void onClick(SweetAlertDialog sweetAlertDialog) {
                                    sweetAlertDialog.dismissWithAnimation();
                                    SubPic();
                                }
                            }).setCancelText("取消")
                            .setCancelClickListener(new SweetAlertDialog.OnSweetClickListener() {
                                @Override
                                public void onClick(SweetAlertDialog sweetAlertDialog) {
                                    sweetAlertDialog.dismissWithAnimation();
                                    finish();
                                }
                            }).show();
                }
            });
        }
    }

    private void successSub() {
        if (!NewFaultActivity.this.isFinishing()) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    new SweetAlertDialog(NewFaultActivity.this, SweetAlertDialog.SUCCESS_TYPE)
                            .setTitleText("上传成功")
                            .setConfirmText("确认")
                            .setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                                @Override
                                public void onClick(SweetAlertDialog sweetAlertDialog) {
                                    sweetAlertDialog.dismissWithAnimation();
                                    finish();
                                }
                            }).show();
                }
            });
        }
    }

    /**
     * 选择图片对话框
     */
    public void showdialog() {
        View localView = LayoutInflater.from(this).inflate(
                R.layout.dialog_add_picture, null);
        TextView tv_camera = (TextView) localView.findViewById(R.id.tv_camera);
        TextView tv_gallery = (TextView) localView.findViewById(R.id.tv_gallery);
        TextView tv_cancel = (TextView) localView.findViewById(R.id.tv_cancel);
        ddialog = new Dialog(this, R.style.custom_dialog);
        ddialog.setContentView(localView);
        ddialog.getWindow().setGravity(Gravity.BOTTOM);
        // 设置全屏
        WindowManager windowManager = getWindowManager();
        Display display = windowManager.getDefaultDisplay();
        WindowManager.LayoutParams lp = ddialog.getWindow().getAttributes();
        lp.width = display.getWidth(); // 设置宽度
        ddialog.getWindow().setAttributes(lp);
        ddialog.show();
        tv_cancel.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {
                ddialog.dismiss();
            }
        });

        tv_camera.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                ddialog.dismiss();
                // 拍照
                camera();
            }
        });

        tv_gallery.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                ddialog.dismiss();
                // 从系统相册选取照片
                gallery();
            }
        });
    }


    /**
     * 拍照
     */
    public void camera() {
        Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            try {
                File file = createOriImageFile();
                file_go = file;
                if (file != null) {
                    Uri imgUriOri = FileProvider.getUriForFile(getApplicationContext(), BuildConfig.APPLICATION_ID + ".fileProvider", file);
                    cameraIntent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);//设置Action为拍照
                    cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, imgUriOri);
                    startActivityForResult(cameraIntent, PHOTO_REQUEST_CAREMA);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else {
            if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
                if (!mars_file.exists()) {
                    mars_file.mkdirs();
                }
                // 并设置拍照的存在方式为外部存储和存储的路径；
                cameraIntent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);//设置Action为拍照
                cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file_go));
                //跳转到拍照界面;
                startActivityForResult(cameraIntent, PHOTO_REQUEST_CAREMA);
            } else {
                Toast.makeText(NewFaultActivity.this, "请先安装好sd卡", Toast.LENGTH_LONG).show();
            }
        }
    }

    /**
     * 创建原图像保存的文件
     *
     * @return
     * @throws IOException
     */
    private File createOriImageFile() throws IOException {
        String imgNameOri = "bk_" + new SimpleDateFormat(
                "yyyyMMdd_HHmmss").format(new Date());
        File pictureDirOri = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).getAbsolutePath() + "/my_camera");
        if (!pictureDirOri.exists()) {
            pictureDirOri.mkdirs();
        }
        File image = File.createTempFile(
                imgNameOri,         /* prefix */
                ".jpg",             /* suffix */
                pictureDirOri       /* directory */
        );
        String imgPathOri = image.getAbsolutePath();
        return image;
    }

    /**
     * 判断sdcard是否被挂载
     */
    public boolean hasSdcard() {
        return Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED);
    }


    /**
     * 从相册获取2
     */
    public void gallery() {
        Intent intent = new Intent(
                Intent.ACTION_PICK,
                MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        startActivityForResult(intent, PHOTO_REQUEST_GALLERY);
    }
}
