package cn.ccy.text_weather.services;

import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;

import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;

import cn.ccy.test_weather.utils.ParseProvinceOrCity;

// 根据省份获取城市列表
public class GetCityService {
	// 定义Web Service的命名空间
	static final String SERVICE_NS = "http://WebXml.com.cn/";
	// 定义Web Service提供服务的URL
	static final String SERVICE_URL = "http://webservice.webxml.com.cn/WebServices/WeatherWS.asmx";

	public static List<String> getCityListByProvince(String province) {
		// 调用的方法
		final String methodName = "getSupportCityString";
		// 创建HttpTransportSE传输对象
		final HttpTransportSE ht = new HttpTransportSE(SERVICE_URL);
		ht.debug = true;
		// 使用SOAP1.1协议创建Envelop对象
		final SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
				SoapEnvelope.VER11);
		// 实例化SoapObject对象
		SoapObject soapObject = new SoapObject(SERVICE_NS, methodName);
		// 添加一个请求参数
		soapObject.addProperty("theRegionCode", province);
		envelope.bodyOut = soapObject;
		// 设置与.Net提供的Web Service保持较好的兼容性
		envelope.dotNet = true;
		FutureTask<List<String>> task = new FutureTask<List<String>>(
				new Callable<List<String>>() {
					@Override
					public List<String> call() throws Exception {
						// 调用Web Service
						ht.call(SERVICE_NS + methodName, envelope);
						if (envelope.getResponse() != null) {
							// 获取服务器响应返回的SOAP消息
							SoapObject result = (SoapObject) envelope.bodyIn;
							SoapObject detail = (SoapObject) result.getProperty(methodName + "Result");
							// 解析服务器响应的SOAP消息。
							return ParseProvinceOrCity
									.parseProvinceOrCity(detail);
						}
						return null;
					}
				});
		new Thread(task).start();
		try {
			return task.get();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

}
