package com.smartdot.cgt.activity; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileOutputStream; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import android.app.AlertDialog; import android.content.ContentValues; import android.content.DialogInterface; import android.content.Intent; import android.database.Cursor; import android.graphics.Bitmap; import android.graphics.Color; import android.location.Location; import android.net.Uri; import android.os.Bundle; import android.os.Environment; import android.os.Handler; import android.os.Message; import android.provider.MediaStore; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.widget.AdapterView; import android.widget.AdapterView.OnItemSelectedListener; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.EditText; import android.widget.ImageButton; import android.widget.LinearLayout; import android.widget.Spinner; import android.widget.TextView; import android.widget.Toast; import com.esri.core.geometry.Point; import com.esri.core.map.FeatureSet; import com.esri.core.tasks.SpatialRelationship; import com.smartdot.cgt.R; import com.smartdot.cgt.activity.baidu.ProblemInputMap; import com.smartdot.cgt.model.CaseModel; import com.smartdot.cgt.model.DictTypeModel; import com.smartdot.cgt.model.ResponseResult; import com.smartdot.cgt.request.ApiClent; import com.smartdot.cgt.request.Request; import com.smartdot.cgt.util.ActivityTools; import com.smartdot.cgt.util.ApplicationMain; import com.smartdot.cgt.util.BaseThread; import com.smartdot.cgt.util.BitmapConvert; import com.smartdot.cgt.util.GpsManager; import com.smartdot.cgt.util.HandlerStatus; import com.smartdot.cgt.util.MapUtil; import com.smartdot.cgt.util.Msg; import com.smartdot.cgt.util.PointD; import com.smartdot.cgt.util.StringUtils; import com.smartdot.cgt.view.ImagesLayout; import com.smartdot.cgt.view.SoundRecorder; import com.smartdot.cgt.view.TitleBar; import org.json.JSONException; import org.json.JSONObject; public class FrmSanBaoInput extends BaseActivity { private static int SELECT_PICTURE = 0; private static int TAKE_PHOTO = 1; private String txtPartNum; //新版本中没有该参数 private String txtGrid; //新版本中没有该参数 private EditText spinSq; private EditText txtAddress; private EditText txtEventDesc; private EditText txtLongitude; private EditText txtLatitude; private View btnGetImage; public static final String NEEDGETLOCATION = "needGetLocation"; private View btnGetPosition; private ImagesLayout imagesLayout; private ImageButton closeBtn1,closeBtn2,closeBtn3; private Button submit_bt; private SoundRecorder soundRecorder; private AlertDialog soundDialog; private String eventId; private String pictureId; private String cacheDept1; private String cacheDept2; private String cacheDept3; public String shequid = null; public String shopid= null,shopname= null,shoptel= null; public int imgcount=0; private BaseThread thread; public List<Map<String,String>> lclass,sclass; private HashMap<String, BaseThread> threadList = new HashMap<String, BaseThread>( 5); private final String THREAD_SUBMIT_FIELD = "THREAD_SUBMIT_FIELD"; private final String THREAD_SUBMIT_PICTURE0 = "THREAD_SUBMIT_PICTURE0"; private final String THREAD_SUBMIT_PICTURE1 = "THREAD_SUBMIT_PICTURE1"; private final String THREAD_SUBMIT_PICTURE2 = "THREAD_SUBMIT_PICTURE2"; private final String THREAD_SUBMIT_AUDIO = "THREAD_SUBMIT_Audio"; private final int RESULT_POINT = 1101; private List<String> picpaths; private TextView txtSh ; @Override protected void setLayout() { initActivity(); setContentView(R.layout.problemsanbaoinput); spinSq = (EditText) findViewById(R.id.spinSq); txtAddress = (EditText) findViewById(R.id.txtAddress); txtEventDesc = (EditText) findViewById(R.id.txtEventDesc); txtLongitude = (EditText) findViewById(R.id.txtLongitude); txtLatitude = (EditText) findViewById(R.id.txtLatitude); btnGetImage = (View) findViewById(R.id.btnGetImage); btnGetPosition = (View) findViewById(R.id.shanghu_allow_button); imagesLayout = (ImagesLayout) ApplicationMain.getInstance().inflateView(R.layout.imagelayout); closeBtn1 = (ImageButton) imagesLayout.findViewById(R.id.closeBtn1); closeBtn2 = (ImageButton) imagesLayout.findViewById(R.id.closeBtn2); closeBtn3 = (ImageButton) imagesLayout.findViewById(R.id.closeBtn3); soundRecorder = (SoundRecorder) ApplicationMain.getInstance().inflateView(R.layout.soundrecorderview); submit_bt = (Button) findViewById(R.id.pt_submit_bt); submit_bt.setOnClickListener(btnSubmitOnClick); txtSh = (TextView) findViewById(R.id.txtSh); LinearLayout mainLayout = (LinearLayout) findViewById(R.id.layout_pic); mainLayout.addView(imagesLayout); TitleBar titlebar = (TitleBar) this.findViewById(R.id.titlebar); titlebar.setTitleText("五包上报"); titlebar.setRigthText(R.string.below_btn_submit); imagesLayout.setVisibility(View.GONE); submit_bt.setClickable(true); } @Override protected void doInit() { getPosition(); } private OnItemSelectedListener onItemSelectedListener = new OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) { TextView v1 = (TextView) arg1; } @Override public void onNothingSelected(AdapterView<?> arg0) { } }; private OnClickListener btnSubmitOnClick = new OnClickListener() { @Override public void onClick(View v) { submitData(); } }; private OnClickListener onClickListener = new OnClickListener() { @Override public void onClick(View arg0) { if (arg0 == btnGetPosition) { //地图和百度地图切换 int getLocationId = ActivityTools.GETLOCATION_SHOP; Intent intent = new Intent(FrmSanBaoInput.this, FrmMap.class); intent.putExtra(NEEDGETLOCATION, getLocationId); startActivityForResult(intent, getLocationId); // ActivityTools.getInstance().takePosition(getLocationId, txtLongitude, txtLatitude, FrmSanBaoInput.this); // getTiDiMapPoint(); } else if (arg0 == btnGetImage) {// 点击获取图片 ActivityTools.getInstance().takePicture(SELECT_PICTURE, TAKE_PHOTO, FrmSanBaoInput.this); } else if(arg0 == closeBtn1) { imagesLayout.removeSelectedImage(0); if(imgcount==1) closeBtn1.setVisibility(View.INVISIBLE); else if(imgcount==2) closeBtn2.setVisibility(View.INVISIBLE); else if(imgcount==3) closeBtn3.setVisibility(View.INVISIBLE); imgcount--; } else if(arg0 == closeBtn2) { imagesLayout.removeSelectedImage(1); if(imgcount==1) closeBtn1.setVisibility(View.INVISIBLE); else if(imgcount==2) closeBtn2.setVisibility(View.INVISIBLE); else if(imgcount==3) closeBtn3.setVisibility(View.INVISIBLE); imgcount--; } else if(arg0 == closeBtn3) { imagesLayout.removeSelectedImage(2); if(imgcount==1) closeBtn1.setVisibility(View.INVISIBLE); else if(imgcount==2) closeBtn2.setVisibility(View.INVISIBLE); else if(imgcount==3) closeBtn3.setVisibility(View.INVISIBLE); imgcount--; } } }; @Override protected void onActivityResult(int requestCode, int resultCode, Intent intent) { if (resultCode == RESULT_OK) { if (requestCode == SELECT_PICTURE) { Bitmap yourSelectedImage = getImageFromReturnIntent(intent); if (yourSelectedImage != null) { imagesLayout.addSelectedImage(yourSelectedImage); if(imgcount<3){ imgcount++; if(imgcount==1) closeBtn1.setVisibility(View.VISIBLE); else if(imgcount==2) closeBtn2.setVisibility(View.VISIBLE); else if(imgcount==3) closeBtn3.setVisibility(View.VISIBLE); } } } else if (requestCode == TAKE_PHOTO) { Bitmap bitmap = getImageFromCameraIntent(intent); if (bitmap != null) { imagesLayout.addSelectedImage(bitmap); if(imgcount<3){ imgcount++; if(imgcount==1) closeBtn1.setVisibility(View.VISIBLE); else if(imgcount==2) closeBtn2.setVisibility(View.VISIBLE); else if(imgcount==3) closeBtn3.setVisibility(View.VISIBLE); } } } else if (requestCode == ActivityTools.GETLOCATION_SHOP) { Bundle bundle = intent.getExtras(); String longitude=null; String latitude=null; if (bundle != null && bundle.containsKey("MapReturn_X")) { longitude=String.valueOf(bundle.get("MapReturn_X")); latitude=String.valueOf(bundle.get("MapReturn_Y")); } String shequ = bundle.getString(MapReturn_SheQu); shequid = bundle.getString(MapReturn_SheQuId); String gridId = bundle.getString(MapReturn_GridId); shopid = bundle.getString(MapReturn_ShopId); shopname = bundle.getString(MapReturn_ShopName); txtSh.setText(shopname); shoptel = bundle.getString(MapReturn_ShopTel); spinSq.setText(shequ); txtLongitude.setText(longitude); txtLatitude.setText(latitude); setTxtGrid(gridId);//新版本中没有该参数 Msg.showInfo(FrmSanBaoInput.this, "已获取指定点信息!"); } } else if (resultCode == ProblemInputMap.RESULTCODE) { String lat = intent.getStringExtra("lat"); String lon = intent.getStringExtra("lon"); String address = intent.getStringExtra("address"); if (StringUtils.isNotBlank(lat)) { txtLatitude.setText(lat); } if (StringUtils.isNotBlank(lon)) { txtLongitude.setText(lon); } if (StringUtils.isNotBlank(address)) { txtAddress.setText(address); } } } @Override protected void addEventListener() { btnGetPosition.setOnClickListener(onClickListener); btnGetImage.setOnClickListener(onClickListener); closeBtn1.setOnClickListener(onClickListener); closeBtn2.setOnClickListener(onClickListener); closeBtn3.setOnClickListener(onClickListener); // btnGetAudio.setOnClickListener(onClickListener); imagesLayout.setOnCountChange(imagesLayout.new OnCountChange() { @Override public void getNowCount(int nowCount) { imagesLayout.setVisibility(nowCount == 0 ? View.GONE : View.VISIBLE); btnGetImage.setEnabled(nowCount < 3); imagesLayout.requestFocus(); } }); imagesLayout.setOnPreviewImage(imagesLayout.new OnPreviewImage() { @Override public void previewImage(int viewIndex) { Intent intent = new Intent(FrmSanBaoInput.this, FrmViewImage.class); intent.putExtra(FrmViewImage.BITMAPKEY, imagesLayout.getSelectedImagesPath()); intent.putExtra(FrmViewImage.FIRSTSHOWINDEX, viewIndex); startActivity(intent); } }); } @SuppressWarnings("unchecked") @Override protected void handleMessage(Message msg) { if (msg.what == HandlerStatus.SUBMIT_FIELDVALUE) { threadList.get(THREAD_SUBMIT_FIELD).interrupt(); if (msg.arg1 == HandlerStatus.HANDLE_OK) { // String str =(String) msg.obj; // Msg.showInfo(FrmSanBaoInput.this, str); Msg.showInfo(FrmSanBaoInput.this, "上传成功!"); finishActivity(checkIsNeedCloseProgress()); } else if (msg.arg1 == HandlerStatus.HANDLE_FAIL) { Msg.showInfo(FrmSanBaoInput.this, "案卷录入提交失败!"); } else { Msg.showInfo(FrmSanBaoInput.this, "案卷录入提交失败!"); // Msg.showInfo(FrmProblemInput.this, "案卷录入时连接出错,将自动缓存在本地,待网络联通后自动上报!"); // addCaseToDB((CaseModel) msg.obj); // finishActivity(checkIsNeedCloseProgress(), true); } checkIsNeedCloseProgress(); } else if (msg.what == HandlerStatus.SUBMIT_PICTURE0) { threadList.get(THREAD_SUBMIT_PICTURE0).interrupt(); if (msg.arg1 == HandlerStatus.HANDLE_OK) { // Msg.showInfo(FrmSanBaoInput.this, "图片上传成功!"); finishActivity(checkIsNeedCloseProgress()); } else if (msg.arg1 == HandlerStatus.HANDLE_FAIL) { Msg.showInfo(FrmSanBaoInput.this, "上传图片失败!"); } else { Msg.showInfo(FrmSanBaoInput.this, "上传图片时出现错误!"); } checkIsNeedCloseProgress(); } else if (msg.what == HandlerStatus.SUBMIT_AUTIO) { threadList.get(THREAD_SUBMIT_AUDIO).interrupt(); if (msg.arg1 == HandlerStatus.HANDLE_OK) { Msg.showInfo(FrmSanBaoInput.this, "录音上传成功!"); finishActivity(checkIsNeedCloseProgress()); } else if (msg.arg1 == HandlerStatus.HANDLE_FAIL) { Msg.showInfo(FrmSanBaoInput.this, "录音上传失败!"); } else { Msg.showInfo(FrmSanBaoInput.this, "录音上传时出现错误!"); } checkIsNeedCloseProgress(); } else if (msg.what == HandlerStatus.MAP_QUERYGRID) { closeProgress(); if (msg.arg1 == HandlerStatus.HANDLE_OK) { // String[] gridAndAddress = ((String) msg.obj).split("&"); String gridId = (String) msg.obj; // txtGrid.setText(gridId);新版本中没有该参数 // if (gridAndAddress.length > 1) // { txtGrid=gridId; // } } } } @Override protected void onCancelProgress(DialogInterface arg0) { for (BaseThread thread : threadList.values()) { if (thread != null) { thread.interrupt(); } } threadList.clear(); // FrmProblemInput.this.finish(); } private boolean checkFieldValue(CaseModel inputCase) { StringBuilder errorBuilder = new StringBuilder(); if(StringUtils.isNullOrEmpty(shopid)){ errorBuilder.append("请先通过地图获取商户信息!\n"); } if(StringUtils.isNullOrEmpty(shequid)){ errorBuilder.append("请先通过地图获取社区信息!\n"); }else { inputCase.setSq(shequid); } inputCase.setCaseAddress(txtAddress.getText().toString().trim()); inputCase.setCaseSituation(txtEventDesc.getText().toString().trim()); if (!StringUtils.isNullOrEmpty(txtLongitude.getText().toString())) { inputCase.setCaseLongitude(txtLongitude.getText().toString()); } else { errorBuilder.append("请先获取经纬度坐标!\n"); } if (!StringUtils.isNullOrEmpty(txtLatitude.getText().toString())) { inputCase.setCaseLatitude(txtLatitude.getText().toString()); } else { errorBuilder.append("请先获取经纬度坐标!\n"); } if(StringUtils.isNullOrEmpty(txtAddress.getText().toString().trim())){ errorBuilder.append("请填写发生地点!\n"); } if(txtAddress.getText().toString().length()>50){ errorBuilder.append("发生地点不能超过50字!\n"); } if(txtEventDesc.getText().toString().length()>50){ errorBuilder.append("案卷描述不能超过50字!\n"); } if(StringUtils.isNullOrEmpty(txtEventDesc.getText().toString().trim())){ errorBuilder.append("请描述案卷描述!\n"); } inputCase.setCaseGrid(getTxtGrid()); inputCase.setCasePartNum(getTxtPartNum()); if (imagesLayout.getSelectedImageCount() <2) { errorBuilder.append("请上传二张图片!"); } boolean checkResult = errorBuilder.length() == 0; if (!checkResult) { Msg.showInfo(FrmSanBaoInput.this, errorBuilder.toString()); } return checkResult; } /** // * @param imageReturnedIntent * @return */ private Bitmap getImageFromCameraIntent(Intent imageReturnedIntent) { Bitmap bitmap = BitmapConvert.resizeBitmap(ApplicationMain .getInstance().getImageTempPath()); if (bitmap == null) { Msg.showInfo(this, "未能获取所拍摄的图片!"); } return bitmap; } /** * @param imageReturnedIntent * @return */ private Bitmap getImageFromReturnIntent(Intent imageReturnedIntent) { Bitmap yourSelectedImage = null; try { String filePath = ""; Uri selectedImage = imageReturnedIntent.getData(); String[] filePathColumn = { MediaStore.Images.Media.DATA }; Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null); if (cursor != null) { cursor.moveToFirst(); int columnIndex = cursor.getColumnIndex(filePathColumn[0]); filePath = cursor.getString(columnIndex); cursor.close(); } else { filePath = selectedImage.getPath(); } yourSelectedImage = BitmapConvert.resizeBitmap(filePath); } catch (Exception e) { Msg.showInfo(this, "未找到图片!"); } return yourSelectedImage; } private void submitData() { submit_bt.setClickable(false); // if (!StringUtils.isNullOrEmpty(eventId) && !StringUtils.isNullOrEmpty(pictureId)) // { // if (imagesLayout.getSelectedImageCount() <= 0 ) // { // finishActivity(checkIsNeedCloseProgress()); // } // else // { // submitPicture(pictureId); // } // } // else // { if (imagesLayout.getSelectedImageCount() <2) { Msg.showInfo(FrmSanBaoInput.this, "请上传二张图片"); submit_bt.setClickable(true); } else { // TODO 伪造一个提交Dialog // dialogHandler.sendEmptyMessageDelayed(4, 1000); CaseModel inputCase = new CaseModel(); inputCase.setDept1(cacheDept1); inputCase.setDept2(cacheDept2); inputCase.setDept3(cacheDept3); if (checkFieldValue(inputCase)) { showProgress("案卷提交中。。。", "案卷上报"); picpaths = new ArrayList<String>(); submitPicture(); submitField(inputCase); }else{ submit_bt.setClickable(true); } } // } } public File getFile(Bitmap bm) { Long random = System.currentTimeMillis(); String randomstr = random.toString(); String path = Environment.getExternalStorageDirectory() + "/Ask"; File dirFile = new File(path); if(!dirFile.exists()){ dirFile.mkdir(); } File myCaptureFile = new File(path +"/" + randomstr +".jpg"); try { BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(myCaptureFile)); bm.compress(Bitmap.CompressFormat.JPEG, 80, bos); bos.flush(); bos.close(); }catch (Exception e){ e.printStackTrace(); } return myCaptureFile; } private void submitPicture(){ final Bitmap[] bitmapList = imagesLayout.getSelectedImages(); BaseThread thread = new BaseThread(baseHandler) { @Override public void runThread() { final Message msg = this.obtainMessage(); if (msg != null) { msg.what = HandlerStatus.SUBMIT_PICTURE0; try { for (int i = 0, count = imagesLayout.getSelectedImageCount(); i < count; i++){ final int nowIndex = i; File file = getFile(bitmapList[nowIndex]); ApiClent.fileupload(file, new ApiClent.ClientCallback() { @Override public void onSuccess(Object data) { try { JSONObject jsonObject = new JSONObject(data.toString()); picpaths.add(jsonObject.getString("data")); msg.arg1 = HandlerStatus.HANDLE_OK; } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); Log.i("fileupload", e.getMessage()); msg.arg1 = HandlerStatus.HANDLE_FAIL; } } @Override public void onFailure(String message) { System.out.println("fileupload.message------------------ " + message); msg.arg1 = HandlerStatus.HANDLE_FAIL; } @Override public void onError(Exception e) { System.out.println("fileupload.e.getMessage()------------------ " + e.getMessage()); msg.arg1 = HandlerStatus.HANDLE_FAIL; } }); } } catch (Exception e) { msg.arg1 = HandlerStatus.HANDLE_ERROR; } this.sendMessage(msg); } } }; showProgress("图片上传中。。。", "案卷录入"); thread.start(); final String key = "THREAD_SUBMIT_PICTURE0"; threadList.put(key, thread); } private void submitField(CaseModel inputCase) { final CaseModel toSubmitCase = inputCase; BaseThread thread = new BaseThread(baseHandler) { @Override public void runThread() { final Message msg = this.obtainMessage(); if (msg != null) { msg.what = HandlerStatus.SUBMIT_FIELDVALUE; try { while(picpaths.size()<imagesLayout.getSelectedImageCount()){ Thread.currentThread().sleep(500); } String picstr ="" ; for(int i=0; i<picpaths.size(); i++){ if(i>0) picstr+=","; picstr+=picpaths.get(i); } ApiClent.inputNewCaseByShop("0","0", toSubmitCase.getCaseLongitude(), toSubmitCase.getCaseLatitude(), "2","1", toSubmitCase.getCaseGrid().substring(0,6),toSubmitCase.getCaseGrid().substring(0,9), toSubmitCase.getSq(),toSubmitCase.getCaseGrid(),toSubmitCase.getCaseSituation(),toSubmitCase.getCaseAddress() ,picstr,0,0,shopid,shopname,shoptel, new ApiClent.ClientCallback() { @Override public void onSuccess(Object data) { try { JSONObject jsonObject = new JSONObject(data.toString()); msg.obj = jsonObject.getString("message"); msg.arg1 = HandlerStatus.HANDLE_OK; } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); Log.i("inputNewCase", e.getMessage()); msg.arg1 = HandlerStatus.HANDLE_FAIL; } } @Override public void onFailure(String message) { System.out.println("inputNewCase.message------------------ " + message); msg.arg1 = HandlerStatus.HANDLE_FAIL; } @Override public void onError(Exception e) { System.out.println("inputNewCase.e.getMessage()------------------ " + e.getMessage()); msg.arg1 = HandlerStatus.HANDLE_FAIL; } }); } catch (Exception e) { msg.arg1 = HandlerStatus.HANDLE_ERROR; msg.obj = toSubmitCase; } this.sendMessage(msg); } } }; showProgress("案卷提交中。。。", "案卷录入"); thread.start(); threadList.put(THREAD_SUBMIT_FIELD, thread); } private void finishActivity(boolean canClose) { this.finishActivity(canClose, false); } private void finishActivity(boolean canClose, boolean needCacheAudio) { if (canClose) { if (imagesLayout.getSelectedImageCount() > 0) { try { Request.getRequest().saveImageCache(imagesLayout.getSelectedImages(), eventId, null); } catch (Exception e) { e.printStackTrace(); } } if (needCacheAudio && soundRecorder.getIsSoundFileExists()) { try { Request.getRequest().saveAudioCache(soundRecorder.getRecordFilePath(), eventId); } catch (Exception e) { e.printStackTrace(); } } FrmSanBaoInput.this.finish(); } } /** * */ private boolean checkIsNeedCloseProgress() { boolean canCloseProgress = true; for (BaseThread thread : threadList.values()) { if (thread != null && thread.getIsThreadGoing()) { canCloseProgress = false; } } if (canCloseProgress) { try { closeProgress(); } catch (Exception e) { e.printStackTrace(); } } return canCloseProgress; } private void getPosition() { Location location = GpsManager.getGpsSingerton().getLocation(); if (location != null) { double longitude = (double) Math.round(location.getLongitude() * 100000000) / 100000000; double latitude = (double) Math.round(location.getLatitude() * 100000000) / 100000000; final PointD point = new PointD(longitude, latitude); txtLongitude.setText(Double.toString(longitude)); txtLatitude.setText(Double.toString(latitude)); } } // TODO class DialogHandler extends Handler { @Override public void handleMessage(Message msg) { super.handleMessage(msg); closeProgress(); Toast.makeText(FrmSanBaoInput.this, "上报成功", Toast.LENGTH_SHORT) .show(); } } public String getTxtPartNum() { return txtPartNum; } public void setTxtPartNum(String txtPartNum) { this.txtPartNum = txtPartNum; } public String getTxtGrid() { return txtGrid; } public void setTxtGrid(String txtGrid) { this.txtGrid = txtGrid; } }