package com.ai.ced.bluetooth;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Handler;
import android.util.Log;



import org.apache.cordova.CallbackContext;
import org.apache.cordova.PluginResult;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.ref.SoftReference;
import java.text.SimpleDateFormat;
import java.util.Date;


public class ReadCardMessage {

  private CallbackContext readcardCallbackContext;

  public ReadCardMessage(CallbackContext readcardCallbackContext)
  {
    this.readcardCallbackContext = readcardCallbackContext;
  }

  public void readCardFailed(String strcardinfo) {
    int bret = Integer.parseInt(strcardinfo);
    String str = "";
    switch (bret) {
      case -1:
        Log.i("", "服务器连接失败!");
        str = "服务器连接失败!";
        if (readcardCallbackContext != null)
          sendRespmsg("6003", str, readcardCallbackContext);
        break;
      case -2:
        Log.i("", "无返回结果!");
        str = "无返回结果!";
        if (readcardCallbackContext != null)
          sendRespmsg("6003", str, readcardCallbackContext);
        break;
      case 1:
        Log.i("", "请放置身份证!");
        str = "请放置身份证!";
        if (readcardCallbackContext != null)
          sendRespmsg("6003", str, readcardCallbackContext);
        break;
      case 2:
        Log.i("", "读卡失败!");
        str = "读卡失败!";
        if (readcardCallbackContext != null)
          sendRespmsg("6003", str, readcardCallbackContext);
        break;
      case 3:
        Log.i("", "网络超时!");
        str = "网络超时!";
        if (readcardCallbackContext != null)
          sendRespmsg("6003", str, readcardCallbackContext);
        break;
      case 4:
        Log.i("", "读卡失败!");
        str = "读卡失败!";
        if (readcardCallbackContext != null)
          sendRespmsg("6003", str, readcardCallbackContext);
        break;
      case 5:
        Log.i("", "照片解码失败!");
        str = "照片解码失败!";
        if (readcardCallbackContext != null)
          sendRespmsg("6003", str, readcardCallbackContext);
        break;
    }
  }


