package com.cloudcross.ssp.service.impl;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.cloudcross.ssp.model.AdGroup;
import com.cloudcross.ssp.model.AdGroupPlace;
import com.cloudcross.ssp.model.Location;
import com.cloudcross.ssp.model.Wifi;
import com.cloudcross.ssp.model.pojo.WifiPojo;
import com.cloudcross.ssp.service.IAdGroupScheduleService;
import com.cloudcross.ssp.service.IWifiService;
import com.cloudcross.ssp.base.dao.GenericIBatisDao;
import com.cloudcross.ssp.common.utils.MapBuilder;
import com.cloudcross.ssp.common.utils.Pager;
import com.cloudcross.ssp.common.utils.SqlHelper;

@Service
public class WifiService implements IWifiService{

	@Autowired
	private GenericIBatisDao myBatisDao;
	
	/**
	 * 以经度为longitude，纬度为latitude周围距离dis千米的所有热点
	 */
	@Override
	public List<Wifi> findNeighPosition(double longitude,double latitude,double dis,String location) {
		//先计算查询点的经纬度范围
		double r = 6371;//地球半径千米
		double dlng =  2*Math.asin(Math.sin(dis/(2*r))/Math.cos(latitude*Math.PI/180));
		dlng = dlng*180/Math.PI;//角度转为弧度
		double dlat = dis/r;
		dlat = dlat*180/Math.PI;		
		Double minlat =latitude-dlat;
		Double maxlat = latitude+dlat;
		Double minlng = longitude -dlng;
		Double maxlng = longitude + dlng;	
		HashMap<String, Object> paramMap = new HashMap<String, Object>();
		paramMap.put("minlat", minlat);
		paramMap.put("maxlat", maxlat);
		paramMap.put("minlng", minlng);
		paramMap.put("maxlng", maxlng);
		paramMap.put("location", location);
		System.out.println(paramMap + "kkkk");
		return myBatisDao.getList("wifiSqlMapper.findWifi",paramMap);		
//		return null;
	}
	//找到城市下面的所有的wifi热点
	public List<Wifi> findAllLocation(String location) {
		
		return myBatisDao.getList("wifiSqlMapper.findLocation",location);
		
	}
	
	//找到已选择的所有的wifi热点
	public List<Wifi> findAllAdgroupWifi(Long adGroupId) {
		return myBatisDao.getList("wifiSqlMapper.findAllAdgroupWifi",adGroupId);
	}
	
	@Override
	public Wifi findAddress(String address) {
		
		return myBatisDao.get("wifiSqlMapper.findAddress", address);
	}
		      
    /** 
     * 返回输入地址的经纬度坐标 
     * key lng(经度),lat(纬度) 
     */ 
	@Override
    public Map<String,String> getGeocoderLatitude(String address){  
    	final String KEY_1 = "fc9dbd184cd52c9855fcec1ef1bffb7c";
    	BufferedReader in = null;  
        try {  
            //将地址转换成utf-8的16进制  
            address = URLEncoder.encode(address, "UTF-8");  
//	           如果有代理，要设置代理，没代理可注释  
//	      System.setProperty("http.proxyHost","192.168.1.188");  
//	      System.setProperty("http.proxyPort","3128");  
            URL tirc = new URL("http://api.map.baidu.com/geocoder?address="+ address +"&output=json&key="+ KEY_1);  
              
            in = new BufferedReader(new InputStreamReader(tirc.openStream(),"UTF-8"));  
            String res;  
            StringBuilder sb = new StringBuilder("");  
            while((res = in.readLine())!=null){  
                sb.append(res.trim());  
            }  
            String str = sb.toString();  
            Map<String,String> map = null;  
            if(StringUtils.isNotEmpty(str)){  
                int lngStart = str.indexOf("lng\":");  
                int lngEnd = str.indexOf(",\"lat");  
                int latEnd = str.indexOf("},\"precise");  
                if(lngStart > 0 && lngEnd > 0 && latEnd > 0){  
                    String lng = str.substring(lngStart+5, lngEnd);  
                    String lat = str.substring(lngEnd+7, latEnd);  
                    map = new HashMap<String,String>();  
                    map.put("lng", lng);  
                    map.put("lat", lat);  
                    return map;  
                }  
            }  
        }catch (Exception e) {  
            e.printStackTrace();  
        }finally{  
            try {  
                in.close();  
            } catch (IOException e) {  
                e.printStackTrace();  
            }  
        }  
        return null;  
    }  
		
	public List<Location>findLocation(String location) {
		
		return null;
	}
	
	
	@Override
	public Wifi findById(Long id) {
		return myBatisDao.get("wifiSqlMapper.findById", id);
	}
	
	@Override
	public int countByParams(Map<String, Object> paramMap) {
		String searchValue = SqlHelper.doLike(paramMap.get("searchValue"));
		paramMap.put("key", paramMap.get("searchKey"));
		paramMap.put("value", searchValue);
		return myBatisDao.get("wifiSqlMapper.countByParamsAdvertiser", paramMap);
	}
	
