package cn.com.countrygarden.bi.main.sms;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.alibaba.cloudapi.sdk.core.model.ApiResponse;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import cn.com.countrygarden.bi.main.dto.TemplateParamVo;
import cn.com.countrygarden.bi.main.sms.client.SyncApiClientSmsService;
@Component
public class SmsSend {
	private final static Logger logger = LoggerFactory.getLogger(SmsSend.class);
	
	@Autowired
	private SyncApiClientSmsService syncApiClientSmsService;

	
	public List<TemplateParamVo> getAllDepartments(List<TemplateParamVo> topList, int number) {
		List<TemplateParamVo> list = new ArrayList<TemplateParamVo>();
		walkSmsDataVoTrees(topList, list, number);
		return list;

	}

	public void walkSmsDataVoTrees(Collection<TemplateParamVo> topList, List<TemplateParamVo> list, int number) {
		if (number > 0) {
			JSONObject jsonObject = null;
			JSONObject jsonData = null;
			ApiResponse response = null;
			TemplateParamVo templateParamVoTop = null;

			List<TemplateParamVo> list2 = new ArrayList<TemplateParamVo>();
			for (TemplateParamVo templateParamVo : topList) {
				templateParamVoTop = new TemplateParamVo();
				response = syncApiClientSmsService.postSms(null, null, null, null, null, null,
						templateParamVo.getPhone(), templateParamVo.getUrl(), "marketing", "fr4SJVclw4d0jb1W");
				try {
					// 获得发送的数据
					jsonObject = JSON.parseObject((new String(response.getBody(), "utf-8")).toString());

					jsonData = JSON.parseObject(jsonObject.getString("data"));
					response = syncApiClientSmsService.getSms(null, null, null, null, null, null,
							jsonData.getInteger("id"));
					// 通过发送数据其中的id得到信息发送的状态
					jsonObject = JSON.parseObject((new String(response.getBody(), "utf-8")).toString());
					jsonData = JSON.parseObject(jsonObject.getString("data"));
					logger.error((new String(response.getBody(), "utf-8")).toString());
					// 根据statusCode判断是否发送成功，如失败的号码再重发3次
					if (!jsonData.getString("statusCode").equals("0") && !jsonData.getString("statusCode").equals("200")
							&& !jsonData.getString("statusCode").equals("DELIVRD")) {
						templateParamVoTop.setPhone(templateParamVo.getPhone());
						templateParamVoTop.setUrl(templateParamVo.getUrl());
						list2.add(templateParamVoTop);
					}
				} catch (UnsupportedEncodingException e) {
					e.printStackTrace();
				}
			}
			number--;
			walkSmsDataVoTrees(list2, list, number);
		}

	}
}