  /**
   * 读取成功
   *
   * @param strCardInfo
   */
  public void readCardSuccess(String strCardInfo) {

    try {
      JSONObject JsonObj;
      InputStream input = null;
      byte[] avatar = new byte[20 * 1024];
      XtParm parm = new XtParm();
      try {
        JsonObj = new JSONObject(strCardInfo);
        String type = JsonObj.getString("type");
        if (type.equals("I")) {
          parm.setName(JsonObj.getString("name"));
          parm.setEnname(JsonObj.getString("enname"));
          parm.setLabelehtnic("");
          parm.setLableaddress("国籍");
          parm.setFolkText("");
          parm.setAddr(JsonObj.getString("ethnicity"));
          parm.setNumberofissue("");
          parm.setPassnumber("");
          parm.setCardType("");
        } else if (type.equals("")) {
          parm.setLabelehtnic("民族");
          parm.setLableaddress("住址");
          parm.setName(JsonObj.getString("name"));
          parm.setAddr(JsonObj.getString("address"));
          parm.setFolkText(JsonObj.getString("ethnicity"));
          parm.setNumberofissue("");
          parm.setPassnumber("");
          parm.setCardType("0");
        } else if (type.equals("J")) {
          parm.setLabelehtnic("民族");
          parm.setLableaddress("住址");
          parm.setName(JsonObj.getString("name"));
          parm.setAddr(JsonObj.getString("address"));
          parm.setFolkText(JsonObj.getString("ethnicity"));
          parm.setNumberofissue(JsonObj.getString("numberofissue"));
          parm.setPassnumber(JsonObj.getString("passnumber"));
          parm.setCardType("5");
        }
        parm.setSex(JsonObj.getString("gender"));
        parm.setBirth(JsonObj.getString("birth"));
        parm.setCode(JsonObj.getString("cardNo"));
        parm.setPolicy(JsonObj.getString("authority"));
        parm.setValidDate(JsonObj.getString("period"));
        JSONArray javatar = JsonObj.getJSONArray("avatar");

//        Log.d("ReadCardMessage","readCardSuccess...base64" + JsonObj.getString("pictureBase64"));

        int len = javatar.length();

        for (int j = 0; j < len; j++) {
          avatar[j] = (byte) javatar.getInt(j);
        }

      } catch (JSONException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
      }

      try {
        Log.e("", "图片成功");
        Bitmap photobm = null;
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inSampleSize = 1;
        input = new ByteArrayInputStream(avatar);
        ;
        SoftReference softRef = new SoftReference(BitmapFactory.decodeStream(input, null, options));
        photobm = (Bitmap) softRef.get();
        parm.setPic( Util.bitmapToBase64(photobm));
        //photoView.setImageBitmap(photobm);
        try {
          setIdResult(parm);
        } catch (JSONException e) {
          e.printStackTrace();
        }
        Log.e("", "图片成功");
      } finally {
        if (avatar != null) {
          avatar = null;
        }

        if (input != null) {
          try {
            input.close();
          } catch (IOException e) {
            e.printStackTrace();
          }
        }
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
  }



  /**
   * 身份证信息显示
   *
   * @param xtParm
   * @throws JSONException
   */
  public void setIdResult(XtParm xtParm) throws JSONException {//返回结果
    try {
      if(!xtParm.getCardType().equals("")) {
        JSONObject resp = new JSONObject();
        JSONObject data = new JSONObject();
        resp.put("respCode", "0000");
        resp.put("respDesc", "信通读取身份证成功");
        data.put("name", xtParm.getName()); //姓名
        data.put("sexCode", xtParm.getSex().equals("男") ? "1" : "0");// 性别
        data.put("sexName", xtParm.getSex());//性别
        String birth = xtParm.getBirth().replace("年", "").replace("月", "").replace("日", "").replace(" ", "");
        SimpleDateFormat sdf=new SimpleDateFormat("yyyyMMdd");
        data.put("birth", birth);//生日yyyymmdd
        String nowtime=sdf.format(new Date());
        boolean resultb= Util.CompareTime(birth,nowtime);
        data.put("nationCode", xtParm.getCode());//民族编码, 神思没有
        data.put("nationName", xtParm.getFolkText());//民族汉字
        data.put("address", xtParm.getAddr());//住址
        data.put("idNum", xtParm.getCode());//身份证号
        data.put("signOffice", xtParm.getPolicy());//发证机关
        String date = xtParm.getValidDate();
        String result[] = date.split("-");
        data.put("usefulStartDate", result[0].replace(".", ""));//有效期开始yyyymmdd
        data.put("usefulEndDate", result[1].replace(".", ""));//有效期结束yyyymmdd
        data.put("cardType", xtParm.getCardType());
        data.put("passNo", xtParm.getPassnumber());
        data.put("issueNo", xtParm.getNumberofissue());
        //String picStr = bitmapToBase64(""); //照片base64字符串
        data.put("pic", xtParm.getPic());

        if(resultb == false){
          resp = new JSONObject();
          resp.put("respCode", "0100");
          resp.put("respDesc", "身份证已过期，不允许办理此业务!");
        }else {
          resp.put("data", data);
        }
        //返回结果
        sendRespInfo(resp, this.readcardCallbackContext);
      }else {
        JSONObject resp = new JSONObject();
        resp.put("respCode", "9999");
        resp.put("respDesc", "读取身份证失败外国人身份证不支持");
        sendRespInfo(resp, this.readcardCallbackContext);
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
  }

  /**
   * JSOM字段赋值
   */
  public void sendRespmsg(String respCode, String respDesc, CallbackContext normalCallbackContext) {
    try {
      Log.d("BluetoothDevicePlugin", "sendRespInfo......" + respDesc+"-"+respCode);
      System.out.println("callbackContext......" + respDesc+"-"+respCode);
      JSONObject resp = new JSONObject();
      resp.put("respCode", respCode);
      resp.put("respDesc", respDesc);
      sendRespInfo(resp, normalCallbackContext);
    } catch (JSONException e) {
      e.printStackTrace();
    }
  }

  /**
   * 返回消息给前端，这边全都算做success，只是通过respCode来区分是否成功
   * 返回的是json字符串，跟ios统一
   *
   * @param resp
   * @param callbackContext
   */
  private void sendRespInfo(JSONObject resp, CallbackContext callbackContext) {
    String message = resp.toString(); //json转换成字符串
    Log.d("BluetoothDevicePlugin", "sendRespInfo......" + message);
    System.out.println("callbackContext......" + callbackContext);
    System.out.println("sendRespInfo......" + message);
    //成功回调
    //callbackContext.success(message);

    //为了一次调用能多次返回结果给前端，得用下面的方式返回结果,
    //PluginResult plugin = new PluginResult(PluginResult.Status.OK, message);
    PluginResult plugin = new PluginResult(PluginResult.Status.OK, resp);
    plugin.setKeepCallback(true);
    callbackContext.sendPluginResult(plugin);
  }
}