	@Override
	public int countByParamsOperator(Map<String, Object> paramMap) {
		return myBatisDao.get("wifiSqlMapper.countByParamsOperator", paramMap);
	}

	@Override
	public List<Wifi> findByParams(Map<String, Object> paramMap, Pager pager) {
		String searchValue = SqlHelper.doLike(paramMap.get("searchValue"));
		paramMap.put("key", paramMap.get("searchKey"));
		paramMap.put("value", searchValue);
		paramMap.put("pager", pager);
		return myBatisDao.getList("wifiSqlMapper.selectByParams", paramMap);
	}
	
	@Override
	public List<Wifi> findByParamsOperator(Map<String, Object> paramMap, Pager pager) {
		paramMap.put("pager", pager);
		return myBatisDao.getList("wifiSqlMapper.findByParams", paramMap);
	}

	@Override
	public boolean add(Wifi t) {
		myBatisDao.save("wifiSqlMapper.add", t);
		return true;
	}

	@Override
	public boolean edit(Wifi t) {
		myBatisDao.save("wifiSqlMapper.editWifi", t);
		return true;
	}

	@Override
	public boolean updateStatus(List<Long> idList, int status) {
		myBatisDao.save("wifiSqlMapper.updateWifiStatus",MapBuilder.create(HashMap.class)
				.add("status", status)
				.add("idList", idList)
				.add("updated", new Date())
				.map());
		return true;
	}
	
	public boolean deleteWifi(Long adGroupId) {
		//删除之前保存的wifi热点
		myBatisDao.delete("wifiSqlMapper.deleteAdgroupWifi", adGroupId);
		return true;
	}
	//将选择的wifi热点保存到数据库t_adgroup_wifi里面
	public void front2dbwifi(String str,Long adGroupId) {
		HashMap<String, Object> map = new HashMap<String, Object>();
		if(null != str) {
			String[] strArr = str.split(",");
			for(int i = 0; i < strArr.length; i++) {
				Long wifiId = Long.valueOf(strArr[i]).longValue();
				map.put("adGroupId", adGroupId);
				map.put("wifiId", wifiId);
				myBatisDao.get("wifiSqlMapper.addAdgroupWifi", map);
			}
		}
	}

	@Override
	public List<Wifi> findByParams(Map<String, Object> paramMap) {
		return myBatisDao.getList("wifiSqlMapper.findByParams1", paramMap);
	}
	@Override
	public int countByParamsBack(Map<String, Object> paramMap) {
		// 按mac地址搜索
		if (null != paramMap.get("searchValue")
				&& !"".equals(paramMap.get("searchValue"))) {
			String name = (String) paramMap.get("searchValue");
			paramMap.put("mac", SqlHelper.doLike(name.trim()));
		} else {
			paramMap.put("mac", null);
		}
		return myBatisDao.get("wifiSqlMapper.countByParamsBack", paramMap);
	}
	@Override
	public List<Wifi> findByParamsBack(Map<String, Object> paramMap, Pager pager) {
		// 按mac地址搜索
		if (null != paramMap.get("searchValue")
				&& !"".equals(paramMap.get("searchValue"))) {
			String name = (String) paramMap.get("searchValue");
			paramMap.put("mac", SqlHelper.doLike(name.trim()));
		} else {
			paramMap.put("mac", null);
		}
		paramMap.put("pager", pager);
		return myBatisDao.getList("wifiSqlMapper.findByParamsBack", paramMap);
	}
	@Override
	public List<Wifi> findByParamsBack(Map<String, Object> paramMap) {
		return myBatisDao.getList("wifiSqlMapper.findByParams1Back", paramMap);
	}
	@Override
	public int countWifiGroupByCondition(Map<String, Object> paramMap) {
		return myBatisDao.get("wifiSqlMapper.queryWifiGroupCount", paramMap);
	}
	@Override
	public List<WifiPojo> queryWifiGroupByCondition(Map<String, Object> paramMap, Pager pager) {
		paramMap.put("pager", pager);
		return myBatisDao.getList("wifiSqlMapper.queryWifiGroup", paramMap);
	}
	@Override
	public int queryWifiCountByCondition(Map<String, Object> condition) {
		return myBatisDao.get("wifiSqlMapper.queryWifiGroupCount", condition);
	}
	@Override
	public List<WifiPojo> queryWifiByCondition(Map<String, Object> condition,Pager pager) {
		condition.put("pager", pager);
		return myBatisDao.getList("wifiSqlMapper.queryWifiGroup", condition);
	}
	@Override
	public int findWifiCountByCondition(Map<String, Object> condition) {
		return myBatisDao.get("wifiSqlMapper.queryWifiCountByCondition", condition);
	}
	@Override
	public List<Wifi> findWifiByCondition(Map<String, Object> condition,Pager pager) {
		condition.put("pager", pager);
		return myBatisDao.getList("wifiSqlMapper.queryWifiByCondition", condition);
	}
	
	
	
}
