Newer
Older
dxcgt / app / src / main / java / com / smartdot / cgt / activity / FrmProblemInput.java
wangxitong on 6 Apr 2021 32 KB first commit
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.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.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;

import static com.smartdot.cgt.R.drawable.probleminput_et;


public class FrmProblemInput extends BaseActivity
{
	private static int SELECT_PICTURE = 0;
	private static int TAKE_PHOTO = 1;
	private Spinner spinProblemType;
	private Spinner spinLargeClass;
	private Spinner spinSmallClass;
	public static final String NEEDGETLOCATION = "needGetLocation";

	private String txtPartNum; //新版本中没有该参数
	private String txtGrid; //新版本中没有该参数
	private EditText spinSq;
	private EditText txtAddress;
	private EditText txtEventDesc;
	private EditText txtLongitude;
	private EditText txtLatitude;
	private View btnGetImage;

	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 caseLClass = null;
	private String caseSClass = null;
	private String cacheDept1;
	private String cacheDept2;
	private String cacheDept3;
	public String shequid = 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;
	ArrayAdapter<String> type_arr_adapter;

	@Override
	protected void setLayout()
	{
		initActivity();

		setContentView(R.layout.probleminput);

		spinProblemType = (Spinner) findViewById(R.id.spinProblemType);
		spinLargeClass = (Spinner) findViewById(R.id.spinLargeClass);
		spinSmallClass = (Spinner) findViewById(R.id.spinSmallClass);
		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.btnGetPosition);
		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);
		LinearLayout mainLayout = (LinearLayout) findViewById(R.id.layout_pic);
		mainLayout.addView(imagesLayout);

		TitleBar titlebar = (TitleBar) this.findViewById(R.id.titlebar);

		titlebar.setTitleText(R.string.module_probleminput);
		titlebar.setRigthText(R.string.below_btn_submit);

		List<String> data_list = new ArrayList<String>();
		data_list.add("事件");
		data_list.add("部件");
		type_arr_adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, data_list);
		type_arr_adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		spinProblemType.setAdapter(type_arr_adapter);
		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;
			if (arg0 == spinProblemType)
			{
				spinProblemType.getChildAt(0).setVisibility(View.VISIBLE);
				caseLClass = null;
				caseSClass = null;
				changeLClassType(arg2);
				if(arg2 == 1){
					spinLargeClass.setClickable(false);
					spinSmallClass.setClickable(false);
					spinLargeClass.setBackgroundResource(R.drawable.probleminput_et);
					spinSmallClass.setBackgroundResource(R.drawable.probleminput_et);
				}else if(arg2 == 0){
					spinLargeClass.setClickable(true);
					spinSmallClass.setClickable(true);
					spinLargeClass.setBackgroundResource(R.drawable.probleminput_spinner);
					spinSmallClass.setBackgroundResource(R.drawable.probleminput_spinner);
				}
			}
			else if (arg0 == spinLargeClass)
			{
				changeSClassType(arg2);
				if(spinProblemType.getSelectedItemPosition()==0){
					v1.setTextColor(Color.parseColor("#000000"));
				}else if(spinProblemType.getSelectedItemPosition()==1){
					v1.setTextColor(Color.parseColor("#999999"));
				}
			}
			else if (arg0 == spinSmallClass)
			{
				if(spinProblemType.getSelectedItemPosition()==0){
					v1.setTextColor(Color.parseColor("#000000"));
				}else if(spinProblemType.getSelectedItemPosition()==1){
					v1.setTextColor(Color.parseColor("#999999"));
				}
			}
		}

		@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)
			{
				//地图和百度地图切换
				 String type = spinProblemType.getSelectedItem().toString();
				 int getLocationId = ActivityTools.GETLOCATION_NONE;
				 if ("部件".equals(type))
				 {
				 	 getLocationId = ActivityTools.GETLOCATION_PART;
					 Intent intent = new Intent(FrmProblemInput.this, FrmMap.class);
					 intent.putExtra("needGetLocation", getLocationId);
					 startActivityForResult(intent, getLocationId);
//					ActivityTools.getInstance().takePosition(getLocationId, txtLongitude, txtLatitude, FrmProblemInput.this);
				 }
				 else if ("事件".equals(type))
				 {
				 	 getLocationId = ActivityTools.GETLOCATION_EVENT;
					 Intent intent = new Intent(FrmProblemInput.this, FrmMap.class);
					 intent.putExtra("needGetLocation", getLocationId);
					 startActivityForResult(intent, getLocationId);
//					ActivityTools.getInstance().takePosition(getLocationId, txtLongitude, txtLatitude, FrmProblemInput.this);
				 }
			}
			else if (arg0 == btnGetImage)
			{// 点击获取图片
				ActivityTools.getInstance().takePicture(SELECT_PICTURE, TAKE_PHOTO, FrmProblemInput.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_EVENT
					|| requestCode == ActivityTools.GETLOCATION_PART)
			{
				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 partNumber = bundle.getString(MapReturn_PartId);
				caseLClass = bundle.getString(MapReturn_LClass);
				caseSClass = bundle.getString(MapReturn_SClass);
				String shequ = bundle.getString(MapReturn_SheQu);
				shequid = bundle.getString(MapReturn_SheQuId);
				String gridId = bundle.getString(MapReturn_GridId);
//				String address = bundle.getString(MapReturn_Address);
				spinSq.setText(shequ);
				txtLongitude.setText(longitude);
				txtLatitude.setText(latitude);
				setTxtGrid(gridId);
//				txtAddress.setText(address);
				if (!StringUtils.isNullOrEmpty(caseLClass) && !StringUtils.isNullOrEmpty(caseSClass))
				{
					for(int i=0; i<lclass.size(); i++){
						if(caseLClass.equals(lclass.get(i).get("typeName"))){
							spinLargeClass.setSelection(i,true);
							changeSClassType(i);
							break;
						}
					}
				}
				Msg.showInfo(FrmProblemInput.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()
	{
		spinProblemType.setOnItemSelectedListener(onItemSelectedListener);
		spinProblemType.setSelection(0, true);
//		spinProblemType.getChildAt(0).setVisibility(View.INVISIBLE);
		spinLargeClass.setSelection(0, true);
		spinLargeClass.setOnItemSelectedListener(onItemSelectedListener);
		spinSmallClass.setSelection(0, true);
		spinSmallClass.setOnItemSelectedListener(onItemSelectedListener);

		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(FrmProblemInput.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(FrmProblemInput.this, str);
				Msg.showInfo(FrmProblemInput.this, "上传成功!");
				finishActivity(checkIsNeedCloseProgress());
			}
			else if (msg.arg1 == HandlerStatus.HANDLE_FAIL)
			{
				Msg.showInfo(FrmProblemInput.this, "案卷录入提交失败!");
			}
			else
			{
				Msg.showInfo(FrmProblemInput.this, "案卷录入提交失败!");
//				Msg.showInfo(FrmProblemInput.this, "案卷录入时连接出错,将自动缓存在本地,待网络联通后自动上报!");
//				addCaseToDB((CaseModel) msg.obj);
//				finishActivity(checkIsNeedCloseProgress(), true);
			}

			checkIsNeedCloseProgress();

		}
		else if (msg.what == HandlerStatus.REQUEST_LCLASS)
		{

			if (msg.arg1 == HandlerStatus.HANDLE_OK)
			{
				try {
					List<String> data_list = (List<String>) msg.obj;
					ArrayAdapter<String> arr_adapter = new ArrayAdapter<String>(FrmProblemInput.this, android.R.layout.simple_spinner_item, data_list);
					arr_adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
					spinLargeClass.setAdapter(arr_adapter);
					arr_adapter.notifyDataSetChanged();
					spinLargeClass.setSelection(0,true);
				}catch (Exception e){
					e.printStackTrace();
				}
			}
			else if (msg.arg1 == HandlerStatus.HANDLE_FAIL)
			{
				Msg.showInfo(FrmProblemInput.this, "获取大类信息失败!");
			}
			else
			{
				Msg.showInfo(FrmProblemInput.this, "获取大类信息时出现错误!");
			}
			checkIsNeedCloseProgress();
		}
		else if (msg.what == HandlerStatus.REQUEST_SCLASS)
		{
			if (msg.arg1 == HandlerStatus.HANDLE_OK)
			{
				try {
					List<String> data_list = (List<String>) msg.obj;
					ArrayAdapter<String> arr_adapter = new ArrayAdapter<String>(FrmProblemInput.this, android.R.layout.simple_spinner_item, data_list);
					arr_adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
					spinSmallClass.setAdapter(arr_adapter);
					arr_adapter.notifyDataSetChanged();
					if(!StringUtils.isNullOrEmpty(caseLClass)){
						for(int i=0; i<sclass.size(); i++){
							if(caseSClass.equals(sclass.get(i).get("typeDetailName"))){
								spinSmallClass.setSelection(i,true);
								break;
							}
						}
					}else{
						spinSmallClass.setSelection(0,true);
					}
				}catch (Exception e){
					e.printStackTrace();
				}
			}
			else if (msg.arg1 == HandlerStatus.HANDLE_FAIL)
			{
				Msg.showInfo(FrmProblemInput.this, "获取小类信息失败!");
			}
			else
			{
				Msg.showInfo(FrmProblemInput.this, "获取小类信息时出现错误!");
			}
			checkIsNeedCloseProgress();
		}
		else if (msg.what == HandlerStatus.SUBMIT_PICTURE0)
		{
			threadList.get(THREAD_SUBMIT_PICTURE0).interrupt();
			if (msg.arg1 == HandlerStatus.HANDLE_OK)
			{
//				Msg.showInfo(FrmProblemInput.this, "图片上传成功!");
				finishActivity(checkIsNeedCloseProgress());
			}
			else if (msg.arg1 == HandlerStatus.HANDLE_FAIL)
			{
				Msg.showInfo(FrmProblemInput.this, "上传图片失败!");
			}
			else
			{
				Msg.showInfo(FrmProblemInput.this, "上传图片时出现错误!");
			}
			checkIsNeedCloseProgress();
		}
		else if (msg.what == HandlerStatus.SUBMIT_AUTIO)
		{
			threadList.get(THREAD_SUBMIT_AUDIO).interrupt();
			if (msg.arg1 == HandlerStatus.HANDLE_OK)
			{
				Msg.showInfo(FrmProblemInput.this, "录音上传成功!");
				finishActivity(checkIsNeedCloseProgress());
			}
			else if (msg.arg1 == HandlerStatus.HANDLE_FAIL)
			{
				Msg.showInfo(FrmProblemInput.this, "录音上传失败!");
			}
			else
			{
				Msg.showInfo(FrmProblemInput.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 void changeLClassType(int typeSelectedIndex)
	{
		thread = new BaseThread(baseHandler)
		{
			@Override
			public void runThread()
			{
				Message msg = thread.obtainMessage();
				if (msg != null)
				{
					msg.what = HandlerStatus.REQUEST_LCLASS;
					ResponseResult< List<Map<String,String>>> typelistResult = null;
					List<String> data_list = new ArrayList<String>();
					try
					{
						String casetype = (String)spinProblemType.getSelectedItem();
						if(casetype.equals("事件")){
							typelistResult = Request.getRequest().typelist("1");
							lclass = typelistResult.getResultObj();
							for (int i=0;i<lclass.size();i++)
								data_list.add(lclass.get(i).get("typeName"));
						}else if(casetype.equals("部件")){
							typelistResult = Request.getRequest().typelist("2");
							lclass = typelistResult.getResultObj();
							for (int i=0;i<lclass.size();i++)
								data_list.add(lclass.get(i).get("typeName"));
						}
						if (typelistResult.isSuccess())
						{
							msg.obj = data_list;
							msg.arg1 = HandlerStatus.HANDLE_OK;
						}
						else if (typelistResult.isHadError())
						{
							msg.arg1 = HandlerStatus.HANDLE_ERROR;
						}
						else
						{
							msg.arg1 = HandlerStatus.HANDLE_FAIL;
						}
					}
					catch (Exception e)
					{
						msg.arg1 = HandlerStatus.HANDLE_ERROR;
						msg.obj = e.getMessage();
						e.printStackTrace();
					}
					thread.sendMessage(msg);
				}
			}
		};
		thread.start();

	}


	/**
	 * @param lclassSelectedIndex
	 */
	private void changeSClassType(int lclassSelectedIndex)
	{
		final String index = lclass.get(lclassSelectedIndex).get("id");

		thread = new BaseThread(baseHandler)
		{
			@Override
			public void runThread()
			{
				Message msg = thread.obtainMessage();
				if (msg != null)
				{
					msg.what = HandlerStatus.REQUEST_SCLASS;
					ResponseResult< List<Map<String,String>>> typelistResult = null;
					List<String> data_list = new ArrayList<String>();
					try
					{
						String casetype = (String)spinProblemType.getSelectedItem();
						if(casetype.equals("事件")){
							typelistResult = Request.getRequest().typelistdetail("1",index);
							sclass = typelistResult.getResultObj();
							for (int i=0;i<sclass.size();i++)
								data_list.add(sclass.get(i).get("typeDetailName"));

						}else if(casetype.equals("部件")){
							typelistResult = Request.getRequest().typelistdetail("2",index);
							sclass = typelistResult.getResultObj();
							for (int i=0;i<sclass.size();i++)
								data_list.add(sclass.get(i).get("typeDetailName"));
						}
						if (typelistResult.isSuccess())
						{
							msg.obj = data_list;
							msg.arg1 = HandlerStatus.HANDLE_OK;
						}
						else if (typelistResult.isHadError())
						{
							msg.arg1 = HandlerStatus.HANDLE_ERROR;
						}
						else
						{
							msg.arg1 = HandlerStatus.HANDLE_FAIL;
						}
					}
					catch (Exception e)
					{
						msg.arg1 = HandlerStatus.HANDLE_ERROR;
						msg.obj = e.getMessage();
						e.printStackTrace();
					}
					thread.sendMessage(msg);
				}
			}
		};
		thread.start();
	}

	private boolean checkFieldValue(CaseModel inputCase)
	{
		StringBuilder errorBuilder = new StringBuilder();

		if (!StringUtils.isNullOrEmpty((String) spinProblemType.getSelectedItem()))
		{
			String casetype = (String) spinProblemType.getSelectedItem();
			if(casetype.equals("事件")){
				inputCase.setCaseTypeId("1");
			}else if(casetype.equals("部件")){
				inputCase.setCaseTypeId("2");
			}
		}
		else
		{
			errorBuilder.append("请选择类型!\n");
		}

		if (!StringUtils.isNullOrEmpty((String) spinLargeClass.getSelectedItem()))
		{
			String caselclassid = lclass.get(spinLargeClass.getSelectedItemPosition()).get("typeCode");
			inputCase.setCaseLClassId(caselclassid);
		}
		else
		{
			errorBuilder.append("请选择大类!\n");
		}
		if (!StringUtils.isNullOrEmpty((String) spinSmallClass.getSelectedItem()))
		{
			String casesclassid = sclass.get(spinSmallClass.getSelectedItemPosition()).get("typeDetailCode");
			inputCase.setCaseSClassId(casesclassid);
		}
		else
		{
			errorBuilder.append("请选择小类!\n");
		}

		if(StringUtils.isNullOrEmpty(shequid)){
			errorBuilder.append("请先通过地图获取社区信息!\n");
		}else {
			inputCase.setSq(shequid);
		}
		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(StringUtils.isNullOrEmpty(txtEventDesc.getText().toString().trim())){
			errorBuilder.append("请填写案卷描述!\n");
		}
		if(txtEventDesc.getText().toString().length()>50){
			errorBuilder.append("案卷描述不能超过50字!\n");
		}
		inputCase.setCaseAddress(txtAddress.getText().toString().trim());
		inputCase.setCaseSituation(txtEventDesc.getText().toString().trim());
		inputCase.setCaseGrid(getTxtGrid());
		inputCase.setCasePartNum(getTxtPartNum());
		// 新版本中没有该参数
		// if (!StringUtils.isNullOrEmpty(txtGrid.toString())) {

		// }
//		else {
//		 errorBuilder.append("网格号不能为空,请点击地图取点获取网格号!\n");
//		 }
		
		 if (imagesLayout.getSelectedImageCount() <2) {
			   errorBuilder.append("请上传二张图片!");
	     }

	     
	        
		boolean checkResult = errorBuilder.length() == 0;
		if (!checkResult)
		{
			Msg.showInfo(FrmProblemInput.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(FrmProblemInput.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);
							}
							Bundle bundle=getIntent().getExtras();
							String caseSource = bundle.getString("caseSource");
							ApiClent.inputNewCase("0","0", toSubmitCase.getCaseLongitude(), toSubmitCase.getCaseLatitude(),
									caseSource,"1",toSubmitCase.getCaseTypeId(),toSubmitCase.getCaseLClassId(), toSubmitCase.getCaseSClassId(),
									toSubmitCase.getCaseGrid().substring(0,6),toSubmitCase.getCaseGrid().substring(0,9),
									toSubmitCase.getSq(),toSubmitCase.getCaseGrid(),toSubmitCase.getCaseSituation(),
									toSubmitCase.getCaseAddress(),picstr,0,0, 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();
				}
			}
			FrmProblemInput.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(FrmProblemInput.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;
		}
	    
	    
}